GCC(1)
๐ gcc(1) โ GNU ๐
okay so welcome to the manual page for the GNU project's C and C++ compiler. It's a lot, bestie, but we're doing this together and we're doing it thoroughly ๐
๐ธ NAME ๐ธ
gccโ GNU project C and C++ compiler ๐
๐ฆ SYNOPSIS ๐ฆ
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
real talk: only the most useful options are listed here; see below for the remainder. And g++ accepts mostly the same options as gcc ๐ซถ
โจ DESCRIPTION โจ
okay so when you invoke GCC, it normally does preprocessing, compilation, assembly and linking โ the full pipeline, the whole glow-up. The "overall options" let you stop this process at an intermediate stage. For example, the -c option says not to run the linker. Then the output consists of object files output by the assembler. ๐
Other options are passed on to one or more stages of processing. Some options control the preprocessor and others the compiler itself. Yet other options control the assembler and linker; most of these are not documented here, since you rarely need to use any of them. (iykyk)
Most of the command-line options that you can use with GCC are useful for C programs; when an option is only useful with another language (usually C++), the explanation says so explicitly. If the description for a particular option does not mention a source language, you can use that option with all supported languages. ๐
The usual way to run GCC is to run the executable called gcc, or machine-gcc when cross-compiling, or machine-gcc-version to run a specific version of GCC. When you compile C++ programs, you should invoke GCC as g++ instead. ๐
The gcc program accepts options and file names as operands. Many options have multi-letter names; therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. ๐จ
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant. โญ
Many options have long names starting with -f or -W---for example, -fmove-loop-invariants, -Wformat and so on. Most of these have both positive and negative forms; the negative form of -ffoo is -fno-foo. This manual documents only one of these two forms, whichever one is not the default. ๐
Some options take one or more arguments typically separated either by a space or by the equals sign (=) from the option name. Unless documented otherwise, an argument can be either numeric or a string. Numeric arguments must typically be small unsigned decimal or hexadecimal integers. Hexadecimal arguments must begin with the 0x prefix. Arguments to options that specify a size threshold of some sort may be arbitrarily large decimal or hexadecimal integers followed by a byte size suffix designating a multiple of bytes such as "kB" and "KiB" for kilobyte and kibibyte, respectively, "MB" and "MiB" for megabyte and mebibyte, "GB" and "GiB" for gigabyte and gibibyte, and so on. Such arguments are designated by byte-size in the following text. Refer to the NIST, IEC, and other relevant national and international standards for the full listing and explanation of the binary and decimal byte size prefixes. ๐
๐ OPTIONS ๐
๐ Option Summary ๐
Here is a summary of all the options, grouped by type. Explanations are in the following sections.
๐ฏ Overall Options
-c-S-E-o file-dumpbase dumpbase-dumpbase-ext auxdropsuf-dumpdir dumppfx-x language-v-###--help[=class[,...]]--target-help--version-pass-exit-codes-pipe-specs=file-wrapper @file-ffile-prefix-map=old=new-fplugin=file-fplugin-arg-name=arg-fdump-ada-spec[-slim]-fada-spec-parent=unit-fdump-go-spec=file
๐ C Language Options
-ansi-std=standard-aux-info filename-fallow-parameterless-variadic-functions-fno-asm-fno-builtin-fno-builtin-function-fcond-mismatch-ffreestanding-fgimple-fgnu-tm-fgnu89-inline-fhosted-flax-vector-conversions-fms-extensions-foffload=arg-foffload-options=arg-fopenacc-fopenacc-dim=geom-fopenmp-fopenmp-simd-fpermitted-flt-eval-methods=standard-fplan9-extensions-fsigned-bitfields-funsigned-bitfields-fsigned-char-funsigned-char-fsso-struct=endianness
๐ C++ Language Options
-fabi-version=n-fno-access-control-faligned-new=n-fargs-in-order=n-fchar8_t-fcheck-new-fconstexpr-depth=n-fconstexpr-cache-depth=n-fconstexpr-loop-limit=n-fconstexpr-ops-limit=n-fno-elide-constructors-fno-enforce-eh-specs-fno-gnu-keywords-fno-implicit-templates-fno-implicit-inline-templates-fno-implement-inlines-fmodule-header[=kind]-fmodule-only-fmodules-ts-fmodule-implicit-inline-fno-module-lazy-fmodule-mapper=specification-fmodule-version-ignore-fms-extensions-fnew-inheriting-ctors-fnew-ttp-matching-fno-nonansi-builtins-fnothrow-opt-fno-operator-names-fno-optional-diags-fpermissive-fno-pretty-templates-fno-rtti-fsized-deallocation-ftemplate-backtrace-limit=n-ftemplate-depth=n-fno-threadsafe-statics-fuse-cxa-atexit-fno-weak-nostdinc++-fvisibility-inlines-hidden-fvisibility-ms-compat-fext-numeric-literals-flang-info-include-translate[=header]-flang-info-include-translate-not-flang-info-module-cmi[=module]-stdlib=libstdc++,libc++-Wabi-tag-Wcatch-value-Wcatch-value=n-Wno-class-conversion-Wclass-memaccess-Wcomma-subscript-Wconditionally-supported-Wno-conversion-null-Wctad-maybe-unsupported-Wctor-dtor-privacy-Wno-delete-incomplete-Wdelete-non-virtual-dtor-Wno-deprecated-array-compare-Wdeprecated-copy-Wdeprecated-copy-dtor-Wno-deprecated-enum-enum-conversion-Wno-deprecated-enum-float-conversion-Weffc++-Wno-exceptions-Wextra-semi-Wno-inaccessible-base-Wno-inherited-variadic-ctor-Wno-init-list-lifetime-Winvalid-imported-macros-Wno-invalid-offsetof-Wno-literal-suffix-Wmismatched-new-delete-Wmismatched-tags-Wmultiple-inheritance-Wnamespaces-Wnarrowing-Wnoexcept-Wnoexcept-type-Wnon-virtual-dtor-Wpessimizing-move-Wno-placement-new-Wplacement-new=n-Wrange-loop-construct-Wredundant-move-Wredundant-tags-Wreorder-Wregister-Wstrict-null-sentinel-Wno-subobject-linkage-Wtemplates-Wno-non-template-friend-Wold-style-cast-Woverloaded-virtual-Wno-pmf-conversions-Wsign-promo-Wsized-deallocation-Wsuggest-final-methods-Wsuggest-final-types-Wsuggest-override-Wno-terminate-Wuseless-cast-Wno-vexing-parse-Wvirtual-inheritance-Wno-virtual-move-assign-Wvolatile-Wzero-as-null-pointer-constant
๐ Objective-C and Objective-C++ Language Options
-fconstant-string-class=class-name-fgnu-runtime-fnext-runtime-fno-nil-receivers-fobjc-abi-version=n-fobjc-call-cxx-cdtors-fobjc-direct-dispatch-fobjc-exceptions-fobjc-gc-fobjc-nilcheck-fobjc-std=objc1-fno-local-ivars-fivar-visibility=[public|protected|private|package]-freplace-objc-classes-fzero-link-gen-decls-Wassign-intercept-Wno-property-assign-default-Wno-protocol-Wobjc-root-class-Wselector-Wstrict-selector-match-Wundeclared-selector
๐ Diagnostic Message Formatting Options
-fmessage-length=n-fdiagnostics-plain-output-fdiagnostics-show-location=[once|every-line]-fdiagnostics-color=[auto|never|always]-fdiagnostics-urls=[auto|never|always]-fdiagnostics-format=[text|json]-fno-diagnostics-show-option-fno-diagnostics-show-caret-fno-diagnostics-show-labels-fno-diagnostics-show-line-numbers-fno-diagnostics-show-cwe-fdiagnostics-minimum-margin-width=width-fdiagnostics-parseable-fixits-fdiagnostics-generate-patch-fdiagnostics-show-template-tree-fno-elide-type-fdiagnostics-path-format=[none|separate-events|inline-events]-fdiagnostics-show-path-depths-fno-show-column-fdiagnostics-column-unit=[display|byte]-fdiagnostics-column-origin=origin-fdiagnostics-escape-format=[unicode|bytes]
okay bestie, that's the index handled โ the actual deep dives on every single one of these are literally right there in the following sections, and we are not skipping a single one ๐
๐จ Warning Options ๐จ
okay bestie, hydrate ๐, sit down, put your phone on silent โ this is the list. every warning-adjacent flag GCC has, in order, no cuts, no skipping, no "you get the idea" โจ. I'm obsessed with how thorough she is. it's giving completionist queen and I respect it ๐
-fsyntax-onlyโ the low-commitment icon ๐-fmax-errors=nโ n is a number and you're picking it, bestie ๐ข-Wpedanticโ hall monitor energy, and honestly? valid ๐-pedantic-errorsโ same girl but she's serious this time ๐-wโ one lowercase letter and she is silence itself ๐คซ-Wextraโ extra. as advertised. more is more โจ-Wallโ THE blueprint, the icon, the moment, the legend ๐-Wabi=nโ n again. she's always in the details-Waddressโ address drama, we've all been there-Wno-address-of-packed-memberโ no-prefix era, off duty ๐-Waggregate-returnโ returns, but make them aggregate-Walloc-size-larger-than=byte-sizeโ byte-size, the units matter ๐-Walloc-zeroโ zero. chill? also zero.-Wallocaโ alloca! say her name! ๐ฃ๏ธ-Walloca-larger-than=byte-sizeโ the alloca crossover episode, now with a byte-size limit-Wno-aggressive-loop-optimizationsโ not aggressive today, she's mellowing ๐ง-Warith-conversionโ arithmetic conversions, the plot twist-Warray-boundsโ bounds! stay in them!-Warray-bounds=nโ same energy, n dial included ๐๏ธ-Warray-compareโ comparing arrays. the audacity ๐ณ-Wno-attributesโ attributes? not today-Wattribute-alias=nโ alias plus n, don't forget her-Wno-attribute-aliasโ the no-prefix twin, love her-Wno-attribute-warningโ no-prefix, still iconic-Wbidi-chars=[none|unpaired|any|ucn]โ four flavours:none,unpaired,any,ucn. pick your fighter ๐-Wbool-compareโ booleans doing comparisons, messy-Wbool-operationโ booleans doing operations, messier-Wno-builtin-declaration-mismatchโ the no-prefix diva-Wno-builtin-macro-redefinedโ also no-prefix, also diva-Wc90-c99-compatโ the C90-to-C99 era, a period piece ๐๏ธ-Wc99-c11-compatโ C99 to C11, the sequel-Wc11-c2x-compatโ C11 to C2x, the threequel-Wc++-compatโ C++ compat, she's multilingual ๐-Wc++11-compatโ C++11 edition-Wc++14-compatโ C++14 edition-Wc++17-compatโ C++17 edition-Wc++20-compatโ C++20 edition-Wno-c++11-extensionsโ no-prefix, C++11 flavour-Wno-c++14-extensionsโ no-prefix, C++14 flavour-Wno-c++17-extensionsโ no-prefix, C++17 flavour-Wno-c++20-extensionsโ no-prefix, C++20 flavour-Wno-c++23-extensionsโ no-prefix, C++23 flavour (she's new here โจ)-Wcast-alignโ casts and alignment, the classic duo-Wcast-align=strictโ same but she said strict and meant it ๐ฅ-Wcast-function-typeโ casting function types, spicy-Wcast-qualโ quals getting cast, rude-Wchar-subscriptsโ subscripts! on chars!-Wclobberedโ something got clobbered, we're all fine ๐ญ-Wcommentโ comments, scrutinized-Wconversionโ conversions, under a microscope ๐ฌ-Wno-coverage-mismatchโ no-prefix, coverage edition-Wno-cppโ no-prefix, cpp edition-Wdangling-elseโ the dangling else, a true cliffhanger-Wdangling-pointerโ dangling pointer, the thriller-Wdangling-pointer=nโ same thriller, n setting-Wdate-timeโ date and time, timestamped ๐-Wno-deprecatedโ no-prefix, deprecated edition-Wno-deprecated-declarationsโ no-prefix, declarations edition-Wno-designated-initโ no-prefix, designated init edition-Wdisabled-optimizationโ optimization got disabled, gossip ๐๏ธ-Wno-discarded-array-qualifiersโ no-prefix, array qualifiers edition-Wno-discarded-qualifiersโ no-prefix, qualifiers edition-Wno-div-by-zeroโ no-prefix, division edition-Wdouble-promotionโ double promotion, she got promoted twice ๐-Wduplicated-branchesโ twin branches, matching outfits-Wduplicated-condโ twin conditions, also matching-Wempty-bodyโ empty body, no thoughts head empty-Wno-endif-labelsโ no-prefix, endif edition-Wenum-compareโ enums comparing, awkward-Wenum-conversionโ enums converting, even more awkward-Werrorโ the one that turns everything into a whole situation ๐-Werror=*โ same, but with a wildcard, she's flexible-Wexpansion-to-definedโ expansions becoming defined, a glow-up-Wfatal-errorsโ fatal! dramatic! love that for her ๐-Wfloat-conversionโ floats converting, floating along ๐ฆ-Wfloat-equalโ floats being equal, bold of you-Wformatโ format. the classic. the blueprint.-Wformat=2โ format, but level 2, she leveled up โญ-Wno-format-contains-nulโ no-prefix, nul edition-Wno-format-extra-argsโ no-prefix, extra args edition-Wformat-nonliteralโ nonliteral formats, mysterious-Wformat-overflow=nโ overflow with an n setting ๐-Wformat-securityโ security, she's taking it seriously ๐-Wformat-signednessโ signedness, the little detail that matters-Wformat-truncation=nโ truncation, n edition โ๏ธ-Wformat-y2kโ y2k. throwback. nostalgia unlocked ๐ฐ๏ธ-Wframe-addressโ frame address, very architectural-Wframe-larger-than=byte-sizeโ byte-size limit on frames, measurements matter ๐-Wno-free-nonheap-objectโ no-prefix, free edition-Wno-if-not-alignedโ no-prefix, alignment edition-Wno-ignored-attributesโ no-prefix, attributes edition-Wignored-qualifiersโ qualifiers got ignored. rude. ๐-Wno-incompatible-pointer-typesโ no-prefix, pointers edition-Wimplicitโ implicit everything, she's indirect-Wimplicit-fallthroughโ fallthrough! say it with your chest ๐ฃ๏ธ-Wimplicit-fallthrough=nโ fallthrough with an n, levels to this-Wno-implicit-function-declarationโ no-prefix, function declaration edition-Wno-implicit-intโ no-prefix, int edition-Winfinite-recursionโ recursion that never ends, literally never ends โพ๏ธ-Winit-selfโ self-init, she's independent-Winlineโ inlining discourse, we love to see it-Wno-int-conversionโ no-prefix, int edition-Wint-in-bool-contextโ ints in bool context, fish out of water ๐-Wno-int-to-pointer-castโ no-prefix, cast edition-Wno-invalid-memory-modelโ no-prefix, memory model edition-Winvalid-pchโ pch drama, and it's invalid ๐ฌ-Wjump-misses-initโ jumps missing init, parkour fail-Wlarger-than=byte-sizeโ bigger than byte-size, she's measuring ๐-Wlogical-not-parenthesesโ logical not plus parentheses, the duo ๐ญ-Wlogical-opโ logical ops, very logical of her-Wlong-longโ long long. she's long. twice. ๐-Wno-lto-type-mismatchโ no-prefix, lto edition-Wmainโ main character energy, obviously ๐-Wmaybe-uninitializedโ maybe uninitialized, she's keeping it vague-Wmemset-elt-sizeโ memset elt size, very specific, love the precision-Wmemset-transposed-argsโ args got transposed, oopsie-Wmisleading-indentationโ misleading indentation, the betrayal ๐ฑ-Wmissing-attributesโ attributes went missing, have you seen them-Wmissing-bracesโ braces went missing, so did they-Wmissing-field-initializersโ field initializers, also missing-Wmissing-format-attributeโ format attribute, missing too-Wmissing-include-dirsโ include dirs, missing, a whole trend-Wmissing-noreturnโ noreturn, missing, ironically returns-Wno-missing-profileโ no-prefix, profile edition-Wno-multicharโ no-prefix, multichar edition-Wmultistatement-macrosโ macros with multiple statements, multitasking queen ๐-Wnonnullโ nonnull, she said what she said-Wnonnull-compareโ nonnull comparisons, comparing the incomparable-Wnormalized=[none|id|nfc|nfkc]โ four modes:none,id,nfc,nfkc. choose your destiny ๐-Wnull-dereferenceโ dereferencing null, we do not do that here ๐ซ-Wno-odrโ no-prefix, odr edition-Wopenacc-parallelismโ openacc parallelism, she's parallel โจ-Wopenmp-simdโ openmp simd, she's vectorized-Wno-overflowโ no-prefix, overflow edition-Woverlength-stringsโ strings that are too long, she's wordy-Wno-override-init-side-effectsโ no-prefix, side effects edition-Wpackedโ packed! compact! efficient! ๐-Wno-packed-bitfield-compatโ no-prefix, bitfield edition-Wpacked-not-alignedโ packed but not aligned, a situationship-Wpaddedโ padded, she's got cushioning ๐๏ธ-Wparenthesesโ parentheses discourse, always-Wno-pedantic-ms-formatโ no-prefix, ms format edition-Wpointer-arithโ pointer arithmetic, math but make it pointers ๐งฎ-Wno-pointer-compareโ no-prefix, pointer edition-Wno-pointer-to-int-castโ no-prefix, int cast edition-Wno-pragmasโ no-prefix, pragma edition-Wno-prio-ctor-dtorโ no-prefix, ctor/dtor edition-Wredundant-declsโ redundant declarations, saying it twice-Wrestrictโ restrict! boundaries! respect! ๐-Wno-return-local-addrโ no-prefix, local address edition-Wreturn-typeโ return types, she cares about them-Wno-scalar-storage-orderโ no-prefix, storage order edition-Wsequence-pointโ sequence points, the plot structure-Wshadowโ shadowing, mysterious and moody ๐-Wshadow=globalโ shadowing, global scope edition ๐-Wshadow=localโ shadowing, local scope edition ๐-Wshadow=compatible-localโ shadowing, compatible-local edition ๐ค-Wno-shadow-ivarโ no-prefix, ivar edition-Wno-shift-count-negativeโ no-prefix, negative shift edition-Wno-shift-count-overflowโ no-prefix, shift overflow edition-Wshift-negative-valueโ shifting a negative value, bold move-Wno-shift-overflowโ no-prefix, shift overflow edition (the other one)-Wshift-overflow=nโ shift overflow with an n dial ๐๏ธ-Wsign-compareโ comparing signs, star signs? no, the other kind-Wsign-conversionโ sign conversion, converting signs โจ-Wno-sizeof-array-argumentโ no-prefix, sizeof edition-Wsizeof-array-divโ sizeof with array division, math girlie ๐-Wsizeof-pointer-divโ sizeof with pointer division, also math-Wsizeof-pointer-memaccessโ sizeof pointer memaccess, very specific-Wstack-protectorโ stack protector, she's protecting the stack ๐ก๏ธ-Wstack-usage=byte-sizeโ stack usage in byte-size, measured ๐-Wstrict-aliasingโ strict aliasing, she has standards-Wstrict-aliasing=nโ strict aliasing, level n ๐ฅ-Wstrict-overflowโ strict overflow, no mess-Wstrict-overflow=nโ strict overflow, level n ๐ฅ-Wstring-compareโ string comparisons, comparing strings-Wno-stringop-overflowโ no-prefix, stringop overflow edition-Wno-stringop-overreadโ no-prefix, stringop overread edition-Wno-stringop-truncationโ no-prefix, stringop truncation edition-Wsuggest-attribute=[pure|const|noreturn|format|malloc]โ five flavours:pure,const,noreturn,format,malloc. she's suggesting ๐ซถ-Wswitchโ switch! flip it! ๐-Wno-switch-boolโ no-prefix, switch bool edition-Wswitch-defaultโ switch default, the default option-Wswitch-enumโ switch enum, enum edition-Wno-switch-outside-rangeโ no-prefix, out-of-range edition-Wno-switch-unreachableโ no-prefix, unreachable edition-Wsync-nandโ sync nand, very specific, very iconic-Wsystem-headersโ system headers, the system is involved ๐ฅ๏ธ-Wtautological-compareโ tautological comparisons, saying the same thing twice-Wtrampolinesโ trampolines! bouncing! fun! ๐คธ-Wtrigraphsโ trigraphs, a relic, a legend ๐บ-Wtrivial-auto-var-initโ trivial auto var init, trivial but cute-Wtsanโ tsan, she's threading ๐งต-Wtype-limitsโ type limits, she knows her limits-Wundefโ undef, undefined, mysterious ๐ซ๏ธ-Wuninitializedโ uninitialized, she woke up like this-Wunknown-pragmasโ unknown pragmas, mystery pragmas ๐ต๏ธ-Wunsuffixed-float-constantsโ float constants with no suffix, she's raw-Wunusedโ unused! she noticed! she always notices ๐-Wunused-but-set-parameterโ a parameter set but not used, tragic arc-Wunused-but-set-variableโ same story, variable edition-Wunused-const-variableโ a const variable, unused, crying-Wunused-const-variable=nโ same, with an n setting-Wunused-functionโ a function, unused, unemployed-Wunused-labelโ a label, unused, unlabeled-Wunused-local-typedefsโ local typedefs, unused, local-Wunused-macrosโ macros, unused, macro-depressed-Wunused-parameterโ parameters, unused, param-sad-Wno-unused-resultโ no-prefix, result edition-Wunused-valueโ values, unused, value-less-Wunused-variableโ variables, unused, the whole saga-Wno-varargsโ no-prefix, varargs edition-Wvariadic-macrosโ variadic macros, she contains multitudes โจ-Wvector-operation-performanceโ vector operation performance, she's fast ๐๏ธ-Wvlaโ vla! variable length arrays! say it! ๐ฃ-Wvla-larger-than=byte-sizeโ vla bigger than byte-size, measurements again ๐-Wno-vla-larger-thanโ no-prefix, vla edition-Wvolatile-register-varโ volatile register var, chaotic combo ๐ฅ-Wwrite-stringsโ write strings, she writes โ๏ธ-Wzero-length-boundsโ zero-length bounds, empty but bounded
that's the whole roster. no skips. no shortcuts. she's thorough and we love her for it ๐ซถ
๐ต๏ธ Static Analyzer Options ๐ต๏ธ
okay so this next batch is the detective division ๐. these are the flags that hang out with the static analyzer โ the part of GCC that stares at your code like she's reading your texts. full list, bestie, no edits ๐
-fanalyzerโ the main character of this whole section ๐-fanalyzer-call-summariesโ call summaries, she takes notes ๐-fanalyzer-checker=nameโ you pass a name, she runs that checker ๐-fno-analyzer-feasibilityโ thefno-version, she's off-fanalyzer-fine-grainedโ fine-grained, delicate, precise โจ-fno-analyzer-state-mergeโ no merge today-fno-analyzer-state-purgeโ no purge today-fanalyzer-transitivityโ transitivity, the transitive property but make it analysis-fanalyzer-verbose-edgesโ verbose edges, chatty graph ๐-fanalyzer-verbose-state-changesโ verbose state changes, even chattier-fanalyzer-verbosity=levelโ level controls the yapping volume ๐-fdump-analyzerโ dump it, bestie ๐๏ธ-fdump-analyzer-callgraphโ dump the callgraph-fdump-analyzer-exploded-graphโ dump the exploded graph ๐ฅ-fdump-analyzer-exploded-nodesโ dump the exploded nodes-fdump-analyzer-exploded-nodes-2โ dump them again, part two-fdump-analyzer-exploded-nodes-3โ and part three, she's committed ๐ฌ-fdump-analyzer-exploded-pathsโ dump the exploded paths-fdump-analyzer-feasibilityโ dump the feasibility-fdump-analyzer-jsonโ dump it as json ๐ฆ-fdump-analyzer-state-purgeโ dump the state purge-fdump-analyzer-stderrโ dump to stderr, she's going to the error stream ๐ข-fdump-analyzer-supergraphโ dump the supergraph, very superhero ๐ฆธ-fdump-analyzer-untrackedโ dump the untracked, she lost track of them-Wno-analyzer-double-fcloseโ no-prefix, double fclose edition-Wno-analyzer-double-freeโ no-prefix, double free edition-Wno-analyzer-exposure-through-output-fileโ no-prefix, output-file exposure edition-Wno-analyzer-file-leakโ no-prefix, file leak edition-Wno-analyzer-free-of-non-heapโ no-prefix, non-heap free edition-Wno-analyzer-malloc-leakโ no-prefix, malloc leak edition-Wno-analyzer-mismatching-deallocationโ no-prefix, mismatching deallocation edition-Wno-analyzer-null-argumentโ no-prefix, null argument edition-Wno-analyzer-null-dereferenceโ no-prefix, null dereference edition-Wno-analyzer-possible-null-argumentโ no-prefix, possible null argument edition-Wno-analyzer-possible-null-dereferenceโ no-prefix, possible null dereference edition-Wno-analyzer-shift-count-negativeโ no-prefix, negative shift count edition-Wno-analyzer-shift-count-overflowโ no-prefix, shift count overflow edition-Wno-analyzer-stale-setjmp-bufferโ no-prefix, stale setjmp buffer edition-Wno-analyzer-tainted-allocation-sizeโ no-prefix, tainted allocation size edition ๐ฆ-Wno-analyzer-tainted-array-indexโ no-prefix, tainted array index edition-Wno-analyzer-tainted-divisorโ no-prefix, tainted divisor edition-Wno-analyzer-tainted-offsetโ no-prefix, tainted offset edition-Wno-analyzer-tainted-sizeโ no-prefix, tainted size edition-Wanalyzer-too-complexโ too complex! she said it! she's overwhelmed ๐ต-Wno-analyzer-unsafe-call-within-signal-handlerโ no-prefix, signal handler edition-Wno-analyzer-use-after-freeโ no-prefix, use after free edition-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ no-prefix, stale stack frame edition-Wno-analyzer-use-of-uninitialized-valueโ no-prefix, uninitialized value edition-Wno-analyzer-write-to-constโ no-prefix, write to const edition-Wno-analyzer-write-to-string-literalโ no-prefix, string literal edition
detective work: complete. ๐ she found everything and she wrote it all down ๐ซถ
๐ C and Objective-C-only Warning Options ๐
these ones are exclusive โ C and Objective-C only, bestie. no C++, no other languages, just the two of them ๐
-Wbad-function-castโ a cast that's being bad ๐-Wmissing-declarationsโ declarations, missing, again-Wmissing-parameter-typeโ parameter types, also missing-Wmissing-prototypesโ prototypes, missing, a whole pattern-Wnested-externsโ nested externs, nested like matryoshka ๐ช-Wold-style-declarationโ old-style declarations, vintage ๐บ-Wold-style-definitionโ old-style definitions, also vintage-Wstrict-prototypesโ strict prototypes, she has standards-Wtraditionalโ traditional, she's classic ๐-Wtraditional-conversionโ traditional conversion, classic edition-Wdeclaration-after-statementโ declarations after statements, she has opinions on ordering-Wpointer-signโ pointer signs, she's pointing ๐
๐ Debugging Options ๐
and finally, bestie, the debug era ๐. every -g and friend, all of them, exactly as she wrote them. this is the part where GCC puts on her little detective hat and tells you what your code was actually doing at 3am ๐ต๏ธ๐
-gโ the original. the blueprint. the moment ๐-glevelโ level controls how much she tells you ๐ถ-gdwarfโ dwarf format, fantasy vibes ๐ง-gdwarf-versionโ dwarf, but version picker-gbtfโ btf, three letters, mystery-gctfโ ctf, also three letters-gctflevelโ ctf plus a level, leveled up โญ-ggdbโ gdb-flavoured debug, she's gdb's bestie ๐ซถ-grecord-gcc-switchesโ record the switches, receipts kept ๐งพ-gno-record-gcc-switchesโ no receipts today-gstabsโ stabs! a classic! ๐ช (metaphorically)-gstabs+โ stabs but plus, extra sparkle โจ-gstrict-dwarfโ strict dwarf, no nonsense-gno-strict-dwarfโ chill dwarf, all nonsense-gas-loc-supportโ as loc support, supportive queen-gno-as-loc-supportโ unsupportive, sadly-gas-locview-supportโ as locview support, also supportive-gno-as-locview-supportโ also unsupportive-gcolumn-infoโ column info, she knows your column ๐งญ-gno-column-infoโ she does not know your column-gdwarf32โ dwarf 32, small and mighty-gdwarf64โ dwarf 64, big and mightier-gstatement-frontiersโ statement frontiers, she's exploring ๐บ๏ธ-gno-statement-frontiersโ no exploring today-gvariable-location-viewsโ variable location views, very geographic ๐-gno-variable-location-viewsโ no geography today-ginternal-reset-location-viewsโ internal reset, she reset it ๐-gno-internal-reset-location-viewsโ no reset-ginline-pointsโ inline points, points for inlining ๐ฏ-gno-inline-pointsโ no points-gvmsโ vms, three letters, vintage-gxcoffโ xcoff, x marks the spot-gxcoff+โ xcoff but plus, extra credit โจ-gz[=type]โ z for compressed, and type is optional ๐๏ธ-gsplit-dwarfโ split dwarf, she's divided-gdescribe-diesโ describe dies, she's describing-gno-describe-diesโ no describing-fdebug-prefix-map=old=newโ maps old to new, a little remix ๐ง-fdebug-types-sectionโ types section, very sectioned-fno-eliminate-unused-debug-typesโ no eliminating today-femit-struct-debug-baseonlyโ emit struct debug, baseonly flavour-femit-struct-debug-reducedโ emit struct debug, reduced flavour-femit-struct-debug-detailed[=spec-list]โ emit struct debug, detailed flavour, with an optional spec-list ๐-fno-eliminate-unused-debug-symbolsโ no eliminating symbols either-femit-class-debug-alwaysโ always emit class debug, she's committed ๐-fno-merge-debug-stringsโ no merging today-fno-dwarf2-cfi-asmโ no dwarf2 cfi asm today-fvar-trackingโ var tracking, she's following the variables ๐-fvar-tracking-assignmentsโ var tracking assignments, the sequel
and that's the debugging era. she will tell you everything ๐๐ซถ
๐ Optimization Options ๐
okay bestie, deep breath, because this is the list. this is the one. every optimization flag GCC has, rolled out in one glorious line like the world's longest group chat roster. you are not expected to memorize this. you are expected to scroll, nod, and feel something. ๐
(these are just the roll call โ the actual explanations live in the pages that follow, so don't panic if a name looks like a keyboard smash. it's not. probably.)
-faggressive-loop-optimizations,-falign-functions[=n[:m:[n2[:m2]]]],-falign-jumps[=n[:m:[n2[:m2]]]],-falign-labels[=n[:m:[n2[:m2]]]],-falign-loops[=n[:m:[n2[:m2]]]],-fno-allocation-dce,-fallow-store-data-races,-fassociative-math,-fauto-profile,-fauto-profile[=path]-fauto-inc-dec,-fbranch-probabilities,-fcaller-saves,-fcombine-stack-adjustments,-fconserve-stack,-fcompare-elim,-fcprop-registers,-fcrossjumping,-fcse-follow-jumps,-fcse-skip-blocks,-fcx-fortran-rules,-fcx-limited-range-fdata-sections,-fdce,-fdelayed-branch,-fdelete-null-pointer-checks,-fdevirtualize,-fdevirtualize-speculatively,-fdevirtualize-at-ltrans,-fdse,-fearly-inlining,-fipa-sra,-fexpensive-optimizations-ffat-lto-objects,-ffast-math,-ffinite-math-only,-ffloat-store,-fexcess-precision=style,-ffinite-loops,-fforward-propagate,-ffp-contract=style,-ffunction-sections,-fgcse,-fgcse-after-reload,-fgcse-las,-fgcse-lm,-fgraphite-identity,-fgcse-sm-fhoist-adjacent-loads,-fif-conversion,-fif-conversion2,-findirect-inlining,-finline-functions,-finline-functions-called-once,-finline-limit=n,-finline-small-functions- the
-fipa-*family reunion (they're all here, every single cousin):-fipa-modref,-fipa-cp,-fipa-cp-clone,-fipa-bit-cp,-fipa-vrp,-fipa-pta,-fipa-profile,-fipa-pure-const,-fipa-reference,-fipa-reference-addressable,-fipa-stack-alignment,-fipa-icf -fira-algorithm=algorithm,-flive-patching=level,-fira-region=region,-fira-hoist-pressure,-fira-loop-pressure,-fno-ira-share-save-slots,-fno-ira-share-spill-slots,-fisolate-erroneous-paths-dereference,-fisolate-erroneous-paths-attribute,-fivopts,-fkeep-inline-functions,-fkeep-static-functions,-fkeep-static-consts,-flimit-function-alignment,-flive-range-shrinkage- the loop girlies ๐ธ:
-floop-block,-floop-interchange,-floop-strip-mine,-floop-unroll-and-jam,-floop-nest-optimize,-floop-parallelize-all,-flra-remat,-flto,-flto-compression-level,-flto-partition=alg,-fmerge-all-constants,-fmerge-constants,-fmodulo-sched,-fmodulo-sched-allow-regmoves,-fmove-loop-invariants,-fmove-loop-stores - the
-fno-*committee has entered the chat, and they are very serious:-fno-branch-count-reg,-fno-defer-pop,-fno-fp-int-builtin-inexact,-fno-function-cse,-fno-guess-branch-probability,-fno-inline,-fno-math-errno,-fno-peephole,-fno-peephole2,-fno-printf-return-value,-fno-sched-interblock,-fno-sched-spec,-fno-signed-zeros,-fno-toplevel-reorder,-fno-trapping-math,-fno-zero-initialized-in-bss -fomit-frame-pointer,-foptimize-sibling-calls,-fpartial-inlining,-fpeel-loops,-fpredictive-commoning,-fprefetch-loop-arrays,-fprofile-correction,-fprofile-use,-fprofile-use=path,-fprofile-partial-training,-fprofile-values,-fprofile-reorder-functions,-freciprocal-math,-free,-frename-registers-freorder-blocks,-freorder-blocks-algorithm=algorithm,-freorder-blocks-and-partition,-freorder-functions,-frerun-cse-after-loop,-freschedule-modulo-scheduled-loops,-frounding-math,-fsave-optimization-record,-fsched2-use-superblocks,-fsched-pressure,-fsched-spec-load,-fsched-spec-load-dangerous,-fsched-stalled-insns-dep[=n],-fsched-stalled-insns[=n]- the scheduling heuristics, aka the vibes-based decision makers:
-fsched-group-heuristic,-fsched-critical-path-heuristic,-fsched-spec-insn-heuristic,-fsched-rank-heuristic,-fsched-last-insn-heuristic,-fsched-dep-count-heuristic,-fschedule-fusion,-fschedule-insns,-fschedule-insns2,-fsection-anchors,-fselective-scheduling,-fselective-scheduling2,-fsel-sched-pipelining,-fsel-sched-pipelining-outer-loops -fsemantic-interposition,-fshrink-wrap,-fshrink-wrap-separate,-fsignaling-nans,-fsingle-precision-constant,-fsplit-ivs-in-unroller,-fsplit-loops,-fsplit-paths,-fsplit-wide-types,-fsplit-wide-types-early,-fssa-backprop,-fssa-phiopt,-fstdarg-opt,-fstore-merging,-fstrict-aliasing,-fipa-strict-aliasing,-fthread-jumps,-ftracer- okay the
-ftree-*situation is genuinely enormous, brace yourself:-ftree-bit-ccp,-ftree-builtin-call-dce,-ftree-ccp,-ftree-ch,-ftree-coalesce-vars,-ftree-copy-prop,-ftree-dce,-ftree-dominator-opts,-ftree-dse,-ftree-forwprop,-ftree-fre,-fcode-hoisting,-ftree-loop-if-convert,-ftree-loop-im,-ftree-phiprop,-ftree-loop-distribution,-ftree-loop-distribute-patterns,-ftree-loop-ivcanon,-ftree-loop-linear,-ftree-loop-optimize,-ftree-loop-vectorize,-ftree-parallelize-loops=n,-ftree-pre,-ftree-partial-pre,-ftree-pta,-ftree-reassoc,-ftree-scev-cprop,-ftree-sink,-ftree-slsr,-ftree-sra,-ftree-switch-conversion,-ftree-tail-merge,-ftree-ter,-ftree-vectorize,-ftree-vrp,-ftrivial-auto-var-init -funconstrained-commons,-funit-at-a-time,-funroll-all-loops,-funroll-loops,-funsafe-math-optimizations,-funswitch-loops,-fipa-ra,-fvariable-expansion-in-unroller,-fvect-cost-model,-fvpt,-fweb,-fwhole-program,-fwpa,-fuse-linker-plugin,-fzero-call-used-regs- and nowโฆ the moment you've all been waiting for, the icons themselves ๐:
--param name=value,-O,-O0,-O1,-O2,-O3,-Os,-Ofast,-Og,-Oz
๐ Program Instrumentation Options ๐
this is the "let's watch what the program is actually doing" section. coverage, profiling, sanitizers, stack guards, the whole surveillance situation. very demure, very mindful, very tracked.
-p,-pg,-fprofile-arcs,--coverage,-ftest-coverage,-fprofile-abs-path,-fprofile-dir=path,-fprofile-generate,-fprofile-generate=path,-fprofile-info-section,-fprofile-info-section=name,-fprofile-note=path,-fprofile-prefix-path=path,-fprofile-update=method,-fprofile-filter-files=regex,-fprofile-exclude-files=regex,-fprofile-reproducible=[multithreaded|parallel-runs|serial]- the sanitizer squad, keeping your undefined behaviour in check ๐ซถ:
-fsanitize=style,-fsanitize-recover,-fsanitize-recover=style,-fasan-shadow-offset=number,-fsanitize-sections=s1,s2,...,-fsanitize-undefined-trap-on-error,-fbounds-check -fcf-protection=[full|branch|return|none|check],-fharden-compares,-fharden-conditional-branches- stack protectors, aka the bodyguards:
-fstack-protector,-fstack-protector-all,-fstack-protector-strong,-fstack-protector-explicit,-fstack-check,-fstack-limit-register=reg,-fstack-limit-symbol=sym,-fno-stack-limit,-fsplit-stack -fvtable-verify=[std|preinit|none],-fvtv-counts,-fvtv-debug,-finstrument-functions,-finstrument-functions-exclude-function-list=sym,sym,...,-finstrument-functions-exclude-file-list=file,file,...,-fprofile-prefix-map=old=new
๐งช Preprocessor Options ๐งช
the before-times. everything that happens before your code even gets to be code. macros, includes, charset drama. iconic behaviour honestly.
-Aquestion=answer,-A-question[=answer],-C,-CC,-Dmacro[=defn],-dD,-dI,-dM,-dN,-dU-fdebug-cpp,-fdirectives-only,-fdollars-in-identifiers,-fexec-charset=charset,-fextended-identifiers,-finput-charset=charset,-flarge-source-files,-fmacro-prefix-map=old=new,-fmax-include-depth=depth,-fno-canonical-system-headers,-fpch-deps,-fpch-preprocess,-fpreprocessed,-ftabstop=width,-ftrack-macro-expansion,-fwide-exec-charset=charset,-fworking-directory-H,-imacros file,-include file,-M,-MD,-MF,-MG,-MM,-MMD,-MP,-MQ,-MT,-Mno-modules-no-integrated-cpp,-P,-pthread,-remap,-traditional,-traditional-cpp,-trigraphs,-Umacro,-undef,-Wp,option,-Xpreprocessor option
๐ง Assembler Options ๐ง
short and sweet, and honestly? respect. ๐
-Wa,option,-Xassembler option
๐ Linker Options ๐
where all your object files finally meet each other. this is the friendship ceremony. the linking. ๐
object-file-name,-fuse-ld=linker,-llibrary,-nostartfiles,-nodefaultlibs,-nolibc,-nostdlib-e entry,--entry=entry,-pie,-pthread,-r,-rdynamic,-s,-static,-static-pie-static-libgcc,-static-libstdc++,-static-libasan,-static-libtsan,-static-liblsan,-static-libubsan-shared,-shared-libgcc,-symbolic,-T script,-Wl,option,-Xlinker option,-u symbol,-z keyword
๐ Directory Options ๐
all the places GCC goes looking for things. it has a whole little map. ๐บ๏ธ
-Bprefix,-Idir,-I-,-idirafter dir,-imacros file,-imultilib dir,-iplugindir=dir,-iprefix file,-iquote dir,-isysroot dir,-isystem dir,-iwithprefix dir,-iwithprefixbefore dir,-Ldir-no-canonical-prefixes,--no-sysroot-suffix,-nostdinc,-nostdinc++,--sysroot=dir
๐งฌ Code Generation Options ๐งฌ
how the actual instructions get built. registers, exceptions, visibility, struct returns. the real machinery.
-fcall-saved-reg,-fcall-used-reg,-ffixed-reg,-fexceptions,-fnon-call-exceptions,-fdelete-dead-exceptions,-funwind-tables,-fasynchronous-unwind-tables,-fno-gnu-unique-finhibit-size-directive,-fcommon,-fno-ident,-fpcc-struct-return,-fpic,-fPIC,-fpie,-fPIE,-fno-plt,-fno-jump-tables,-fno-bit-tests-frecord-gcc-switches,-freg-struct-return,-fshort-enums,-fshort-wchar,-fverbose-asm,-fpack-struct[=n],-fleading-underscore,-ftls-model=model,-fstack-reuse=reuse_level,-ftrampolines,-ftrapv,-fwrapv,-fvisibility=[default|internal|hidden|protected],-fstrict-volatile-bitfields,-fsync-libcalls
๐ ๏ธ Developer Options ๐ ๏ธ
for when you're the one building the compiler. yes, that kind of developer. dumps, debug counters, pass disabling, all the behind-the-scenes drama. ๐ฌ
-dletters,-dumpspecs,-dumpmachine,-dumpversion,-dumpfullversion,-fcallgraph-info[=su,da],-fchecking,-fchecking=n,-fdbg-cnt-list,-fdbg-cnt=counter-value-list-fdisable-ipa-pass_name,-fdisable-rtl-pass_name,-fdisable-rtl-pass-name=range-list,-fdisable-tree-pass_name,-fdisable-tree-pass-name=range-list-fdump-debug,-fdump-earlydebug,-fdump-noaddr,-fdump-unnumbered,-fdump-unnumbered-links,-fdump-final-insns[=file],-fdump-ipa-all,-fdump-ipa-cgraph,-fdump-ipa-inline,-fdump-lang-all,-fdump-lang-switch,-fdump-lang-switch-options,-fdump-lang-switch-options=filename,-fdump-passes,-fdump-rtl-pass,-fdump-rtl-pass=filename,-fdump-statistics,-fdump-tree-all,-fdump-tree-switch,-fdump-tree-switch-options,-fdump-tree-switch-options=filename-fcompare-debug[=opts],-fcompare-debug-second,-fenable-kind-pass,-fenable-kind-pass=range-list,-fira-verbose=n,-flto-report,-flto-report-wpa,-fmem-report-wpa,-fmem-report,-fpre-ipa-mem-report,-fpost-ipa-mem-report-fopt-info,-fopt-info-options[=file],-fprofile-report,-frandom-seed=string,-fsched-verbose=n,-fsel-sched-verbose,-fsel-sched-dump-cfg,-fsel-sched-pipelining-verbose,-fstats,-fstack-usage,-ftime-report,-ftime-report-details,-fvar-tracking-assignments-toggle,-gtoggle-print-file-name=library,-print-libgcc-file-name,-print-multi-directory,-print-multi-lib,-print-multi-os-directory,-print-prog-name=program,-print-search-dirs,-Q,-print-sysroot,-print-sysroot-headers-suffix-save-temps,-save-temps=cwd,-save-temps=obj,-time[=file]
๐ฅ๏ธ Machine-Dependent Options ๐ฅ๏ธ
the part where it gets specific. your target architecture has opinions and it will share them.
AArch64 Options
-mabi=name,-mbig-endian,-mlittle-endian,-mgeneral-regs-only-mcmodel=tiny,-mcmodel=small,-mcmodel=large,-mstrict-align,-mno-strict-align,-momit-leaf-frame-pointer-mtls-dialect=desc,-mtls-dialect=traditional,-mtls-size=size-mfix-cortex-a53-835769,-mfix-cortex-a53-843419,-mlow-precision-recip-sqrt,-mlow-precision-sqrt,-mlow-precision-div,-mpc-relative-literal-loads-msign-return-address=scope,-mbranch-protection=none|standard|pac-ret[+leaf +b-key]|bti,-mharden-sls=opts-march=name,-mcpu=name,-mtune=name,-moverride=string,-mverbose-cost-dump-mstack-protector-guard=guard,-mstack-protector-guard-reg=sysreg,-mstack-protector-guard-offset=offset,-mtrack-speculation,-moutline-atomics
Adapteva Epiphany Options โจ
okay so bestie, we've hit the machine-specific part of the menu and it is long, but every single one of these is real, so buckle up ๐ซถ
-mhalf-reg-file-mprefer-short-insn-regs-mbranch-cost=num-mcmove-mnops=num-msoft-cmpsf-msplit-lohi-mpost-inc-mpost-modify-mstack-offset=num-mround-nearest-mlong-calls-mshort-calls-msmall16-mfp-mode=mode-mvect-double-max-vect-align=num-msplit-vecmove-early-m1reg-reg
AMD GCN Options ๐
GPU time, no cap ๐ฎ
-march=gpu-mtune=gpu-mstack-size=bytes
ARC Options ๐ฆ
-mbarrel-shifter-mjli-always-mcpu=cpu-mA6-mARC600-mA7-mARC700-mdpfp-mdpfp-compact-mdpfp-fast-mno-dpfp-lrsr-mea-mno-mpy-mmul32x16-mmul64-matomic-mnorm-mspfp-mspfp-compact-mspfp-fast-msimd-msoft-float-mswap-mcrc-mdsp-packa-mdvbf-mlock-mmac-d16-mmac-24-mrtsc-mswape-mtelephony-mxy-misize-mannotate-align-marclinux-marclinux_prof-mlong-calls-mmedium-calls-msdata-mirq-ctrl-saved-mrgf-banked-regs-mlpc-width=width-G num-mvolatile-cache-mtp-regno=regno-malign-call-mauto-modify-reg-mbbit-peephole-mno-brcc-mcase-vector-pcrel-mcompact-casesi-mno-cond-exec-mearly-cbranchsi-mexpand-adddi-mindexed-loads-mlra-mlra-priority-none-mlra-priority-compact-mlra-priority-noncompact-mmillicode-mmixed-code-mq-class-mRcq-mRcw-msize-level=level-mtune=cpu-mmultcost=num-mcode-density-frame-munalign-prob-threshold=probability-mmpy-option=multo-mdiv-rem-mcode-density-mll64-mfpu=fpu-mrf16-mbranch-index
ARM Options ๐
the ARM list is serving today, there are so many of these, we are obsessed ๐
-mapcs-frame-mno-apcs-frame-mabi=name-mapcs-stack-check-mno-apcs-stack-check-mapcs-reentrant-mno-apcs-reentrant-mgeneral-regs-only-msched-prolog-mno-sched-prolog-mlittle-endian-mbig-endian-mbe8-mbe32-mfloat-abi=name-mfp16-format=name-mthumb-interwork-mno-thumb-interwork-mcpu=name-march=name-mfpu=name-mtune=name-mprint-tune-info-mstructure-size-boundary=n-mabort-on-noreturn-mlong-calls-mno-long-calls-msingle-pic-base-mno-single-pic-base-mpic-register=reg-mnop-fun-dllimport-mpoke-function-name-mthumb-marm-mflip-thumb-mtpcs-frame-mtpcs-leaf-frame-mcaller-super-interworking-mcallee-super-interworking-mtp=name-mtls-dialect=dialect-mword-relocations-mfix-cortex-m3-ldrd-mfix-cortex-a57-aes-1742098-mfix-cortex-a72-aes-1655431-munaligned-access-mneon-for-64bits-mslow-flash-data-masm-syntax-unified-mrestrict-it-mverbose-cost-dump-mpure-code-mcmse-mfix-cmse-cve-2021-35465-mstack-protector-guard=guard-mstack-protector-guard-offset=offset-mfdpic
AVR Options ๐ธ
-mmcu=mcu-mabsdata-maccumulate-args-mbranch-cost=cost-mcall-prologues-mgas-isr-prologues-mint8-mdouble=bits-mlong-double=bits-mn_flash=size-mno-interrupts-mmain-is-OS_task-mrelax-mrmw-mstrict-X-mtiny-stack-mfract-convert-truncate-mshort-calls-nodevicelib-nodevicespecs-Waddr-space-convert-Wmisspelled-isr
Blackfin Options ๐
-mcpu=cpu[-sirevision]-msim-momit-leaf-frame-pointer-mno-omit-leaf-frame-pointer-mspecld-anomaly-mno-specld-anomaly-mcsync-anomaly-mno-csync-anomaly-mlow-64k-mno-low64k-mstack-check-l1-mid-shared-library-mno-id-shared-library-mshared-library-id=n-mleaf-id-shared-library-mno-leaf-id-shared-library-msep-data-mno-sep-data-mlong-calls-mno-long-calls-mfast-fp-minline-plt-mmulticore-mcorea-mcoreb-msdram-micplb
C6X Options ๐
-mbig-endian-mlittle-endian-march=cpu-msim-msdata=sdata-type
CRIS Options โญ
-mcpu=cpu-march=cpu-mtune=cpu-mmax-stack-frame=n-metrax4-metrax100-mpdebug-mcc-init-mno-side-effects-mstack-align-mdata-align-mconst-align-m32-bit-m16-bit-m8-bit-mno-prologue-epilogue-melf-maout-sim-sim2-mmul-bug-workaround-mno-mul-bug-workaround
CR16 Options ๐
-mmac-mcr16cplus-mcr16c-msim-mint32-mbit-ops-mdata-model=model
C-SKY Options ๐ง
-march=arch-mcpu=cpu-mbig-endian-EB-mlittle-endian-EL-mhard-float-msoft-float-mfpu=fpu-mdouble-float-mfdivdu-mfloat-abi=name-melrw-mistack-mmp-mcp-mcache-msecurity-mtrust-mdsp-medsp-mvdsp-mdiv-msmart-mhigh-registers-manchor-mpushpop-mmultiple-stld-mconstpool-mstack-size-mccrt-mbranch-cost=n-mcse-cc-msched-prolog-msim
Darwin Options ๐
macOS bestie representation, we love to see it. heads up that some of these show up more than once in the list as given, so that's what you're getting ๐
-all_load-allowable_client-arch-arch_errors_fatal-arch_only-bind_at_load-bundle-bundle_loader-client_name-compatibility_version-current_version-dead_strip-dependency-file-dylib_file-dylinker_install_name-dynamic-dynamiclib-exported_symbols_list-filelist-flat_namespace-force_cpusubtype_ALL-force_flat_namespace-headerpad_max_install_names-iframework-image_base-init-install_name-keep_private_externs-multi_module-multiply_defined-multiply_defined_unused-noall_load-no_dead_strip_inits_and_terms-nofixprebinding-nomultidefs-noprebind-noseglinkedit-pagezero_size-prebind-prebind_all_twolevel_modules-private_bundle-read_only_relocs-sectalign-sectobjectsymbols-whyload-seg1addr-sectcreate-sectobjectsymbols-sectorder-segaddr-segs_read_only_addr-segs_read_write_addr-seg_addr_table-seg_addr_table_filename-seglinkedit-segprot-segs_read_only_addr-segs_read_write_addr-single_module-static-sub_library-sub_umbrella-twolevel_namespace-umbrella-undefined-unexported_symbols_list-weak_reference_mismatches-whatsloaded-F-gused-gfull-mmacosx-version-min=version-mkernel-mone-byte-bool
DEC Alpha Options ๐ฆ
-mno-fp-regs-msoft-float-mieee-mieee-with-inexact-mieee-conformant-mfp-trap-mode=mode-mfp-rounding-mode=mode-mtrap-precision=mode-mbuild-constants-mcpu=cpu-type-mtune=cpu-type-mbwx-mmax-mfix-mcix-mfloat-vax-mfloat-ieee-mexplicit-relocs-msmall-data-mlarge-data-msmall-text-mlarge-text-mmemory-latency=time
eBPF Options ๐ฅ
-mbig-endian-mlittle-endian-mkernel=version-mframe-limit=bytes-mxbpf-mco-re-mno-co-re-mjmpext-mjmp32-malu32-mcpu=version
FR30 Options ๐
-msmall-model-mno-lsim
FT32 Options โจ
-msim-mlra-mnodiv-mft32b-mcompress-mnopm
FRV Options ๐ซ
-mgpr-32-mgpr-64-mfpr-32-mfpr-64-mhard-float-msoft-float-malloc-cc-mfixed-cc-mdword-mno-dword-mdouble-mno-double-mmedia-mno-media-mmuladd-mno-muladd-mfdpic-minline-plt-mgprel-ro-multilib-library-pic-mlinked-fp-mlong-calls-malign-labels-mlibrary-pic-macc-4-macc-8-mpack-mno-pack-mno-eflags-mcond-move-mno-cond-move-moptimize-membar-mno-optimize-membar-mscc-mno-scc-mcond-exec-mno-cond-exec-mvliw-branch-mno-vliw-branch-mmulti-cond-exec-mno-multi-cond-exec-mnested-cond-exec-mno-nested-cond-exec-mtomcat-stats-mTLS-mtls-mcpu=cpu
GNU/Linux Options ๐ง
-mglibc-muclibc-mmusl-mbionic-mandroid-tno-android-cc-tno-android-ld
H8/300 Options ๐
-mrelax-mh-ms-mn-mexr-mno-exr-mint32-malign-300
HPPA Options ๐
-march=architecture-type-mcaller-copies-mdisable-fpregs-mdisable-indexing-mfast-indirect-calls-mgas-mgnu-ld-mhp-ld-mfixed-range=register-range-mjump-in-delay-mlinker-opt-mlong-calls-mlong-load-store-mno-disable-fpregs-mno-disable-indexing-mno-fast-indirect-calls-mno-gas-mno-jump-in-delay-mno-long-load-store-mno-portable-runtime-mno-soft-float-mno-space-regs-msoft-float-mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0-mportable-runtime-mschedule=cpu-type-mspace-regs-msio-mwsio-munix=unix-std-nolibdld-static-threads
IA-64 Options ๐ฆพ
-mbig-endian-mlittle-endian-mgnu-as-mgnu-ld-mno-pic-mvolatile-asm-stop-mregister-names-msdata-mno-sdata-mconstant-gp-mauto-pic-mfused-madd-minline-float-divide-min-latency-minline-float-divide-max-throughput-mno-inline-float-divide-minline-int-divide-min-latency-minline-int-divide-max-throughput-mno-inline-int-divide-minline-sqrt-min-latency-minline-sqrt-max-throughput-mno-inline-sqrt-mdwarf2-asm-mearly-stop-bits-mfixed-range=register-range-mtls-size=tls-size-mtune=cpu-type-milp32-mlp64-msched-br-data-spec-msched-ar-data-spec-msched-control-spec-msched-br-in-data-spec-msched-ar-in-data-spec-msched-in-control-spec-msched-spec-ldc-msched-spec-control-ldc-msched-prefer-non-data-spec-insns-msched-prefer-non-control-spec-insns-msched-stop-bits-after-every-cycle-msched-count-spec-in-critical-path-msel-sched-dont-check-control-spec-msched-fp-mem-deps-zero-cost-msched-max-memory-insns-hard-limit-msched-max-memory-insns=max-insns
LM32 Options ๐
-mbarrel-shift-enabled-mdivide-enabled-mmultiply-enabled-msign-extend-enabled-muser-enabled
LoongArch Options ๐
-march=cpu-type-mtune=cpu-type-mabi=base-abi-type-mfpu=fpu-type-msoft-float-msingle-float-mdouble-float-mbranch-cost=n-mcheck-zero-division-mno-check-zero-division-mcond-move-int-mno-cond-move-int-mcond-move-float-mno-cond-move-float-memcpy-mno-memcpy-mstrict-align-mno-strict-align-mmax-inline-memcpy-size=n-mcmodel=code-model-mrelax-mpass-mrelax-to-as
M32R/D Options ๐
-m32r2-m32rx-m32r-mdebug-malign-loops-mno-align-loops-missue-rate=number-mbranch-cost=number-mmodel=code-size-model-type-msdata=sdata-type-mno-flush-func-mflush-func=name-mno-flush-trap-mflush-trap=number-G num
M32C Options ๐
-mcpu=cpu-msim-memregs=number
M680x0 Options ๐น๏ธ
-march=arch-mcpu=cpu-mtune=tune-m68000-m68020-m68020-40-m68020-60-m68030-m68040-m68060-mcpu32-m5200-m5206e-m528x-m5307-m5407-mcfv4e-mbitfield-mno-bitfield-mc68000-mc68020-mnobitfield-mrtd-mno-rtd-mdiv-mno-div-mshort-mno-short-mhard-float-m68881-msoft-float-mpcrel-malign-int-mstrict-align-msep-data-mno-sep-data-mshared-library-id=n-mid-shared-library-mno-id-shared-library-mxgot-mno-xgot-mlong-jump-table-offsets
MCore Options ๐งธ
-mhardlit-mno-hardlit-mdiv-mno-div-mrelax-immediates-mno-relax-immediates-mwide-bitfields-mno-wide-bitfields-m4byte-functions-mno-4byte-functions-mcallgraph-data-mno-callgraph-data-mslow-bytes-mno-slow-bytes-mno-lsim-mlittle-endian-mbig-endian-m210-m340-mstack-increment
MeP Options ๐
okay bestie, MeP dumped its whole flag collection on the bed and said โpickโ:
-mabsdiff-mall-opts-maverage-mbased=n-mbitops-mc=n-mclip-mconfig=name-mcop-mcop32-mcop64-mivc2-mdc-mdiv-meb-mel-mio-volatile-ml-mleadz-mm-mminmax-mmult-mno-opts-mrepeat-ms-msatur-msdram-msim-msimnovec-mtf-mtiny=n
MicroBlaze Options ๐ฆ
MicroBlaze said โsoft float, hard float, and a whole personalityโ:
-msoft-float-mhard-float-msmall-divides-mcpu=cpu-mmemcpy-mxl-soft-mul-mxl-soft-div-mxl-barrel-shift-mxl-pattern-compare-mxl-stack-check-mxl-gp-opt-mno-clearbss-mxl-multiply-high-mxl-float-convert-mxl-float-sqrt-mbig-endian-mlittle-endian-mxl-reorder-mxl-mode-app-model-mpic-data-is-text-relative
MIPS Options ๐
MIPS really said โI contain multitudesโ and handed over this iconic list:
-EL-EB-march=arch-mtune=arch-mips1-mips2-mips3-mips4-mips32-mips32r2-mips32r3-mips32r5-mips32r6-mips64-mips64r2-mips64r3-mips64r5-mips64r6-mips16-mno-mips16-mflip-mips16-minterlink-compressed-mno-interlink-compressed-minterlink-mips16-mno-interlink-mips16-mabi=abi-mabicalls-mno-abicalls-mshared-mno-shared-mplt-mno-plt-mxgot-mno-xgot-mgp32-mgp64-mfp32-mfpxx-mfp64-mhard-float-msoft-float-mno-float-msingle-float-mdouble-float-modd-spreg-mno-odd-spreg-mabs=mode-mnan=encoding-mdsp-mno-dsp-mdspr2-mno-dspr2-mmcu-mmno-mcu-meva-mno-eva-mvirt-mno-virt-mxpa-mno-xpa-mcrc-mno-crc-mginv-mno-ginv-mmicromips-mno-micromips-mmsa-mno-msa-mloongson-mmi-mno-loongson-mmi-mloongson-ext-mno-loongson-ext-mloongson-ext2-mno-loongson-ext2-mfpu=fpu-type-msmartmips-mno-smartmips-mpaired-single-mno-paired-single-mdmx-mno-mdmx-mips3d-mno-mips3d-mmt-mno-mt-mllsc-mno-llsc-mlong64-mlong32-msym32-mno-sym32-Gnum-mlocal-sdata-mno-local-sdata-mextern-sdata-mno-extern-sdata-mgpopt-mno-gopt-membedded-data-mno-embedded-data-muninit-const-in-rodata-mno-uninit-const-in-rodata-mcode-readable=setting-msplit-addresses-mno-split-addresses-mexplicit-relocs-mno-explicit-relocs-mcheck-zero-division-mno-check-zero-division-mdivide-traps-mdivide-breaks-mload-store-pairs-mno-load-store-pairs-munaligned-access-mno-unaligned-access-mmemcpy-mno-memcpy-mlong-calls-mno-long-calls-mmad-mno-mad-mimadd-mno-imadd-mfused-madd-mno-fused-madd-nocpp-mfix-24k-mno-fix-24k-mfix-r4000-mno-fix-r4000-mfix-r4400-mno-fix-r4400-mfix-r5900-mno-fix-r5900-mfix-r10000-mno-fix-r10000-mfix-rm7000-mno-fix-rm7000-mfix-vr4120-mno-fix-vr4120-mfix-vr4130-mno-fix-vr4130-mfix-sb1-mno-fix-sb1-mflush-func=func-mno-flush-func-mbranch-cost=num-mbranch-likely-mno-branch-likely-mcompact-branches=policy-mfp-exceptions-mno-fp-exceptions-mvr4130-align-mno-vr4130-align-msynci-mno-synci-mlxc1-sxc1-mno-lxc1-sxc1-mmadd4-mno-madd4-mrelax-pic-calls-mno-relax-pic-calls-mmcount-ra-address-mframe-header-opt-mno-frame-header-opt
MMIX Options ๐
MMIX came through with the MMIX-ware and GNU-ware vibes:
-mlibfuncs-mno-libfuncs-mepsilon-mno-epsilon-mabi=gnu-mabi=mmixware-mzero-extend-mknuthdiv-mtoplevel-symbols-melf-mbranch-predict-mno-branch-predict-mbase-addresses-mno-base-addresses-msingle-exit-mno-single-exit
MN10300 Options ๐
MN10300 said โmult-bug? no mult-bug? letโs discussโ:
-mmult-bug-mno-mult-bug-mno-am33-mam33-mam33-2-mam34-mtune=cpu-type-mreturn-pointer-on-d0-mno-crt0-mrelax-mliw-msetlb
Moxie Options ๐ง
Moxie is short and sweet, no cap:
-meb-mel-mmul.x-mno-crt0
MSP430 Options ๐
MSP430 brought the microcontroller energy and a whole lot of equals signs:
-msim-masm-hex-mmcu=-mcpu=-mlarge-msmall-mrelax-mwarn-mcu-mcode-region=-mdata-region=-msilicon-errata=-msilicon-errata-warn=-mhwmult=-minrt-mtiny-printf-mmax-inline-shift=
NDS32 Options โจ
NDS32 said โendianness, registers, extensions, letโs goโ:
-mbig-endian-mlittle-endian-mreduced-regs-mfull-regs-mcmov-mno-cmov-mext-perf-mno-ext-perf-mext-perf2-mno-ext-perf2-mext-string-mno-ext-string-mv3push-mno-v3push-m16bit-mno-16bit-misr-vector-size=num-mcache-block-size=num-march=arch-mcmodel=code-model-mctor-dtor-mrelax
Nios II Options ๐ซถ
Nios II is giving custom instructions and soft-core main character energy:
-G num-mgpopt=option-mgpopt-mno-gpopt-mgprel-sec=regexp-mr0rel-sec=regexp-mel-meb-mno-bypass-cache-mbypass-cache-mno-cache-volatile-mcache-volatile-mno-fast-sw-div-mfast-sw-div-mhw-mul-mno-hw-mul-mhw-mulx-mno-hw-mulx-mno-hw-div-mhw-div-mcustom-insn=N-mno-custom-insn-mcustom-fpu-cfg=name-mhal-msmallc-msys-crt0=name-msys-lib=name-march=arch-mbmx-mno-bmx-mcdx-mno-cdx
Nvidia PTX Options ๐ฅ
Nvidia PTX keeps it short, like a three-track EP:
-m64-mmainkernel-moptimize
OpenRISC Options ๐ฆ
OpenRISC said โboard, newlib, hard mul, soft div, we contain optionsโ:
-mboard=name-mnewlib-mhard-mul-mhard-div-msoft-mul-msoft-div-msoft-float-mhard-float-mdouble-float-munordered-float-mcmov-mror-mrori-msext-msfimm-mshftimm-mcmodel=code-model
PDP-11 Options ๐
PDP-11 is vintage and knows it:
-mfpu-msoft-float-mac0-mno-ac0-m40-m45-m10-mint32-mno-int16-mint16-mno-int32-msplit-munix-asm-mdec-asm-mgnu-asm-mlra
picoChip Options ๐
picoChip is niche and knows it, and thatโs iconic:
-mae=ae_type-mvliw-lookahead=N-msymbol-as-address-mno-inefficient-warnings
PowerPC Options ๐
See RS/6000 and PowerPC Options.
PRU Options โญ
PRU said โmcu, int, relax, loop, abiโ and thatโs the whole vibe:
-mmcu=mcu-minrt-mno-relax-mloop-mabi=variant
RISC-V Options ๐
RISC-V is the moment, the myth, the legend, and the ISA string:
-mbranch-cost=N-instruction-mplt-mno-plt-mabi=ABI-string-mfdiv-mno-fdiv-mdiv-mno-div-misa-spec=ISA-spec-string-march=ISA-string-mtune=processor-string-mpreferred-stack-boundary=num-msmall-data-limit=N-bytes-msave-restore-mno-save-restore-mshorten-memrefs-mno-shorten-memrefs-mstrict-align-mno-strict-align-mcmodel=medlow-mcmodel=medany-mexplicit-relocs-mno-explicit-relocs-mrelax-mno-relax-mriscv-attribute-mmo-riscv-attribute-malign-data=type-mbig-endian-mlittle-endian-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset
RL78 Options ๐
RL78 is giving simulator, multiplier choices, and cpu variants:
-msim-mmul=none-mmul=g13-mmul=g14-mallregs-mcpu=g10-mcpu=g13-mcpu=g14-mg10-mg13-mg14-m64bit-doubles-m32bit-doubles-msave-mduc-in-interrupts
RS/6000 and PowerPC Options ๐
okay this one is the final boss of option lists, bestie. hydrate first:
-mcpu=cpu-type-mtune=cpu-type-mcmodel=code-model-mpowerpc64-maltivec-mno-altivec-mpowerpc-gpopt-mno-powerpc-gpopt-mpowerpc-gfxopt-mno-powerpc-gfxopt-mmfcrf-mno-mfcrf-mpopcntb-mno-popcntb-mpopcntd-mno-popcntd-mfprnd-mno-fprnd-mcmpb-mno-cmpb-mhard-dfp-mno-hard-dfp-mfull-toc-mminimal-toc-mno-fp-in-toc-mno-sum-in-toc-m64-m32-mxl-compat-mno-xl-compat-mpe-malign-power-malign-natural-msoft-float-mhard-float-mmultiple-mno-multiple-mupdate-mno-update-mavoid-indexed-addresses-mno-avoid-indexed-addresses-mfused-madd-mno-fused-madd-mbit-align-mno-bit-align-mstrict-align-mno-strict-align-mrelocatable-mno-relocatable-mrelocatable-lib-mno-relocatable-lib-mtoc-mno-toc-mlittle-mlittle-endian-mbig-mbig-endian-mdynamic-no-pic-mswdiv-msingle-pic-base-mprioritize-restricted-insns=priority-msched-costly-dep=dependence_type-minsert-sched-nops=scheme-mcall-aixdesc-mcall-eabi-mcall-freebsd-mcall-linux-mcall-netbsd-mcall-openbsd-mcall-sysv-mcall-sysv-eabi-mcall-sysv-noeabi-mtraceback=traceback_type-maix-struct-return-msvr4-struct-return-mabi=abi-type-msecure-plt-mbss-plt-mlongcall-mno-longcall-mpltseq-mno-pltseq-mblock-move-inline-limit=num-mblock-compare-inline-limit=num-mblock-compare-inline-loop-limit=num-mno-block-ops-unaligned-vsx-mstring-compare-inline-limit=num-misel-mno-isel-mvrsave-mno-vrsave-mmulhw-mno-mulhw-mdlmzb-mno-dlmzb-mprototype-mno-prototype-msim-mmvme-mads-myellowknife-memb-msdata-msdata=opt-mreadonly-in-sdata-mvxworks-G num-mrecip-mrecip=opt-mno-recip-mrecip-precision-mno-recip-precision-mveclibabi=type-mfriz-mno-friz-mpointers-to-nested-functions-mno-pointers-to-nested-functions-msave-toc-indirect-mno-save-toc-indirect-mpower8-fusion-mno-mpower8-fusion-mpower8-vector-mno-power8-vector-mcrypto-mno-crypto-mhtm-mno-htm-mquad-memory-mno-quad-memory-mquad-memory-atomic-mno-quad-memory-atomic-mcompat-align-parm-mno-compat-align-parm-mfloat128-mno-float128-mfloat128-hardware-mno-float128-hardware-mgnu-attribute-mno-gnu-attribute-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mprefixed-mno-prefixed-mpcrel-mno-pcrel-mmma-mno-mmma-mrop-protect-mno-rop-protect-mprivileged-mno-privileged
RX Options ๐
RX said โdoubles, fpu, endian data, sim, syntax, relax, registers, pid, string insns, jsr, interruptsโ and honestly same:
-m64bit-doubles-m32bit-doubles-fpu-nofpu-mcpu=-mbig-endian-data-mlittle-endian-data-msmall-data-msim-mno-sim-mas100-syntax-mno-as100-syntax-mrelax-mmax-constant-size=-mint-register=-mpid-mallow-string-insns-mno-allow-string-insns-mjsr-mno-warn-multiple-fast-interrupts-msave-acc-in-interrupts
S/390 and zSeries Options ๐ธ
S/390 and zSeries brought mainframe excellence and a hotpatch at the end:
-mtune=cpu-type-march=cpu-type-mhard-float-msoft-float-mhard-dfp-mno-hard-dfp-mlong-double-64-mlong-double-128-mbackchain-mno-backchain-mpacked-stack-mno-packed-stack-msmall-exec-mno-small-exec-mmvcle-mno-mvcle-m64-m31-mdebug-mno-debug-mesa-mzarch-mhtm-mvx-mzvector-mtpf-trace-mno-tpf-trace-mtpf-trace-skip-mno-tpf-trace-skip-mfused-madd-mno-fused-madd-mwarn-framesize-mwarn-dynamicstack-mstack-size-mstack-guard-mhotpatch=halfwords,halfwords
Score Options ๐
Score is compact and cute:
-meb-mel-mnhwloop-muls-mmac-mscore5-mscore5u-mscore7-mscore7d
SH Options ๐
SH said โhereโs every variant, delay slot, atomic model, and a tasโ:
-m1-m2-m2e-m2a-nofpu-m2a-single-only-m2a-single-m2a-m3-m3e-m4-nofpu-m4-single-only-m4-single-m4-m4a-nofpu-m4a-single-only-m4a-single-m4a-m4al-mb-ml-mdalign-mrelax-mbigtable-mfmovd-mrenesas-mno-renesas-mnomacsave-mieee-mno-ieee-mbitops-misize-minline-ic_invalidate-mpadstruct-mprefergot-musermode-multcost=number-mdiv=strategy-mdivsi3_libfunc=name-mfixed-range=register-range-maccumulate-outgoing-args-matomic-model=atomic-model-mbranch-cost=num-mzdcbranch-mno-zdcbranch-mcbranch-force-delay-slot-mfused-madd-mno-fused-madd-mfsca-mno-fsca-mfsrra-mno-fsrra-mpretend-cmove-mtas
Solaris 2 Options โ๏ธ
Solaris 2 closes this part out with a tiny but mighty set:
-mclear-hwcap-mno-clear-hwcap-mimpure-text-mno-impure-text-pthreads
โจ SPARC Options โจ
okay so SPARC options, bestie, here's the whole menu, no cap:
-mcpu=cpu-type-mtune=cpu-type-mcmodel=code-model-mmemory-model=mem-model-m32-m64-mapp-regs-mno-app-regs-mfaster-structs-mno-faster-structs-mflat-mno-flat-mfpu-mno-fpu-mhard-float-msoft-float-mhard-quad-float-msoft-quad-float-mstack-bias-mno-stack-bias-mstd-struct-return-mno-std-struct-return-munaligned-doubles-mno-unaligned-doubles-muser-mode-mno-user-mode-mv8plus-mno-v8plus-mvis-mno-vis-mvis2-mno-vis2-mvis3-mno-vis3-mvis4-mno-vis4-mvis4b-mno-vis4b-mcbcond-mno-cbcond-mfmaf-mno-fmaf-mfsmuld-mno-fsmuld-mpopc-mno-popc-msubxc-mno-subxc-mfix-at697f-mfix-ut699-mfix-ut700-mfix-gr712rc-mlra-mno-lra
โจ System V Options โจ
-Qy-Qn-YP,paths-Ym,dir
โจ TILE-Gx Options โจ
-mcpu=CPU-m32-m64-mbig-endian-mlittle-endian-mcmodel=code-model
โจ TILEPro Options โจ
-mcpu=cpu-m32
โจ V850 Options โจ
-mlong-calls-mno-long-calls-mep-mno-ep-mprolog-function-mno-prolog-function-mspace-mtda=n-msda=n-mzda=n-mapp-regs-mno-app-regs-mdisable-callt-mno-disable-callt-mv850e2v3-mv850e2-mv850e1-mv850es-mv850e-mv850-mv850e3v5-mloop-mrelax-mlong-jumps-msoft-float-mhard-float-mgcc-abi-mrh850-abi-mbig-switch
โจ VAX Options โจ
-mg-mgnu-munix-mlra
โจ Visium Options โจ
-mdebug-msim-mfpu-mno-fpu-mhard-float-msoft-float-mcpu=cpu-type-mtune=cpu-type-msv-mode-muser-mode
โจ VMS Options โจ
-mvms-return-codes-mdebug-main=prefix-mmalloc64-mpointer-size=size
โจ VxWorks Options โจ
-mrtp-non-static-Bstatic-Bdynamic-Xbind-lazy-Xbind-now
โจ x86 Options โจ
bestie, this list is long but we're gonna get through it together, i promise ๐
-mtune=cpu-type-march=cpu-type-mtune-ctrl=feature-list-mdump-tune-features-mno-default-mfpmath=unit-masm=dialect-mno-fancy-math-387-mno-fp-ret-in-387-m80387-mhard-float-msoft-float-mno-wide-multiply-mrtd-malign-double-mpreferred-stack-boundary=num-mincoming-stack-boundary=num-mcld-mcx16-msahf-mmovbe-mcrc32-mmwait-mrecip-mrecip=opt-mvzeroupper-mprefer-avx128-mprefer-vector-width=opt-mmove-max=bits-mstore-max=bits-mmmx-msse-msse2-msse3-mssse3-msse4.1-msse4.2-msse4-mavx-mavx2-mavx512f-mavx512pf-mavx512er-mavx512cd-mavx512vl-mavx512bw-mavx512dq-mavx512ifma-mavx512vbmi-msha-maes-mpclmul-mfsgsbase-mrdrnd-mf16c-mfma-mpconfig-mwbnoinvd-mptwrite-mprefetchwt1-mclflushopt-mclwb-mxsavec-mxsaves-msse4a-m3dnow-m3dnowa-mpopcnt-mabm-mbmi-mtbm-mfma4-mxop-madx-mlzcnt-mbmi2-mfxsr-mxsave-mxsaveopt-mrtm-mhle-mlwp-mmwaitx-mclzero-mpku-mthreads-mgfni-mvaes-mwaitpkg-mshstk-mmanual-endbr-mforce-indirect-call-mavx512vbmi2-mavx512bf16-menqcmd-mvpclmulqdq-mavx512bitalg-mmovdiri-mmovdir64b-mavx512vpopcntdq-mavx5124fmaps-mavx512vnni-mavx5124vnniw-mprfchw-mrdpid-mrdseed-msgx-mavx512vp2intersect-mserialize-mtsxldtrk-mamx-tile-mamx-int8-mamx-bf16-muintr-mhreset-mavxvnni-mavx512fp16-mcldemote-mms-bitfields-mno-align-stringops-minline-all-stringops-minline-stringops-dynamically-mstringop-strategy=alg-mkl-mwidekl-mmemcpy-strategy=strategy-mmemset-strategy=strategy-mpush-args-maccumulate-outgoing-args-m128bit-long-double-m96bit-long-double-mlong-double-64-mlong-double-80-mlong-double-128-mregparm=num-msseregparm-mveclibabi=type-mvect8-ret-in-mem-mpc32-mpc64-mpc80-mdaz-ftz-mstackrealign-momit-leaf-frame-pointer-mno-red-zone-mno-tls-direct-seg-refs-mcmodel=code-model-mabi=name-maddress-mode=mode-m32-m64-mx32-m16-miamcu-mlarge-data-threshold=num-msse2avx-mfentry-mrecord-mcount-mnop-mcount-m8bit-idiv-minstrument-return=type-mfentry-name=name-mfentry-section=name-mavx256-split-unaligned-load-mavx256-split-unaligned-store-malign-data=type-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offset-mstack-protector-guard-symbol=symbol-mgeneral-regs-only-mcall-ms2sysv-xlogues-mrelax-cmpxchg-loop-mindirect-branch=choice-mfunction-return=choice-mindirect-branch-register-mharden-sls=choice-mindirect-branch-cs-prefix-mneeded-mno-direct-extern-access
โจ x86 Windows Options โจ
-mconsole-mcygwin-mno-cygwin-mdll-mnop-fun-dllimport-mthread-municode-mwin32-mwindows-fno-set-stack-executable
โจ Xstormy16 Options โจ
-msim
โจ Xtensa Options โจ
-mconst16-mno-const16-mfused-madd-mno-fused-madd-mforce-no-pic-mserialize-volatile-mno-serialize-volatile-mtext-section-literals-mno-text-section-literals-mauto-litpools-mno-auto-litpools-mtarget-align-mno-target-align-mlongcalls-mno-longcalls-mabi=abi-type
โจ zSeries Options โจ
zSeries Optionsโ See S/390 and zSeries Options.
โจ Options Controlling the Kind of Output โจ
okay so compilation is like a four-stage glow-up, bestie: preprocessing, compilation proper, assembly, and linking โ always in that order, no skipping steps. GCC can preprocess and compile a bunch of files either into several assembler input files, or into one assembler input file; then each assembler input file makes an object file, and linking combines all the object files (the newly compiled ones and the ones you specified as input) into an executable file. slay.
For any given input file, the file name suffix determines what kind of compilation is done:
file.cโ C source code that must be preprocessed.file.iโ C source code that should not be preprocessed.file.iiโ C++ source code that should not be preprocessed.file.mโ Objective-C source code. Note that you must link with thelibobjclibrary to make an Objective-C program work.file.miโ Objective-C source code that should not be preprocessed.file.mm,file.Mโ Objective-C++ source code. Note that you must link with thelibobjclibrary to make an Objective-C++ program work. Note that.Mrefers to a literal capital M.file.miiโ Objective-C++ source code that should not be preprocessed.file.hโ C, C++, Objective-C or Objective-C++ header file to be turned into a precompiled header (default), or C, C++ header file to be turned into an Ada spec (via the-fdump-ada-specswitch).file.cc,file.cp,file.cxx,file.cpp,file.CPP,file.c++,file.Cโ C++ source code that must be preprocessed. Note that in.cxx, the last two letters must both be literally x. Likewise,.Crefers to a literal capital C.file.mm,file.Mโ Objective-C++ source code that must be preprocessed.file.miiโ Objective-C++ source code that should not be preprocessed.file.hh,file.H,file.hp,file.hxx,file.hpp,file.HPP,file.h++,file.tccโ C++ header file to be turned into a precompiled header or Ada spec.file.f,file.for,file.ftnโ Fixed form Fortran source code that should not be preprocessed.file.F,file.FOR,file.fpp,file.FPP,file.FTNโ Fixed form Fortran source code that must be preprocessed (with the traditional preprocessor).file.f90,file.f95,file.f03,file.f08โ Free form Fortran source code that should not be preprocessed.file.F90,file.F95,file.F03,file.F08โ Free form Fortran source code that must be preprocessed (with the traditional preprocessor).file.goโ Go source code.file.dโ D source code.file.diโ D interface file.file.ddโ D documentation code (Ddoc).file.adsโ Ada source code file that contains a library unit declaration (a declaration of a package, subprogram, or generic, or a generic instantiation), or a library unit renaming declaration (a package, generic, or subprogram renaming declaration). Such files are also called specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). Such files are also called bodies.file.sโ Assembler code.file.S,file.sxโ Assembler code that must be preprocessed.otherโ An object file to be fed straight into linking. Any file name with no recognized suffix is treated this way.
You can specify the input language explicitly with the -x option:
-x languageโ Specify explicitly the language for the following input files (rather than letting the compiler choose a default based on the file name suffix). This option applies to all following input files until the next-xoption. Possible values for language are:
c c-header cpp-output
c++ c++-header c++-system-header c++-user-header c++-cpp-output
objective-c objective-c-header objective-c-cpp-output
objective-c++ objective-c++-header objective-c++-cpp-output
assembler assembler-with-cpp
ada
d
f77 f77-cpp-input f95 f95-cpp-input
go
-x noneโ Turn off any specification of a language, so that subsequent files are handled according to their file name suffixes (as they are if-xhas not been used at all).
If you only want some of the stages of compilation, you can use -x (or filename suffixes) to tell gcc where to start, and one of the options -c, -S, or -E to say where gcc is to stop. Note that some combinations (for example, -x cpp-output -E) instruct gcc to do nothing at all.
-cโ Compile or assemble the source files, but do not link. The linking stage simply is not done. The ultimate output is in the form of an object file for each source file.
By default, the object file name for a source file is made by replacing the suffix .c, .i, .s, etc., with .o.
Unrecognized input files, not requiring compilation or assembly, are ignored.
-Sโ Stop after the stage of compilation proper; do not assemble. The output is in the form of an assembler code file for each non-assembler input file specified.
By default, the assembler file name for a source file is made by replacing the suffix .c, .i, etc., with .s.
Input files that don't require compilation are ignored.
-Eโ Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.
Input files that don't require preprocessing are ignored.
-o fileโ bestie, this is the one that says where the actual output goes. Whatever kind of output we're making โ an executable, an object file, an assembler file, or preprocessed C code โ it lands infile. Periodt. ๐
If you don't say -o, here's the default tea: an executable goes in a.out, the object file for source.suffix goes in source.o, its assembler file goes in source.s, a precompiled header file goes in source.suffix.gch, and all preprocessed C source gets dumped on standard output. ๐ซถ
Okay but here's the plot twist nobody tells you: even though -o names only the primary output, it also messes with how auxiliary and dump outputs get named. See the examples below. ๐ Unless something overrides it, both aux outputs and dump outputs live in the same directory as the primary output. In aux outputs, the suffix of the input file gets swapped for the suffix of the aux output file type; in dump outputs, the suffix of the dump file gets appended to the input file suffix. In compilation commands, the base name of both aux and dump outputs is that of the primary output; in compile-and-link commands, the primary output name, minus the executable suffix, gets combined with the input file name. If both share the same base name (suffix not counted), the combination result is just that base name โ otherwise they get concatenated with a dash between them. ๐
gcc -c foo.c ...
will use foo.o as the primary output, and place aux outputs and dumps right next to it, e.g. aux file foo.dwo for -gsplit-dwarf, and dump file foo.c.???r.final for -fdump-rtl-final. ๐
If a non-linker output file is explicitly specified, aux and dump files by default take the same base name:
gcc -c foo.c -o dir/foobar.o ...
will name aux outputs dir/foobar.* and dump outputs dir/foobar.c.*. โจ
A linker output will instead prefix aux and dump outputs:
gcc foo.c bar.c -o dir/foobar ...
will generally name aux outputs dir/foobar-foo.* and dir/foobar-bar.*, and dump outputs dir/foobar-foo.c.* and dir/foobar-bar.c.*. ๐ธ
The one exception to all of the above is when the executable shares the base name with the single input:
gcc foo.c -o dir/foo ...
in which case aux outputs are named dir/foo.* and dump outputs named dir/foo.c.*. ๐
And the location plus the names of auxiliary and dump outputs can be adjusted with the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj. iykyk. ๐
-dumpbase dumpbaseโ this sets the base name for auxiliary and dump output files. It does not touch the name of the primary output file, no cap. ๐ซ
Intermediate outputs, when they get preserved, are not regarded as primary outputs โ they're auxiliary outputs:
gcc -save-temps -S foo.c
saves the (no longer) temporary preprocessed file in foo.i, and then compiles to the (implied) output file foo.s, whereas:
gcc -save-temps -dumpbase save-foo -c foo.c
preprocesses to in save-foo.i, compiles to save-foo.s (now an intermediate, thus auxiliary output), and then assembles to the (implied) output file foo.o. ๐คฏ
Absent this option, dump and aux files take their names from the input file, or from the (non-linker) output file if one is explicitly specified: dump output files (e.g. those requested by -fdump-* options) with the input name suffix, and aux output files (those requested by other non-dump options, e.g. "-save-temps", "-gsplit-dwarf", "-fcallgraph-info") without it. ๐
Similar suffix differentiation of dump and aux outputs can be attained for explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf.
If dumpbase is explicitly specified with any directory component, any dumppfx specification (e.g. -dumpdir or -save-temps=*) is ignored, and instead of appending to it, dumpbase fully overrides it:
gcc foo.c -c -o dir/foo.o -dumpbase alt/foo \
-dumpdir pfx- -save-temps=cwd ...
creates auxiliary and dump outputs named alt/foo.*, disregarding dir/ in -o, the ./ prefix implied by -save-temps=cwd, and pfx- in -dumpdir. ๐
When -dumpbase is specified in a command that compiles multiple inputs, or that compiles and then links, it may be combined with dumppfx, as specified under -dumpdir. Then, each input file is compiled using the combined dumppfx, and default values for dumpbase and auxdropsuf are computed for each input file:
gcc foo.c bar.c -c -dumpbase main ...
creates foo.o and bar.o as primary outputs, and avoids overwriting the auxiliary and dump outputs by using the dumpbase as a prefix, creating auxiliary and dump outputs named main-foo.* and main-bar.*. ๐ฆ
An empty string specified as dumpbase avoids the influence of the output basename in the naming of auxiliary and dump outputs during compilation, computing default values :
gcc -c foo.c -o dir/foobar.o -dumpbase " ...
will name aux outputs dir/foo.* and dump outputs dir/foo.c.*. Note how their basenames are taken from the input name, but the directory still defaults to that of the output. ๐
The empty-string dumpbase does not prevent the use of the output basename for outputs during linking:
gcc foo.c bar.c -o dir/foobar -dumpbase " -flto ...
The compilation of the source files will name auxiliary outputs dir/foo.* and dir/bar.*, and dump outputs dir/foo.c.* and dir/bar.c.*. LTO recompilation during linking will use dir/foobar. as the prefix for dumps and auxiliary files. ๐ฅ
-dumpbase-ext auxdropsufโ when forming the name of an auxiliary (but not a dump) output file, drop trailingauxdropsuffromdumpbasebefore appending any suffixes. If you don't specify it, this option defaults to the suffix of a defaultdumpbaseโ i.e. the suffix of the input file when-dumpbaseisn't present on the command line, or whendumpbaseis combined withdumppfx. ๐ง
gcc foo.c -c -o dir/foo.o -dumpbase x-foo.c -dumpbase-ext .c ...
creates dir/foo.o as the main output, and generates auxiliary outputs in dir/x-foo.*, taking the location of the primary output, and dropping the .c suffix from the dumpbase. Dump outputs retain the suffix: dir/x-foo.c.*. โจ
This option is disregarded if it does not match the suffix of a specified dumpbase โ except as an alternative to the executable suffix when appending the linker output base name to dumppfx, as specified below:
gcc foo.c bar.c -o main.out -dumpbase-ext .out ...
creates main.out as the primary output, and avoids overwriting the auxiliary and dump outputs by using the executable name minus auxdropsuf as a prefix, creating auxiliary outputs named main-foo.* and main-bar.* and dump outputs named main-foo.c.* and main-bar.c.*. ๐
-dumpdir dumppfxโ when forming the name of an auxiliary or dump output file, usedumppfxas a prefix:
gcc -dumpdir pfx- -c foo.c ...
creates foo.o as the primary output, and auxiliary outputs named pfx-foo.*, combining the given dumppfx with the default dumpbase derived from the default primary output, derived in turn from the input name. Dump outputs also take the input name suffix: pfx-foo.c.*. ๐
If dumppfx is gonna be used as a directory name, it must end with a directory separator:
gcc -dumpdir dir/ -c foo.c -o obj/bar.o ...
creates obj/bar.o as the primary output, and auxiliary outputs named dir/bar.*, combining the given dumppfx with the default dumpbase derived from the primary output name. Dump outputs also take the input name suffix: dir/bar.c.*. ๐ธ
It defaults to the location of the output file โ unless the output file is a special file like "/dev/null". Options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option. In case multiple such options are given, the last one prevails:
gcc -dumpdir pfx- -c foo.c -save-temps=obj ...
outputs foo.o, with auxiliary outputs named foo.* because -save-temps=* overrides the dumppfx given by the earlier -dumpdir option. It does not matter that =obj is the default for -save-temps, nor that the output directory is implicitly the current directory. Dump outputs are named foo.c.*. ๐
When compiling from multiple input files, if -dumpbase is specified, dumpbase, minus a auxdropsuf suffix, and a dash are appended to (or override, if containing any directory components) an explicit or defaulted dumppfx, so that each of the multiple compilations gets differently-named aux and dump outputs. ๐
gcc foo.c bar.c -c -dumpdir dir/pfx- -dumpbase main ...
outputs auxiliary dumps to dir/pfx-main-foo.* and dir/pfx-main-bar.*, appending dumpbase- to dumppfx. Dump outputs retain the input file suffix: dir/pfx-main-foo.c.* and dir/pfx-main-bar.c.*, respectively. Contrast with the single-input compilation:
gcc foo.c -c -dumpdir dir/pfx- -dumpbase main ...
that, applying -dumpbase to a single source, does not compute and append a separate dumpbase per input file. Its auxiliary and dump outputs go in dir/pfx-main.*. ๐
When compiling and then linking from multiple input files, a defaulted or explicitly specified dumppfx also undergoes the dumpbase- transformation above (e.g. the compilation of foo.c and bar.c above, but without -c). If neither -dumpdir nor -dumpbase are given, the linker output base name, minus auxdropsuf, if specified, or the executable suffix otherwise, plus a dash is appended to the default dumppfx instead. Note, however, that unlike earlier cases of linking:
gcc foo.c bar.c -dumpdir dir/pfx- -o main ...
does not append the output name main to dumppfx, because -dumpdir is explicitly specified. The goal is that the explicitly-specified dumppfx may contain the specified output name as part of the prefix, if desired; only an explicitly-specified -dumpbase would be combined with it, in order to avoid simply discarding a meaningful option. ๐ซถ
When compiling and then linking from a single input file, the linker output base name will only be appended to the default dumppfx as above if it does not share the base name with the single input file name. This has been covered in single-input linking cases above, but not with an explicit -dumpdir that inhibits the combination, even if overridden by -save-temps=*:
gcc foo.c -dumpdir alt/pfx- -o dir/main.exe -save-temps=cwd ...
Auxiliary outputs get named foo.*, and dump outputs get foo.c.*, and they land in the current working directory that you ultimately asked for with -save-temps=cwd.
Okay so let's sum this whole thing up, bestie โ it's an intuitive-but-slightly-imprecise data flow, and here's the tea: the primary output name gets broken into a directory part and a basename part. dumppfx gets set to the directory part, unless something overrides it with -dumpdir or -save-temps=*. And dumpbase gets set to the basename part, unless it's overridden by -dumpbase. โจ
If there are multiple inputs, or if you're linking, this dumpbase may get combined with dumppfx and taken from each input file. Auxiliary output names for each input are formed by combining dumppfx, dumpbase minus the suffix, and the auxiliary output suffix. Dump output names are only different in that the suffix from dumpbase is retained. ๐
Now, when it comes to auxiliary and dump outputs created during LTO recompilation, a combination of dumppfx and dumpbase โ as given, or as derived from the linker output name but not from inputs, even in cases where this combination wouldn't otherwise be used as such โ gets passed down with a trailing period replacing the compiler-added dash (if any) as a -dumpdir option to lto-wrapper. And because it's involved in linking, this program doesn't normally get any -dumpbase and -dumpbase-ext, and it ignores them.
When it's running sub-compilers, lto-wrapper appends LTO stage names to the received dumppfx, makes sure it contains a directory component so that it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. ๐ฆ
-vโ Print (on standard error output) the commands executed to run the stages of compilation. It also prints the version number of the compiler driver program, and of the preprocessor, and of the compiler proper. So basically a little backstage pass to everything that's happening. ๐-###โ Like-v, except the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or"./-_". This one is useful for shell scripts that want to capture the driver-generated command lines. Not me loving a dry-run option. ๐--helpโ Print (on standard output) a description of the command-line options understood bygcc. If-vis also specified, then--helpis also passed on to the various processes invoked bygcc, so they can display the command-line options they accept. And if-Wextrahas also been specified (before the--helpoption, okay?), then command-line options that have no documentation associated with them are also displayed. โจ--target-helpโ Print (on standard output) a description of target-specific command-line options for each tool. For some targets, extra target-specific information may also be printed. ๐--help={class|[^]qualifier}[,...]โ Print (on standard output) a description of the command-line options understood by the compiler that fit into all specified classes and qualifiers. Here are the supported classes:optimizersโ Display all of the optimization options supported by the compiler.warningsโ Display all of the options controlling warning messages produced by the compiler.targetโ Display target-specific options. Unlike the--target-helpoption, though, target-specific options of the linker and assembler are not displayed. That's because those tools don't currently support the extended--help=syntax.paramsโ Display the values recognized by the--paramoption.languageโ Display the options supported for language, where language is the name of one of the languages supported in this version of GCC. If an option is supported by all languages, you need to select thecommonclass.commonโ Display the options that are common to all languages.
And these are the supported qualifiers:
undocumentedโ Display only those options that are undocumented.joinedโ Display options taking an argument that appears after an equal sign in the same continuous piece of text, like:--help=target.separateโ Display options taking an argument that appears as a separate word following the original option, like:-o output-file.
So, for example, to display all the undocumented target-specific switches supported by the compiler, use:
--help=target,undocumented
You can invert the sense of a qualifier by prefixing it with the ^ character. So for example, to display all binary warning options (i.e., ones that are either on or off and that don't take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
The argument to --help= should not consist solely of inverted qualifiers. Don't do it, bestie.
Combining several classes is possible, although it usually restricts the output so much that there's nothing left to display. One case where it does work, though, is when one of the classes is target. For example, to display all the target-specific optimization options, use:
--help=target,optimizers
The --help= option can be repeated on the command line. Each successive use displays its requested class of options, skipping those that have already been displayed. And if --help is also specified anywhere on the command line, then it takes precedence over any --help= option. ๐
If the -Q option appears on the command line before the --help= option, then the descriptive text displayed by --help= changes. Instead of describing the displayed options, it gives an indication of whether the option is enabled, disabled, or set to a specific value (assuming the compiler knows this at the point where the --help= option is used). ๐ฅ
Here's a truncated example from the ARM port of gcc:
% gcc -Q -mabi=2 --help=target -c
The following options are target specific:
-mabi= 2
-mabort-on-noreturn [disabled]
-mapcs [disabled]
The output is sensitive to the effects of previous command-line options, so for example you can find out which optimizations are enabled at -O2 by using:
-Q -O2 --help=optimizers
Alternatively you can discover which binary optimizations are enabled by -O3 by using:
gcc -c -Q -O3 --help=optimizers > /tmp/O3-opts
gcc -c -Q -O2 --help=optimizers > /tmp/O2-opts
diff /tmp/O2-opts /tmp/O3-opts | grep enabled
Genuinely iconic detective work honestly. ๐ต๏ธโโ๏ธ
--versionโ Display the version number and copyrights of the invoked GCC. ๐-pass-exit-codesโ Normally thegccprogram exits with the code of1if any phase of the compiler returns a non-success return code. If you specify-pass-exit-codes, thegccprogram instead returns with the numerically highest error produced by any phase returning an error indication. The C, C++, and Fortran front ends return4if an internal compiler error is encountered. ๐ญ-pipeโ Use pipes rather than temporary files for communication between the various stages of compilation. This fails to work on some systems where the assembler is unable to read from a pipe โ but the GNU assembler has no trouble, so if that's you, you're fine. ๐ซถ-specs=fileโ Process file after the compiler reads in the standard specs file, in order to override the defaults that thegccdriver program uses when determining what switches to pass tocc1,cc1plus,as,ld, etc. More than one-specs=filecan be specified on the command line, and they're processed in order, from left to right. ๐ฆ-wrapperโ Invoke all subcommands under a wrapper program. The name of the wrapper program and its parameters are passed as a comma separated list.
gcc -c t.c -wrapper gdb,--args
This invokes all subprograms of gcc under gdb --args, so the invocation of cc1 becomes gdb --args cc1 .... ๐
-ffile-prefix-map=old=newโ When compiling files residing in directory old, record any references to them in the result of the compilation as if the files resided in directory new instead. Specifying this option is equivalent to specifying all the individual-f*-prefix-mapoptions. This can be used to make reproducible builds that are location independent. See also-fmacro-prefix-map,-fdebug-prefix-mapand-fprofile-prefix-map. โจ-fplugin=name.soโ Load the plugin code in filename.so, assumed to be a shared object to bedlopen'd by the compiler. The base name of the shared object file is used to identify the plugin for the purposes of argument parsing (see-fplugin-arg-name-key=valuebelow). Each plugin should define the callback functions specified in the Plugins API. ๐ง-fplugin-arg-name-key=valueโ Define an argument called key with a value of value for the plugin called name. ๐-fdump-ada-spec[-slim]โ For C and C++ source and include files, generate corresponding Ada specs. ๐ธ-fada-spec-parent=unitโ In conjunction with-fdump-ada-spec[-slim]above, generate Ada specs as child units of parent unit. ๐ฆ-fdump-go-spec=fileโ For input files in any language, generate corresponding Go declarations in file. This generates Go"const","type","var", and"func"declarations, which may be a useful way to start writing a Go interface to code written in some other language. ๐@fileโ Read command-line options from file. The options read are inserted in place of the original@fileoption. If file does not exist, or cannot be read, then the option will be treated literally, and not removed.
Options in file are separated by whitespace. A whitespace character may be included in an option by surrounding the entire option in either single or double quotes. Any character (including a backslash) may be included by prefixing the character to be included with a backslash. The file may itself contain additional @file options; any such options will be processed recursively. ๐
Compiling C++ Programs ๐
C++ source files conventionally use one of the suffixes .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx. C++ header files often use .hh, .hpp, .H, or โ for shared template code โ .tcc. And preprocessed C++ files use the suffix .ii. ๐ธ
GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc). So yeah, the vibes are identical, the language is not. ๐
Okay so real talk โ gcc alone does not pull in the C++ library, bestie. That's literally what g++ is for: it's a program that calls GCC and automatically specifies linking against the C++ library. It treats .c, .h and .i files as C++ source files instead of C source files unless -x is used. It's also super useful when you're precompiling a C header file with a .h extension for use in C++ compilations. And on many systems, g++ is also installed with the name c++. ๐
When you compile C++ programs, you may specify many of the same command-line options that you use for compiling programs in any language; or command-line options meaningful for C and related languages; or options that are meaningful only for C++ programs. โจ
๐ Options Controlling C Dialect ๐
The following options control the dialect of C (or languages derived from C, such as C++, Objective-C and Objective-C++) that the compiler accepts:
-ansiโ In C mode, this is equivalent to-std=c90. In C++ mode, it is equivalent to-std=c++98.
This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as the asm and typeof keywords, and predefined macros such as unix and vax that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature ๐ญ. For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword.
The alternate keywords __asm__, __extension__, __inline__ and __typeof__ continue to work despite -ansi. You would not want to use them in an ISO C program, of course, but it is useful to put them in header files that might be included in compilations done with -ansi. Alternate predefined macros such as __unix__ and __vax__ are also available, with or without -ansi.
The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -Wpedantic is required in addition to -ansi. ๐
The macro __STRICT_ANSI__ is predefined when the -ansi option is used. Some header files may notice this macro and refrain from declaring certain functions or defining certain macros that the ISO standard doesn't call for; this is to avoid interfering with any programs that might use these names for other things.
Functions that are normally built in but do not have semantics defined by ISO C (such as alloca and ffs) are not built-in functions when -ansi is used.
-std=โ Determine the language standard. This option is currently only supported when compiling C or C++. ๐ฆ
The compiler can accept several base standards, such as c90 or c++98, and GNU dialects of those standards, such as gnu90 or gnu++98. When a base standard is specified, the compiler accepts all programs following that standard plus those using GNU extensions that do not contradict it. For example, -std=c90 turns off certain features of GCC that are incompatible with ISO C90, such as the asm and typeof keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a ?: expression. On the other hand, when a GNU dialect of a standard is specified, all features supported by the compiler are enabled, even when those features change the meaning of the base standard. As a result, some strict-conforming programs may be rejected. The particular standard is used by -Wpedantic to identify which features are GNU extensions given that version of the standard. For example -std=gnu90 -Wpedantic warns about C++ style // comments, while -std=gnu99 -Wpedantic does not.
A value for this option must be provided; possible values are:
c90c89iso9899:1990โ Support all ISO C90 programs (certain GNU extensions that conflict with ISO C90 are disabled). Same as-ansifor C code.iso9899:199409โ ISO C90 as modified in amendment 1.c99c9xiso9899:1999iso9899:199xโ ISO C99. This standard is substantially completely supported, modulo bugs and floating-point issues (mainly but not entirely relating to optional C99 features from Annexes F and G). See<https://gcc.gnu.org/c99status.html>for more information. The namesc9xandiso9899:199xare deprecated.c11c1xiso9899:2011โ ISO C11, the 2011 revision of the ISO C standard. This standard is substantially completely supported, modulo bugs, floating-point issues (mainly but not entirely relating to optional C11 features from Annexes F and G) and the optional Annexes K (Bounds-checking interfaces) and L (Analyzability). The namec1xis deprecated.c17c18iso9899:2017iso9899:2018โ ISO C17, the 2017 revision of the ISO C standard (published in 2018). This standard is same as C11 except for corrections of defects (all of which are also applied with-std=c11) and a new value of__STDC_VERSION__, and so is supported to the same extent as C11.c2xโ The next version of the ISO C standard, still under development. The support for this version is experimental and incomplete. ๐gnu90gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17gnu18โ GNU dialect of ISO C17. This is the default for C code. ๐gnu2xโ The next version of the ISO C standard, still under development, plus GNU extensions. The support for this version is experimental and incomplete.c++98c++03โ The 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code.gnu++98gnu++03โ GNU dialect of-std=c++98.c++11c++0xโ The 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14c++1yโ The 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17c++1zโ The 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code. The namegnu++1zis deprecated. ๐c++20c++2aโ The 2020 ISO C++ standard plus amendments. Support is experimental, and could change in incompatible ways in future releases. The namec++2ais deprecated.gnu++20gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2bc++23โ The next revision of the ISO C++ standard, planned for 2023. Support is highly experimental, and will almost certainly change in incompatible ways in future releases. ๐gnu++2bgnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
-aux-infofilename โ Output to the given filename prototyped declarations for all functions declared and/or defined in a translation unit, including those in header files. This option is silently ignored in any language other than C.
Besides declarations, the file indicates, in comments, the origin of each declaration (source file and line), whether the declaration was implicit, prototyped or unprototyped (I, N for new or O for old, respectively, in the first character after the line number and the colon), and whether it came from a declaration or a definition (C or F, respectively, in the following character). In the case of function definitions, a K&R-style list of arguments followed by their declarations is also provided, inside comments, after the declaration. ๐
-fallow-parameterless-variadic-functionsโ Accept variadic functions without named parameters.
Although it is possible to define such a function, this is not very useful as it is not possible to read the arguments. This is only supported for C as this construct is allowed by C++.
-fno-asmโ Do not recognizeasm,inlineortypeofas a keyword, so that code can use these words as identifiers. You can use the keywords__asm__,__inline__and__typeof__instead. In C,-ansiimplies-fno-asm.
In C++, inline is a standard keyword and is not affected by this switch. You may want to use the -fno-gnu-keywords flag instead, which disables typeof but not asm and inline. In C99 mode (-std=c99 or -std=gnu99), this switch only affects the asm and typeof keywords, since inline is a standard keyword in ISO C99. โจ
-fno-builtin-fno-builtin-functionโ Don't recognize built-in functions that do not begin with__builtin_as prefix.
GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to alloca may become single instructions which adjust the stack directly, and calls to memcpy may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to printf when printf is built in and strlen is known not to modify global memory. ๐ซถ
- With the
-fno-builtin-functionoption, only the built-in function function gets disabled. And bestie, function must not start with__builtin_. If you name a function that isn't built-in in this version of GCC? The option just gets ignored, no drama. There is no corresponding-fbuiltin-functionoption โ so if you wanna enable built-ins selectively while you're in-fno-builtinor-ffreestandingland, you can define macros like these:
#define abs(n) __builtin_abs ((n))
#define strcpy(d, s) __builtin_strcpy ((d), (s))
-fcond-mismatchโ let conditional expressions have mismatched types in the second and third arguments. The value of such an expression isvoid. Not supported for C++, so don't even try it there. ๐-ffreestandingโ assert that the compilation is targeting a freestanding environment. This implies-fno-builtin. A freestanding environment is one where the standard library might not exist, and program startup might not be atmainat all. The most obvious example? An OS kernel. This is equivalent to-fno-hosted. ๐-fgimpleโ enable parsing of function definitions marked with__GIMPLE. It's an experimental feature that lets you unit test GIMPLE passes. ๐งช-fgnu-tmโ when you pass this, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). Heads up though: this is an experimental feature and its interface may change in future versions of GCC as the official spec changes. Also, not all architectures are supported for this feature.
For more information on GCC's support for transactional memory,
Note: the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). ๐ญ
-fgnu89-inlineโ tells GCC to use the traditional GNU semantics forinlinefunctions when you're in C99 mode.
Using this is roughly equivalent to adding the gnu_inline function attribute to all inline functions.
The option -fno-gnu89-inline explicitly tells GCC to use the C99 semantics for inline when in C99 or gnu99 mode (i.e., it specifies the default behavior). This option is not supported in -std=c90 or -std=gnu90 mode.
The preprocessor macros __GNUC_GNU_INLINE__ and __GNUC_STDC_INLINE__ may be used to check which semantics are in effect for inline functions. ๐ต๏ธ
-fhostedโ assert that compilation targets a hosted environment. This implies-fbuiltin. A hosted environment is one where the entire standard library is available, and wheremainhas a return type ofint. Examples are nearly everything except a kernel. This is equivalent to-fno-freestanding. ๐-flax-vector-conversionsโ allow implicit conversions between vectors with differing numbers of elements and/or incompatible element types. This option should not be used for new code. Periodt.-fms-extensionsโ accept some non-standard constructs used in Microsoft header files.
In C++ code, this allows member names in structures to be similar to previous type declarations, like:
typedef int UOW;
struct ABC {
UOW UOW;
};
Some cases of unnamed fields in structures and unions are only accepted with this option.
Note that this option is off for all targets except for x86 targets using ms-abi.
-foffload=disable-foffload=default-foffload=target-listโ specify for which OpenMP and OpenACC offload targets code should be generated. The default behavior, equivalent to-foffload=default, is to generate code for all supported offload targets. The-foffload=disableform generates code only for the host fallback, while-foffload=target-listgenerates code only for the specified comma-separated list of offload targets.
Offload targets are specified in GCC's internal target-triplet format. You can run the compiler with -v to show the list of configured offload targets under OFFLOAD_TARGET_NAMES. ๐
-foffload-options=options-foffload-options=target-triplet-list=optionsโ with-foffload-options=options, GCC passes the specified options to the compilers for all enabled offloading targets. You can specify options that apply only to a specific target or targets by using the-foffload-options=target-list=optionsform. The target-list is a comma-separated list in the same format as for the-foffload=option.
Typical command lines are
-foffload-options=-lgfortran -foffload-options=-lm
-foffload-options="-lgfortran -lm" -foffload-options=nvptx-none=-latomic
-foffload-options=amdgcn-amdhsa=-march=gfx906 -foffload-options=-lm
-fopenaccโ enable handling of OpenACC directives#pragma accin C/C++ and!$accin Fortran. When-fopenaccis specified, the compiler generates accelerated code according to the OpenACC Application Programming Interface v2.6<https://www.openacc.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread. ๐ฅ-fopenacc-dim=geomโ specify default compute dimensions for parallel offload regions that don't explicitly specify. The geom value is a triple of:-separated sizes, in ordergang,workerand,vector. A size can be omitted, to use a target-specific default value. ๐-fopenmpโ enable handling of OpenMP directives#pragma ompin C/C++ and!$ompin Fortran. When-fopenmpis specified, the compiler generates parallel code according to the OpenMP Application Program Interface v4.5<https://www.openmp.org>. This option implies-pthread, and thus is only supported on targets that have support for-pthread.-fopenmpimplies-fopenmp-simd. โก-fopenmp-simdโ enable handling of OpenMP's SIMD directives with#pragma ompin C/C++ and!$ompin Fortran. Other OpenMP directives are ignored. ๐-fpermitted-flt-eval-methods=styleโ ISO/IEC TS 18661-3 defines new permissible values forFLT_EVAL_METHODthat indicate that operations and constants with a semantic type that is an interchange or extended format should be evaluated to the precision and range of that type. These new values are a superset of those permitted under C99/C11, which does not specify the meaning of other positive values ofFLT_EVAL_METHOD. As such, code conforming to C11 may not have been written expecting the possibility of the new values. ๐ต
-fpermitted-flt-eval-methods specifies whether the compiler should allow only the values of FLT_EVAL_METHOD specified in C99/C11, or the extended set of values specified in ISO/IEC TS 18661-3.
style is either c11 or ts-18661-3 as appropriate.
The default when in a standards compliant mode (-std=c11 or similar) is -fpermitted-flt-eval-methods=c11. The default when in a GNU dialect (-std=gnu11 or similar) is -fpermitted-flt-eval-methods=ts-18661-3.
-fplan9-extensionsโ accept some non-standard constructs used in Plan 9 code.
This enables -fms-extensions, permits passing pointers to structures with anonymous fields to functions that expect pointers to elements of the type of the field, and permits referring to anonymous fields declared using a typedef. This is only supported for C, not C++.
-fsigned-bitfields-funsigned-bitfields-fno-signed-bitfields-fno-unsigned-bitfieldsโ these options control whether a bit-field is signed or unsigned, when the declaration does not use eithersignedorunsigned. By default, such a bit-field is signed, because this is consistent: the basic integer types such asintare signed types. ๐-fsigned-charโ let the typecharbe signed, likesigned char.
Note that this is equivalent to-fno-unsigned-char, which is the negative form of-funsigned-char. Likewise, the option-fno-signed-charis equivalent to-funsigned-char.
-funsigned-charโ let the typecharbe unsigned, likeunsigned char.
Every kind of machine has a default for what char should be. It's either like unsigned char by default or like signed char by default.
Ideally, a portable program should always use signed char or unsigned char when it depends on the signedness of an object. But so many programs have been written to use plain char and expect it to be signed, or expect it to be unsigned, depending on the machines they were written for. This option, and its inverse, let you make such a program work with the opposite default. ๐ซถ
The type char is always a distinct type from each of signed char or unsigned char, even though its behavior is always just like one of those two. โจ
-fsso-struct=endiannessโ set the default scalar storage order of structures and unions to the specified endianness. The accepted values are big-endian, little-endian and native for the native endianness of the target (the default). This option is not supported for C++.
Warning: the -fsso-struct switch causes GCC to generate code that is not binary compatible with code generated without it if the specified endianness is not the native endianness of the target. ๐ญ
โจ Options Controlling C++ Dialect โจ
Okay so this section is literally just for the C++ girlies. It describes the command-line options that are only meaningful for C++ programs. You can also use most of the GNU compiler options regardless of what language your program is in. For example, you might compile a file firstClass.C like this:
g++ -g -fstrict-enums -O -c firstClass.C
In this example, only -fstrict-enums is an option meant only for C++ programs; you can use the other options with any language supported by GCC.
Some options for compiling C programs, such as -std, are also relevant for C++ programs.
Here is a list of options that are only for compiling C++ programs: ๐
-fabi-version=nโ use version n of the C++ ABI. The default is version 0.
Version 0 refers to the version conforming most closely to the C++ ABI specification. Therefore, the ABI obtained using version 0 will change in different versions of G++ as ABI bugs are fixed. ๐ฌ
Version 1 is the version of the C++ ABI that first appeared in G++ 3.2.
Version 2 is the version of the C++ ABI that first appeared in G++ 3.4, and was the default through G++ 4.9.
Version 3 corrects an error in mangling a constant address as a template argument. ๐ง
โจ Version 4 โจ โ first appeared in G++ 4.5, implements a standard mangling for vector types. Slay.
- Version 5 โ first appeared in G++ 4.6, corrects the mangling of attribute const/volatile on function pointer types, decltype of a plain decl, and use of a function parameter in the declaration of another parameter.
- Version 6 โ first appeared in G++ 4.7, corrects the promotion behavior of C++11 scoped enums and the mangling of template argument packs, const/static_cast, prefix ++ and --, and a class scope function used as a template argument.
- Version 7 โ first appeared in G++ 4.8, that treats nullptr_t as a builtin type and corrects the mangling of lambdas in default argument scope.
- Version 8 โ first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
- Version 9 โ first appeared in G++ 5.2, corrects the alignment of
"nullptr_t". - Version 10 โ first appeared in G++ 6.1, adds mangling of attributes that affect type identity, such as ia32 calling convention attributes (e.g. stdcall).
- Version 11 โ first appeared in G++ 7, corrects the mangling of sizeof... expressions and operator names. For multiple entities with the same name within a function, that are declared in different scopes, the mangling now changes starting with the twelfth occurrence. It also implies
-fnew-inheriting-ctors. - Version 12 โ first appeared in G++ 8, corrects the calling conventions for empty classes on the x86_64 target and for classes with only deleted copy/move constructors. It accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor.
- Version 13 โ first appeared in G++ 8.2, fixes the accidental change in version 12.
- Version 14 โ first appeared in G++ 10, corrects the mangling of the nullptr expression.
- Version 15 โ first appeared in G++ 11, changes the mangling of
"__alignof__"to be distinct from that of"alignof", and dependent operator names.
See also -Wabi. ๐
-fabi-compat-version=nโ On targets that support strong aliases, G++ works around mangling changes by creating an alias with the correct mangled name when defining a symbol with an incorrect mangled name. This switch specifies which ABI version to use for the alias.
With -fabi-version=0 (the default), this defaults to 11 (GCC 7 compatibility). If another ABI version is explicitly selected, this defaults to 0. For compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If this option is not provided but -Wabi=n is, that version is used for compatibility aliases. If this option is provided along with -Wabi (without the version), the version from this option is used for the warning. ๐
-fno-access-controlโ Turn off all access checking. This switch is mainly useful for working around bugs in the access control code. ๐-faligned-newโ Enable support for C++17newof types that require more alignment thanvoid* ::operator new(std::size_t)provides. A numeric argument such as-faligned-new=32can be used to specify how much alignment (in bytes) is provided by that function, but few users will need to override the default ofalignof(std::max_align_t).
This flag is enabled by default for -std=c++17. โจ
-fchar8_t,-fno-char8_tโ Enable support forchar8_tas adopted for C++20. This includes the addition of a newchar8_tfundamental type, changes to the types of UTF-8 string and character literals, new signatures for user-defined literals, associated standard library updates, and new__cpp_char8_tand__cpp_lib_char8_tfeature test macros.
This option enables functions to be overloaded for ordinary and UTF-8 strings:
int f(const char *); // #1
int f(const char8_t *); // #2
int v1 = f("text"); // Calls #1
int v2 = f(u8"text"); // Calls #2
and introduces new signatures for user-defined literals:
int operator""_udl1(char8_t);
int v3 = u8'x'_udl1;
int operator""_udl2(const char8_t*, std::size_t);
int v4 = u8"text"_udl2;
template<typename T, T...> int operator""_udl3();
int v5 = u8"text"_udl3;
The change to the types of UTF-8 string and character literals introduces incompatibilities with ISO C++11 and later standards. For example, the following code is well-formed under ISO C++11, but is ill-formed when -fchar8_t is specified.
char ca[] = u8"xx"; // error: char-array initialized from wide
// string
const char *cp = u8"xx";// error: invalid conversion from
// `const char8_t*' to `const char*'
int f(const char*);
auto v = f(u8"xx"); // error: invalid conversion from
// `const char8_t*' to `const char*'
std::string s{u8"xx"}; // error: no matching function for call to
// `std::basic_string<char>::basic_string()'
using namespace std::literals;
s = u8"xx"s; // error: conversion from
// `basic_string<char8_t>' to non-scalar
// type `basic_string<char>' requested
Bestie, this one changes the game for UTF-8 literals, so watch out for those incompatibilities. ๐ญ
-fcheck-newโ Check that the pointer returned byoperator newis non-null before attempting to modify the storage allocated. This check is normally unnecessary because the C++ standard specifies thatoperator newonly returns 0 if it is declaredthrow(), in which case the compiler always checks the return value even without this option. In all other cases, whenoperator newhas a non-empty exception specification, memory exhaustion is signalled by throwingstd::bad_alloc. See alsonew (nothrow). ๐-fconcepts,-fconcepts-tsโ Below-std=c++20,-fconceptsenables support for the C++ Extensions for Concepts Technical Specification, ISO 19217 (2015).
With -std=c++20 and above, Concepts are part of the language standard, so -fconcepts defaults to on. But the standard specification of Concepts differs significantly from the TS, so some constructs that were allowed in the TS but didn't make it into the standard can still be enabled by -fconcepts-ts. ๐ง
-fconstexpr-depth=nโ Set the maximum nested evaluation depth for C++11 constexpr functions ton. A limit is needed to detect endless recursion during constant expression evaluation. The minimum specified by the standard is 512. ๐ฅ-fconstexpr-cache-depth=nโ Set the maximum level of nested evaluation depth for C++11 constexpr functions that will be cached ton. This is a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows very large from highly recursive evaluations). The default is 8. Very few users are likely to want to adjust it, but if your code does heavy constexpr calculations you might want to experiment to find which value works best for you. โจ-fconstexpr-fp-exceptโ Annex F of the C standard specifies that IEC559 floating point exceptions encountered at compile time should not stop compilation. C++ compilers have historically not followed this guidance, instead treating floating point division by zero as non-constant even though it has a well defined value. This flag tells the compiler to give Annex F priority over other rules saying that a particular operation is undefined.
constexpr float inf = 1./0.; // OK with -fconstexpr-fp-except
Literally giving Annex F main character energy. ๐
-fconstexpr-loop-limit=nโ Set the maximum number of iterations for a loop in C++14 constexpr functions ton. A limit is needed to detect infinite loops during constant expression evaluation. The default is 262144 (1<<18). ๐-fconstexpr-ops-limit=nโ Set the maximum number of operations during a single constexpr evaluation. Even when number of iterations of a single loop is limited with the above limit, if there are several nested loops and each of them has many iterations but still smaller than the above limit, or if in a body of some loop or even outside of a loop too many expressions need to be evaluated, the resulting constexpr evaluation might take too long. The default is 33554432 (1<<25). ๐-fcoroutinesโ Enable support for the C++ coroutines extension (experimental). ๐งช-fno-elide-constructorsโ The C++ standard allows an implementation to omit creating a temporary that is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases. This option also causes G++ to call trivial member functions which otherwise would be expanded inline.
In C++17, the compiler is required to omit these temporaries, but this option still affects trivial member functions. ๐ค
-fno-enforce-eh-specsโ Don't generate code to check for violation of exception specifications at run time. This option violates the C++ standard, but may be useful for reducing code size in production builds, much like definingNDEBUG.
This does not give user code permission to throw exceptions in violation of the exception specifications; the compiler still optimizes based on the specifications, so throwing an unexpected exception results in undefined behavior at run time. ๐๐จ
-fextern-tls-init,-fno-extern-tls-initโ okay so C++11 and OpenMP standards letthread_localandthreadprivatevariables have dynamic (runtime) initialization. To support that, any use of such a variable goes through a wrapper function that performs any necessary initialization. When the use and the definition of the variable are in the same translation unit, this overhead can be optimized away, but when the use is in a different translation unit there is significant overhead even if the variable doesn't actually need dynamic initialization. If you as the programmer can be sure that no use of the variable in a non-defining TU needs to trigger dynamic initialization (either because the variable is statically initialized, or a use of the variable in the defining TU will be executed before any uses in another TU), you can avoid this overhead with the-fno-extern-tls-initoption. โจ
On targets that support symbol aliases, the default is -fextern-tls-init. On targets that do not support symbol aliases, the default is -fno-extern-tls-init. ๐
-ffold-simple-inlines,-fno-fold-simple-inlinesโ permit the C++ frontend to fold calls tostd::move,std::forward,std::addressofandstd::as_const. In contrast to inlining, this means no debug information will be generated for such calls. Since these functions are rarely interesting to debug, this flag is enabled by default unless-fno-inlineis active. ๐ซถ-fno-gnu-keywordsโ do not recognizetypeofas a keyword, so that code can use this word as an identifier. You can use the keyword__typeof__instead. This option is implied by the strict ISO C++ dialects:-ansi,-std=c++98,-std=c++11, etc. ๐-fimplicit-constexprโ make inline functions implicitlyconstexpr, if they satisfy the requirements for aconstexprfunction. This option can be used in C++14 mode or later. This can result in initialization changing from dynamic to static and other optimizations. iconic ๐-fno-implicit-templatesโ never emit code for non-inline templates that are instantiated implicitly (i.e. by use); only emit code for explicit instantiations. If you use this option, you must take care to structure your code to include all the necessary explicit instantiations to avoid getting undefined symbols at link time. no cap ๐ญ-fno-implicit-inline-templatesโ don't emit code for implicit instantiations of inline templates, either. The default is to handle inlines differently so that compiles with and without optimization need the same set of explicit instantiations. ๐-fno-implement-inlinesโ to save space, do not emit out-of-line copies of inline functions controlled by#pragma implementation. This causes linker errors if these functions are not inlined everywhere they are called. ๐-fmodules-ts,-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, as that is the default. Even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. iykyk โจ-fmodule-header,-fmodule-header=user,-fmodule-header=systemโ compile a header file to create an importable header unit. ๐ฆ-fmodule-implicit-inlineโ member functions defined in their class definitions are not implicitly inline for modular code. This is different to traditional C++ behavior, for good reasons. However, it may result in a difficulty during code porting. This option makes such function definitions implicitly inline. It does however generate an ABI incompatibility, so you must use it everywhere or nowhere. (Such definitions outside of a named module remain implicitly inline, regardless.) ๐-fno-module-lazyโ disable lazy module importing and module mapper creation. ๐ฆ-fmodule-mapper=[hostname]:port[?ident],-fmodule-mapper=|program[?ident] args...,-fmodule-mapper==socket[?ident],-fmodule-mapper=<>[inout][?ident],-fmodule-mapper=<in>out[?ident],-fmodule-mapper=file[?ident]โ an oracle to query for module name to filename mappings. If unspecified theCXX_MODULE_MAPPERenvironment variable is used, and if that is unset, an in-process default is provided. ๐ฎ-fmodule-onlyโ only emit the Compiled Module Interface, inhibiting any object file. ๐-fms-extensionsโ disableWpedanticwarnings about constructs used in MFC, such as implicit int and getting a pointer to member function via non-standard syntax. ๐ง-fnew-inheriting-ctorsโ enable the P0136 adjustment to the semantics of C++11 constructor inheritance. This is part of C++17 but also considered to be a Defect Report against C++11 and C++14. This flag is enabled by default unless-fabi-version=10or lower is specified. ๐-fnew-ttp-matchingโ enable the P0522 resolution to Core issue 150, template template parameters and default arguments: this allows a template with default template arguments as an argument for a template template parameter with fewer template parameters. This flag is enabled by default for-std=c++17. ๐ฅ-fno-nonansi-builtinsโ disable built-in declarations of functions that are not mandated by ANSI/ISO C. These includeffs,alloca,_exit,index,bzero,conjf, and other related functions. ๐ซ-fnothrow-optโ treat athrow()exception specification as if it were anoexceptspecification to reduce or eliminate the text size overhead relative to a function with no exception specification. If the function has local variables of types with non-trivial destructors, the exception specification actually makes the function smaller because the EH cleanups for those variables can be optimized away. The semantic effect is that an exception thrown out of a function with such an exception specification results in a call toterminaterather thanunexpected. ๐ณ-fno-operator-namesโ do not treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms as keywords. ๐ โโ๏ธ-fno-optional-diagsโ disable diagnostics that the standard says a compiler does not need to issue. Currently, the only such diagnostic issued by G++ is the one for a name having multiple meanings within a class. ๐คซ-fpermissiveโ downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissiveallows some nonconforming code to compile. periodt ๐-fno-pretty-templatesโ when an error message refers to a specialization of a function template, the compiler normally prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (e.g.void f(T) [with T = int]rather thanvoid f(int)) so that it's clear which template is involved. When an error message refers to a specialization of a class template, the compiler omits any template arguments that match the default template arguments for that template. If either of these behaviors make it harder to understand the error message rather than easier, you can use-fno-pretty-templatesto disable them. ๐ญ-fno-rttiโ disable generation of information about every class with virtual functions for use by the C++ run-time type identification features (dynamic_castandtypeid). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but G++ generates it as needed. Thedynamic_castoperator can still be used for casts that do not require run-time type information, i.e. casts tovoid *or to unambiguous base classes. ๐ซ
Mixing code compiled with -frtti with that compiled with -fno-rtti may not work. For example, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. bestie, be careful. ๐
-fsized-deallocationโ enable the built-in global declarations
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
as introduced in C++14. This is useful for user-defined replacement deallocation functions that, for example, use the size of the object to make deallocation faster. Enabled by default under -std=c++14 and above. The flag -Wsized-deallocation warns about places that might want to add a definition. โจ
-fstrict-enumsโ allow the compiler to optimize using the assumption that a value of enumerated type can only be one of the values of the enumeration (as defined in the C++ standard; basically, a value that can be represented in the minimum number of bits needed to represent all the enumerators). This assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. โ ๏ธ-fstrong-eval-orderโ evaluate member access, array subscripting, and shift expressions in left-to-right order, and evaluate assignment in right-to-left order, as adopted for C++17. Enabled by default with-std=c++17.-fstrong-eval-order=someenables just the ordering of member access and shift expressions, and is the default without-std=c++17. ๐ง-ftemplate-backtrace-limit=nโ set the maximum number of template instantiation notes for a single warning or error to n. The default value is10. ๐ข-ftemplate-depth=nโ set the maximum instantiation depth for template classes to n. A limit on the template instantiation depth is needed to detect endless recursions during template class instantiation. ANSI/ISO C++ conforming programs must not rely on a maximum depth greater than17(changed to1024in C++11). The default value is900, as the compiler can run out of stack space before hitting1024in some situations. she's deep ๐-fno-threadsafe-staticsโ do not emit the extra code to use the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this option to reduce code size slightly in code that doesn't need to be thread-safe. ๐งต-fuse-cxa-atexitโ register destructors for objects with static storage duration with the__cxa_atexitfunction rather than theatexitfunction. This option is required for fully standards-compliant handling of static destructors, but only works if your C library supports__cxa_atexit. ๐ซถ-fno-use-cxa-get-exception-ptrโ bestie, this one tells the compiler not to use the"__cxa_get_exception_ptr"runtime routine. The consequence?"std::uncaught_exception"ends up being incorrect ๐ญ โ but you kinda need this flag if that runtime routine just isn't available to you. Trade-off vibes.-fvisibility-inlines-hiddenโ okay so this switch straight up declares that you, the user, are not out here comparing pointers to inline functions or methods where the addresses of those two functions get taken in different shared objects. No cap.
What it actually does: GCC may, effectively, mark inline methods with "__attribute__ ((visibility ("hidden")))" โ so they don't show up in the export table of a DSO and don't need a PLT indirection when used inside that DSO. Turning this on can have a dramatic effect on load and link times of a DSO โจ because it massively shrinks the dynamic export table when the library is heavy on templates. It's giving performance glow-up.
Heads up though โ the behavior here is not quite the same as marking the methods as hidden directly, because it doesn't affect static variables local to the function, and it doesn't make the compiler deduce that the function is defined in only one shared object.
You can mark a method with explicit visibility to negate this switch's effect for that method ๐ . Like, if you genuinely do want to compare pointers to one particular inline method, mark it as having default visibility. But marking the enclosing class with explicit visibility? That does nothing. Zero effect.
Also: explicitly instantiated inline methods are unaffected by this option, since their linkage might otherwise cross a shared library boundary.
-fvisibility-ms-compatโ this flag tries to use visibility settings to make GCC's C++ linkage model compatible with Microsoft Visual Studio's. Iconic crossover episode, honestly.
It makes these changes to GCC's linkage model:
- It sets the default visibility to
"hidden", like-fvisibility=hidden. - Types, but not their members, are not hidden by default.
- The One Definition Rule is relaxed for types without explicit visibility specifications that are defined in more than one shared object: those declarations are permitted if they are permitted when this option is not used.
For new code it's better to use -fvisibility=hidden and export those classes you actually intend to be externally visible. Sadly, it's possible for code to rely โ maybe accidentally ๐ โ on the Visual Studio behavior.
Among the consequences of these changes: static data members of the same type with the same name but defined in different shared objects are different, so changing one does not change the other; and pointers to function members defined in different shared objects may not compare equal. And when this flag is given, it is a violation of the ODR to define types with the same name differently. Periodt.
-fno-weakโ do not use weak symbol support, even if the linker hands it to you on a platter. By default, G++ uses weak symbols if they're available. This option exists only for testing and should not be used by end-users; it results in inferior code and has no benefits. It may be removed in a future release of G++. So likeโฆ don't. ๐-fext-numeric-literals(C++ and Objective-C++ only) โ accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. When this option is turned off, those suffixes get treated as C++11 user-defined literal numeric suffixes. This is on by default for all pre-C++11 dialects and all GNU dialects:-std=c++98,-std=gnu++98,-std=gnu++11,-std=gnu++14. And it's off by default for ISO C++11 onwards (-std=c++11, ...).-nostdinc++โ don't search for header files in the standard directories specific to C++, but do still search the other standard directories. (This option is used when building the C++ library.) Very much a "trust the process, building internals" moment.-flang-info-include-translate,-flang-info-include-translate-not,-flang-info-include-translate=headerโ inform of include translation events ๐ฃ. The first will note accepted include translations, the second will note declined include translations. Theheaderform will inform of include translations relating to that specific header. Ifheaderis of the form"user"or"<system>"it will be resolved to a specific user or system header using the include path.-flang-info-module-cmi,-flang-info-module-cmi=moduleโ inform of Compiled Module Interface pathnames. The first will note all read CMI pathnames. Themoduleform will not reading a specific module's CMI.modulemay be a named module or a header-unit (the latter indicated by either being a pathname containing directory separators or enclosed in"<>"or"").-stdlib=libstdc++,libc++โ when G++ is configured to support this option, it lets you specify alternate C++ runtime libraries ๐ฆ. Two options are available:libstdc++(the default, native C++ runtime for G++) andlibc++, which is the C++ runtime installed on some operating systems (e.g. Darwin versions from Darwin11 onwards). The option switches G++ to use the headers from the specified library and to emit"-lstdc++"or"-lc++"respectively, when a C++ runtime is required for linking.
In addition, these warning options have meanings only for C++ programs:
-Wabi-tag(C++ and Objective-C++ only) โ warn when a type with an ABI tag is used in a context that does not have that ABI tag. See C++ Attributes for more information about ABI tags.-Wcomma-subscript(C++ and Objective-C++ only) โ warn about uses of a comma expression within a subscripting expression. This usage was deprecated in C++20 and is going to be removed in C++23. However, a comma expression wrapped in"( )"is not deprecated. Example:
void f(int *a, int b, int c) {
a[b,c]; // deprecated in C++20, invalid in C++23
a[(b,c)]; // OK
}
In C++23 it's valid to have comma separated expressions in a subscript when an overloaded subscript operator is found and supports the right number and types of arguments. G++ will accept the formerly valid syntax for code that is not valid in C++23 but used to be valid but deprecated in C++20, with a pedantic warning that can be disabled with -Wno-comma-subscript.
Enabled by default with -std=c++20 unless -Wno-deprecated, and with -std=c++23 regardless of -Wno-deprecated.
-Wctad-maybe-unsupported(C++ and Objective-C++ only) โ warn when performing class template argument deduction (CTAD) on a type with no explicitly written deduction guides. This warning points out cases where CTAD succeeded only because the compiler synthesized the implicit deduction guides, which might not be what the programmer intended ๐ฌ. Certain style guides allow CTAD only on types that specifically "opt-in"; i.e., on types that are designed to support CTAD. This warning can be suppressed with the following pattern:
struct allow_ctad_t; // any name works
template <typename T> struct S {
S(T) { }
};
S(allow_ctad_t) -> S<void>; // guide with incomplete parameter type will never be considered
-Wctor-dtor-privacy(C++ and Objective-C++ only) โ warn when a class seems unusable because all the constructors or destructors in that class are private, and it has neither friends nor public static member functions. Also warn if there are no non-private methods, and there's at least one private member function that isn't a constructor or destructor.-Wdelete-non-virtual-dtor(C++ and Objective-C++ only) โ warn when"delete"is used to destroy an instance of a class that has virtual functions and a non-virtual destructor. It is unsafe to delete an instance of a derived class through a pointer to a base class if the base class does not have a virtual destructor ๐จ. This warning is enabled by-Wall.-Wdeprecated-copy(C++ and Objective-C++ only) โ warn that the implicit declaration of a copy constructor or copy assignment operator is deprecated if the class has a user-provided copy constructor or copy assignment operator, in C++11 and up. This warning is enabled by-Wextra. With-Wdeprecated-copy-dtor, also deprecate if the class has a user-provided destructor.-Wno-deprecated-enum-enum-conversion(C++ and Objective-C++ only) โ disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a different enumeration type. This conversion was deprecated in C++20. For example:
enum E1 { e };
enum E2 { f };
int k = f - e;
-Wdeprecated-enum-enum-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-deprecated-enum-float-conversion(C++ and Objective-C++ only) โ disable the warning about the case when the usual arithmetic conversions are applied on operands where one is of enumeration type and the other is of a floating-point type. This conversion was deprecated in C++20 too. For example:
enum E1 { e };
enum E2 { f };
bool b = e <= 3.7;
-Wdeprecated-enum-float-conversion is enabled by default with -std=c++20. In pre-C++20 dialects, this warning can be enabled by -Wenum-conversion.
-Wno-init-list-lifetime(C++ and Objective-C++ only) โ do not warn about uses of"std::initializer_list"that are likely to result in dangling pointers ๐. Since the underlying array for an"initializer_list"is handled like a normal C++ temporary object, it is easy to inadvertently keep a pointer to the array past the end of the array's lifetime. For example:- If a function returns a temporary
"initializer_list", or a local"initializer_list"variable, the array's lifetime ends at the end of the return statement, so the value returned has a dangling pointer. - If a new-expression creates an
"initializer_list", the array only lives until the end of the enclosing full-expression, so the"initializer_list"in the heap has a dangling pointer.
- If a function returns a temporary
...continuing the list, because there's more ways this bites you ๐
- When an
initializer_listvariable is assigned from a brace-enclosed initializer list, the temporary array that gets created for the right side of the assignment only lives until the end of the full-expression โ so at the very next statement yourinitializer_listvariable is out here holding a dangling pointer. not the vibe fr fr
// li's initial underlying array lives as long as li
std::initializer_list<int> li = { 1,2,3 };
// assignment changes li to point to a temporary array
li = { 4, 5 };
// now the temporary is gone and li has a dangling pointer
int i = li.begin()[0] // undefined behavior
- When a list constructor stores the
beginpointer from theinitializer_listargument, that does not extend the lifetime of the array. So if a class variable gets constructed from a temporaryinitializer_list, that pointer is left dangling by the end of the variable declaration statement. ๐ซ
-Winvalid-imported-macrosโ verify that all imported macro definitions are actually valid at the end of compilation. This one is not enabled by default, because it needs extra processing to figure out. It can be useful when you're preparing sets of header-units and you want to make sure the macros are consistent. ๐-Wno-literal-suffix(C++ and Objective-C++ only) โ don't warn when a string or character literal is followed by a ud-suffix that doesn't begin with an underscore. As a conforming extension, GCC treats those suffixes as separate preprocessing tokens, so that code using formatting macros from<inttypes.h>keeps working the way it always did. For example:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <stdio.h>
int main() {
int64_t i64 = 123;
printf("My int64: %" PRId64"\n", i64);
}
In this case, PRId64 is treated as a separate preprocessing token. iykyk
This option also controls the warnings you get when a user-defined literal operator is declared with a literal suffix identifier that doesn't begin with an underscore. Literal suffix identifiers that don't begin with an underscore are reserved for future standardization. ๐ซ
These warnings are enabled by default.
-Wno-narrowing(C++ and Objective-C++ only) โ for C++11 and later standards, narrowing conversions get diagnosed by default, because the standard says so. A narrowing conversion from a constant produces an error, and a narrowing conversion from a non-constant produces a warning, but-Wno-narrowingsuppresses the diagnostic. Note that this does not affect the meaning of well-formed code โ narrowing conversions are still considered ill-formed in SFINAE contexts. โจ
With -Wnarrowing in C++98, warn when a narrowing conversion prohibited by C++11 occurs within { }, e.g.
int i = { 2.2 }; // error: narrowing from double to int
This flag is included in -Wall and -Wc++11-compat.
-Wnoexcept(C++ and Objective-C++ only) โ warn when a noexcept-expression evaluates to false because of a call to a function that does not have a non-throwing exception specification (i.e.throw()ornoexcept) but is known by the compiler to never throw an exception. ๐-Wnoexcept-type(C++ and Objective-C++ only) โ warn if the C++17 feature that makesnoexceptpart of a function type changes the mangled name of a symbol relative to C++14. Enabled by-Wabiand-Wc++17-compat.
As an example:
template <class T> void f(T t) { t(); };
void g() noexcept;
void h() { f(g); }
In C++14, f calls f<void(*)()>, but in C++17 it calls f<void(*)()noexcept>. the way that one character changes everything ๐ญ
-Wclass-memaccess(C++ and Objective-C++ only) โ warn when the destination of a call to a raw memory function such asmemsetormemcpyis an object of class type, and when writing into such an object might bypass the class non-trivial or deleted constructor or copy assignment, violate const-correctness or encapsulation, or corrupt virtual table pointers. Modifying the representation of such objects may violate invariants maintained by member functions of the class. For example, the call tomemsetbelow is undefined because it modifies a non-trivial class object and is, therefore, diagnosed. The safe way to either initialize or clear the storage of objects of such types is by using the appropriate constructor or assignment operator, if one is available. ๐ง
std::string str = "abc";
memset (&str, 0, sizeof str);
The -Wclass-memaccess option is enabled by -Wall. Explicitly casting the pointer to the class object to void * or to a type that can be safely accessed by the raw memory function suppresses the warning.
-Wnon-virtual-dtor(C++ and Objective-C++ only) โ warn when a class has virtual functions and an accessible non-virtual destructor itself or in an accessible polymorphic base class. In that case it is possible but unsafe to delete an instance of a derived class through a pointer to the class itself or base class. This warning is automatically enabled if-Weffc++is specified. โ ๏ธ-Wregister(C++ and Objective-C++ only) โ warn on uses of theregisterstorage class specifier, except when it is part of the GNU Explicit Register Variables extension. The use of theregisterkeyword as a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with-std=c++17. ๐-Wreorder(C++ and Objective-C++ only) โ warn when the order of member initializers given in the code does not match the order in which they must be executed. For instance:
struct A {
int i;
int j;
A(): j (0), i (1) { }
};
The compiler rearranges the member initializers for i and j to match the declaration order of the members, emitting a warning to that effect. This warning is enabled by -Wall. ๐ฅ
-Wno-pessimizing-move(C++ and Objective-C++ only) โ this warning warns when a call tostd::moveprevents copy elision. A typical scenario when copy elision can occur is when returning in a function with a class return type, when the expression being returned is the name of a non-volatile automatic object, and is not a function parameter, and has the same type as the function return type.
struct T {
...
};
T fn()
{
T t;
...
return std::move (t);
}
But in this example, the std::move call prevents copy elision. bestie the move is literally making it slower ๐ญ
This warning is enabled by -Wall.
-Wno-redundant-move(C++ and Objective-C++ only) โ this warning warns about redundant calls tostd::move; that is, when a move operation would have been performed even without thestd::movecall. This happens because the compiler is forced to treat the object as if it were an rvalue in certain situations such as returning a local variable, where copy elision isn't applicable. Consider:
struct T {
...
};
T fn(T t)
{
...
return std::move (t);
}
Here, the std::move call is redundant. Because G++ implements Core Issue 1579, another example is:
struct T { // convertible to U
...
};
struct U {
...
};
U fn()
{
T t;
...
return std::move (t);
}
In this example, copy elision isn't applicable because the type of the expression being returned and the function return type differ, yet G++ treats the return value as if it were designated by an rvalue.
This warning is enabled by -Wextra.
-Wrange-loop-construct(C++ and Objective-C++ only) โ this warning warns when a C++ range-based for-loop is creating an unnecessary copy. This can happen when the range declaration is not a reference, but probably should be. For example:
struct S { char arr[128]; };
void fn () {
S arr[5];
for (const auto x : arr) { ... }
}
It does not warn when the type being copied is a trivially-copyable type whose size is less than 64 bytes.
This warning also warns when a loop variable in a range-based for-loop is initialized with a value of a different type resulting in a copy. For example:
void fn() {
int arr[10];
for (const double &x : arr) { ... }
}
In the example above, in every iteration of the loop a temporary value of type double is created and destroyed, to which the reference const double & is bound. ๐
This warning is enabled by -Wall.
-Wredundant-tags(C++ and Objective-C++ only) โ warn about redundant class-key and enum-key in references to class types and enumerated types in contexts where the key can be eliminated without causing an ambiguity. For example:
struct foo;
struct foo *p; // warn that keyword struct can be eliminated
On the other hand, in this example there is no warning:
struct foo;
void foo (); // "hides" struct foo
void bar (struct foo&); // no warning, keyword struct is necessary
-Wno-subobject-linkage(C++ and Objective-C++ only) โ do not warn if a class type has a base or a field whose type uses the anonymous namespace or depends on a type with no linkage. If a type A depends on a type B with no or internal linkage, defining it in multiple translation units would be an ODR violation because the meaning of B is different in each translation unit. If A only appears in a single translation unit, the best way to silence the warning is to give it internal linkage by putting it in an anonymous namespace as well. The compiler doesn't give this warning for types defined in the main.Cfile, as those are unlikely to have multiple definitions.-Wsubobject-linkageis enabled by default. ๐ธ-Weffc++(C++ and Objective-C++ only) โ warn about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:- bestie, if your class is holding dynamically-allocated memory, you need to define a copy constructor and an assignment operator. like, non-negotiable. ๐
- prefer initialization over assignment inside constructors. it's giving correct. โจ
- make
operator=return a reference to*this. yes queen, hand yourself back. ๐ - if you genuinely have to return an object, then return an object โ do not try to return a reference. no shortcuts. ๐ค
- keep the prefix and postfix forms of the increment and decrement operators clearly distinct. they're different girlies, treat them that way.
- and never overload
&&,||, or,. never ever. not even once. ๐
This option also enables -Wnon-virtual-dtor, which is also one of the effective C++ recommendations. However, the check is extended to warn about the lack of virtual destructor in accessible non-polymorphic bases classes too.
When you pick this option, pls be aware that the standard library headers do not obey all of these guidelines. so use grep -v to filter out those warnings, or you'll be drowning in them fr fr. ๐
-Wno-exceptions(C++ and Objective-C++ only) โ turns off the warning about the case where an exception handler gets shadowed by another handler. which, lowkey, is how you find out your exception handlers are in the wrong order. ๐ซ-Wstrict-null-sentinel(C++ and Objective-C++ only) โ warns about using an uncastedNULLas a sentinel. When you're compiling with GCC only, this is a valid sentinel, sinceNULLis defined to__null. And even though it's a null pointer constant rather than a null pointer, it's guaranteed to be the same size as a pointer. But โ and this is the important part โ this use is not portable across different compilers. โ ๏ธ-Wno-non-template-friend(C++ and Objective-C++ only) โ disables warnings when non-template friend functions are declared inside a template. Here's the lore: in very old versions of GCC that predate implementation of the ISO standard, declarations likefriend int foo(int)โ where the name of the friend is an unqualified-id โ could be interpreted as a particular specialization of a template function. The warning exists to diagnose compatibility problems, and it's enabled by default. ๐-Wold-style-cast(C++ and Objective-C++ only) โ warns if an old-style (C-style) cast to a non-void type shows up in a C++ program. The new-style casts (dynamic_cast,static_cast,reinterpret_cast, andconst_cast) are way less vulnerable to unintended effects and so much easier to search for. glow up your casts bestie. โจ-Woverloaded-virtual(C++ and Objective-C++ only) โ warns when a function declaration hides virtual functions from a base class. For example, in:
struct A {
virtual void f();
};
struct B: public A {
void f(int);
};
the A class version of f is hidden in B, and code like:
B* b;
b->f();
fails to compile. ๐
-Wno-pmf-conversions(C++ and Objective-C++ only) โ disables the diagnostic for converting a bound pointer to member function into a plain pointer.-Wsign-promo(C++ and Objective-C++ only) โ warns when overload resolution chooses a promotion from unsigned or enumerated type to a signed type, over a conversion to an unsigned type of the same size. Previous versions of G++ tried to preserve unsignedness, but the standard mandates the current behavior. the standard said what it said. ๐คท-Wtemplates(C++ and Objective-C++ only) โ warns when a primary template declaration is encountered. Some coding rules disallow templates, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also instantiate or specialize templates. ๐-Wmismatched-new-delete(C++ and Objective-C++ only) โ warns for mismatches between calls tooperator neworoperator deleteand the corresponding call to the allocation or deallocation function. This includes invocations of C++operator deletewith pointers returned from either mismatched forms ofoperator new, or from other functions that allocate objects for which theoperator deleteisn't a suitable deallocator, as well as calls to other deallocation functions with pointers returned fromoperator newfor which the deallocation function isn't suitable.
For example, the delete expression in the function below is diagnosed because it doesn't match the array form of the new expression the pointer argument was returned from. Similarly, the call to free is also diagnosed.
void f ()
{
int *a = new int[n];
delete a; // warning: mismatch in array forms of expressions
char *p = new char[n];
free (p); // warning: mismatch between new and free
}
The related option -Wmismatched-dealloc diagnoses mismatches involving allocation and deallocation functions other than operator new and operator delete.
-Wmismatched-new-delete is included in -Wall. ๐ฅ
-Wmismatched-tags(C++ and Objective-C++ only) โ warns for declarations of structs, classes, and class templates and their specializations with a class-key that does not match either the definition or the first declaration if no definition is provided.
For example, the declaration of struct Object in the argument list of draw triggers the warning. To avoid it, either remove the redundant class-key struct or replace it with class to match its definition.
class Object {
public:
virtual ~Object () = 0;
};
void draw (struct Object*);
It is not wrong to declare a class with the class-key struct as the example above shows. The -Wmismatched-tags option is intended to help achieve a consistent style of class declarations. In code that is intended to be portable to Windows-based compilers the warning helps prevent unresolved references due to the difference in the mangling of symbols declared with different class-keys. The option can be used either on its own or in conjunction with -Wredundant-tags. ๐
-Wmultiple-inheritance(C++ and Objective-C++ only) โ warns when a class is defined with multiple direct base classes. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use multiple inheritance. (sneaky, we love it ๐ )-Wvirtual-inheritanceโ warns when a class is defined with a virtual direct base class. Some coding rules disallow multiple inheritance, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also define classes that indirectly use virtual inheritance.-Wno-virtual-move-assignโ suppresses warnings about inheriting from a virtual base with a non-trivial C++11 move assignment operator. This is dangerous because if the virtual base is reachable along more than one path, it is moved multiple times, which can mean both objects end up in the moved-from state. ๐ญ If the move assignment operator is written to avoid moving from a moved-from object, this warning can be disabled.-Wnamespacesโ warns when a namespace definition is opened. Some coding rules disallow namespaces, and this may be used to enforce that rule. The warning is inactive inside a system header file, such as the STL, so one can still use the STL. One may also useusingdirectives and qualified names. โจ-Wno-terminate(C++ and Objective-C++ only) โ disables the warning about a throw-expression that will immediately result in a call toterminate. ๐-Wno-vexing-parse(C++ and Objective-C++ only) โ warns about the most vexing parse syntactic ambiguity. This warns about the cases when a declaration looks like a variable definition, but the C++ language requires it to be interpreted as a function declaration. For instance:
void f(double a) {
int i(); // extern int i (void);
int n(int(a)); // extern int n (int);
}
Another example:
struct S { S(int); };
void f(double a) {
S x(int(a)); // extern struct S x (int);
S y(int()); // extern struct S y (int (*) (void));
S z(); // extern struct S z (void);
}
The warning will suggest options how to deal with such an ambiguity; e.g., it can suggest removing the parentheses or using braces instead. ๐
This warning is enabled by default.
-Wno-class-conversion(C++ and Objective-C++ only) โ do not warn when a conversion function converts an object to the same type, to a base class of that type, or tovoid; such a conversion function will never be called. it's giving pointless, but no warning for you. ๐-Wvolatile(C++ and Objective-C++ only) โ warns about deprecated uses of thevolatilequalifier. This includes postfix and prefix++and--expressions ofvolatile-qualified types, using simple assignments where the left operand is avolatile-qualified non-class type for their value, compound assignments where the left operand is avolatile-qualified non-class type,volatile-qualified function return type,volatile-qualified parameter type, and structured bindings of avolatile-qualified type. This usage was deprecated in C++20. โ ๏ธ
Enabled by default with -std=c++20.
-Wzero-as-null-pointer-constant(C++ and Objective-C++ only) โ warns when a literal0is used as a null pointer constant. This can be useful to facilitate the conversion tonullptrin C++11. time to upgrade bestie โจ-Waligned-newโ warns about a new-expression of a type that requires greater alignment than thealignof(std::max_align_t)but uses an allocation function without an explicit alignment parameter. This option is enabled by-Wall.
Normally this only warns about global allocation functions, but -Waligned-new=all also warns about class member allocation functions. ๐
-Wno-placement-new,-Wplacement-new=nโ warns about placement new expressions with undefined behavior, such as constructing an object in a buffer that is smaller than the type of the object. For example, the placement new expression below is diagnosed because it attempts to construct an array of 64 integers in a buffer only 64 bytes large. ๐
char buf [64];
new (buf) int[64];
This warning is enabled by default.
-Wplacement-new=1โ bestie, this is the default warning level of-Wplacement-new. At this level, the warning is not issued for some strictly undefined constructs that GCC allows as extensions, for compatibility with legacy code. Case in point: thenewexpression below is not diagnosed at this level, even though it has undefined behavior according to the C++ standard, because it writes past the end of the one-element array. ๐
struct S { int n, a[1]; };
S *s = (S *)malloc (sizeof *s + 31 * sizeof s->a[0]);
new (s->a)int [32]();
-Wplacement-new=2โ level up, we're stricter now โจ At this level, on top of diagnosing all the same constructs as at level 1, a diagnostic is also issued for placement new expressions that construct an object in the last member of a structure whose type is an array of a single element and whose size is less than the size of the object being constructed. So the previous example would get diagnosed โ but the construct below uses the flexible member array extension to dodge the warning at level 2. ๐ง
struct S { int n, a[]; };
S *s = (S *)malloc (sizeof *s + 32 * sizeof s->a[0]);
new (s->a)int [32]();
-Wcatch-value,-Wcatch-value=n(C++ and Objective-C++ only) โ warns about catch handlers that don't catch via reference. The levels, in order:-Wcatch-value=1(or just-Wcatch-valuefor short) โ warns about polymorphic class types that are caught by value.-Wcatch-value=2โ warns about all class types that are caught by value.-Wcatch-value=3โ warns about all types that are not caught by reference.-Wcatch-valueis enabled by-Wall. ๐
-Wconditionally-supported(C++ and Objective-C++ only) โ warns for conditionally-supported (C++11 [intro.defs]) constructs. iykyk ๐ซถ-Wno-delete-incomplete(C++ and Objective-C++ only) โ do not warn when deleting a pointer to incomplete type, which may cause undefined behavior at runtime. This warning is enabled by default. ๐-Wextra-semi(C++, Objective-C++ only) โ warns about redundant semicolons after in-class function definitions. the extra;jumped out, periodt โ-Wno-inaccessible-base(C++, Objective-C++ only) โ this option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. The warning is enabled by default. Note that the warning for ambiguous virtual bases is enabled by the-Wextraoption. ๐ธ
struct A { int a; };
struct B : A { };
struct C : B, A { };
-Wno-inherited-variadic-ctorโ suppresses warnings about use of C++11 inheriting constructors when the base class inherited from has a C variadic constructor; the warning is on by default because the ellipsis is not inherited. ๐ญ-Wno-invalid-offsetof(C++ and Objective-C++ only) โ suppresses warnings from applying theoffsetofmacro to a non-POD type. According to the 2014 ISO C++ standard, applyingoffsetofto a non-standard-layout type is undefined. In existing C++ implementations, however,offsetoftypically gives meaningful results. This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it. ๐ซฃ
The restrictions on offsetof may be relaxed in a future version of the C++ standard. future tea, not today's tea
-Wsized-deallocation(C++ and Objective-C++ only) โ warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
without a definition of the corresponding sized deallocation function
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
or vice versa. Enabled by -Wextra along with -fsized-deallocation. matching set or it's a problem ๐
-Wsuggest-final-typesโ warns about types with virtual methods where code quality would be improved if the type were declared with the C++11finalspecifier, or, if possible, declared in an anonymous namespace. This allows GCC to more aggressively devirtualize the polymorphic calls. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. โญ-Wsuggest-final-methodsโ warns about virtual methods where code quality would be improved if the method were declared with the C++11finalspecifier, or, if possible, its type were declared in an anonymous namespace or with thefinalspecifier. This warning is more effective with link-time optimization, where the information about the class hierarchy graph is more complete. It is recommended to first consider suggestions of-Wsuggest-final-typesand then rebuild with new annotations. ๐-Wsuggest-overrideโ warns about overriding virtual functions that are not marked with theoverridekeyword. say the word, babe โจ-Wuse-after-free,-Wuse-after-free=nโ warns about uses of pointers to dynamically allocated objects that have been rendered indeterminate by a call to a deallocation function. The warning is enabled at all optimization levels, but may yield different results with optimization than without. ๐ฅ-Wuse-after-free=1โ at level 1 the warning attempts to diagnose only unconditional uses of pointers made indeterminate by a deallocation call or a successful call torealloc, regardless of whether or not the call resulted in an actual reallocation of memory. This includes double-freecalls as well as uses in arithmetic and relational expressions. Although undefined, uses of indeterminate pointers in equality (or inequality) expressions are not diagnosed at this level.-Wuse-after-free=2โ at level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of pointers made indeterminate by a deallocation call. As at level 2, uses in equality (or inequality) expressions are not diagnosed. For example, the second call tofreein the following function is diagnosed at this level:
struct A { int refcount; void *data; };
void release (struct A *p)
{
int refcount = --p->refcount;
free (p);
if (refcount == 0)
free (p->data); // warning: p may be used after free
}
-Wuse-after-free=3โ at level 3, the warning also diagnoses uses of indeterminate pointers in equality expressions. All uses of indeterminate pointers are undefined, but equality tests sometimes appear after calls toreallocas an attempt to determine whether the call resulted in relocating the object to a different address. They are diagnosed at a separate level to aid legacy code gradually transition to safe alternatives. For example, the equality test in the function below is diagnosed at this level:
void adjust_pointers (int**, int);
void grow (int **p, int n)
{
int **q = (int**)realloc (p, n *= 2);
if (q == p)
return;
adjust_pointers ((int**)q, n);
}
- To avoid the warning at this level, store offsets into allocated memory instead of pointers. This approach obviates needing to adjust the stored pointers after reallocation. ๐ก
-Wuse-after-free=2is included in-Wall. noted, screenshot taken
-Wuseless-cast(C++ and Objective-C++ only) โ warns when an expression is casted to its own type. casting something to itself? girl, why ๐ญ-Wno-conversion-null(C++ and Objective-C++ only) โ do not warn for conversions betweenNULLand non-pointer types.-Wconversion-nullis enabled by default.
๐ฆ Options Controlling Objective-C and Objective-C++ Dialects ๐ฆ
(NOTE: This manual does not describe the Objective-C and Objective-C++ languages themselves. ๐
This section describes the command-line options that are only meaningful for Objective-C and Objective-C++ programs. You can also use most of the language-independent GNU compiler options. For example, you might compile a file some_class.m like this:
gcc -g -fgnu-runtime -O -c some_class.m
In this example, -fgnu-runtime is an option meant only for Objective-C and Objective-C++ programs; you can use the other options with any language supported by GCC. ๐
Note that since Objective-C is an extension of the C language, Objective-C compilations may also use options specific to the C front-end (e.g., -Wtraditional). Similarly, Objective-C++ compilations may use C++-specific options (e.g., -Wabi). ๐ธ
Here is a list of options that are only for compiling Objective-C and Objective-C++ programs:
- *
-fconstant-string-class=class-name* โ use class-name as the name of the class to instantiate for each literal string specified with the syntax@"...". The default class name isNXConstantStringif the GNU runtime is being used, andNSConstantStringif the NeXT runtime is being used (see below). On Darwin (macOS, MacOS X) platforms, the-fconstant-cfstringsoption, if also present, overrides the-fconstant-string-classsetting and cause@"..."literals to be laid out as constant CoreFoundation strings. Note that-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. ๐ -fgnu-runtimeโ generate object code compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐-fnext-runtimeโ generate output compatible with the NeXT runtime. This is the default for NeXT-based systems, including Darwin and Mac OS X. The macro__NEXT_RUNTIME__is predefined if (and only if) this option is used. โญ-fno-nil-receiversโ assume that all Objective-C message dispatches ([receiver message:arg]) in this translation unit ensure that the receiver is notnil. This allows for more efficient entry points in the runtime to be used. This option is only available in conjunction with the NeXT runtime and ABI version 0 or 1. ๐-fobjc-abi-version=nโ okay so you're picking version n of the Objective-C ABI for whichever runtime you chose. This one is currently only supported for the NeXT runtime, jsyk. In that case: Version 0 is the traditional (32-bit) ABI with no support for properties and other Objective-C 2.0 additions. Version 1 is the traditional (32-bit) ABI with support for properties and those other Objective-C 2.0 additions. Version 2 is the modern (64-bit) ABI. And if you don't specify anything? Default is Version 0 on 32-bit target machines, and Version 2 on 64-bit target machines. โจ-fobjc-call-cxx-cdtorsโ for each Objective-C class, it peeks at whether any of its instance variables is a C++ object with a non-trivial default constructor. If so, it synthesizes a special- (id) .cxx_constructinstance method that runs those non-trivial default constructors on any such instance variables, in order, and then returnsself. Similarly, it checks if any instance variable is a C++ object with a non-trivial destructor, and if so, synthesizes a special- (void) .cxx_destructmethod that runs all such default destructors, in reverse order. ๐
The - (id) .cxx_construct and - (void) .cxx_destruct methods thusly generated only operate on instance variables declared in the current Objective-C class, and not those inherited from superclasses. It is the responsibility of the Objective-C runtime to invoke all such methods in an object's inheritance hierarchy. The - (id) .cxx_construct methods are invoked by the runtime immediately after a new object instance is allocated; the - (void) .cxx_destruct methods are invoked immediately before the runtime deallocates an object instance.
As of this writing, only the NeXT runtime on Mac OS X 10.4 and later has support for invoking the - (id) .cxx_construct and - (void) .cxx_destruct methods.
-fobjc-direct-dispatchโ allow fast jumps to the message dispatcher. On Darwin this is accomplished via the comm page. ๐ฆ-fobjc-exceptionsโ enables syntactic support for structured exception handling in Objective-C, similar to what C++ offers. This option is required to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. It's available with both the GNU runtime and the NeXT runtime โ but not available in conjunction with the NeXT runtime on Mac OS X 10.2 and earlier. ๐-fobjc-gcโ enable garbage collection (GC) in Objective-C and Objective-C++ programs. This one is only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that doesn't need special compiler flags, bestie.-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, check for a nil receiver in method invocations before doing the actual method call. This is the default, and you can turn it off with-fno-objc-nilcheck. Class methods and super calls are never checked for nil in this way no matter what this flag is set to. Currently this flag does nothing when the GNU runtime, or an older version of the NeXT runtime ABI, is used. ๐-fobjc-std=objc1โ conform to the language syntax of Objective-C 1.0, the language recognized by GCC 4.0. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is controlled by the separate C/C++ dialect option flags. When this option is used with the Objective-C or Objective-C++ compiler, any Objective-C syntax that isn't recognized by GCC 4.0 is rejected. Super useful if you need to make sure your Objective-C code can be compiled with older versions of GCC. ๐-freplace-objc-classesโ emits a special marker instructingld(1)not to statically link in the resulting object file, and letsdyld(1)load it in at run time instead. This is used together with the Fix-and-Continue debugging mode, where the object file in question may be recompiled and dynamically reloaded while the program is executing, no restart needed. Currently, Fix-and-Continue functionality is only available with the NeXT runtime on Mac OS X 10.3 and later.-fzero-linkโ when compiling for the NeXT runtime, the compiler ordinarily replaces calls toobjc_getClass("...")(when the name of the class is known at compile time) with static class references that get initialized at load time, which improves run-time performance. Specifying the-fzero-linkflag suppresses this behavior and causes calls toobjc_getClass("...")to be retained. This is useful in Zero-Link debugging mode, since it allows individual class implementations to be modified during program execution. The GNU runtime currently always retains calls toobjc_get_class("...")regardless of command-line options. ๐-fno-local-ivarsโ by default, instance variables in Objective-C can be accessed as if they were local variables from within the methods of the class they're declared in. This can lead to shadowing between instance variables and other variables declared either locally inside a class method or globally with the same name. Specifying the-fno-local-ivarsflag disables this behavior, thus avoiding variable shadowing issues. ๐-fivar-visibility=[public|protected|private|package]โ set the default instance variable visibility to the specified option, so that instance variables declared outside the scope of any access modifier directives default to the specified visibility.-gen-declsโ dump interface declarations for all classes seen in the source file to a file namedsourcename.decl. ๐-Wassign-intercept(Objective-C and Objective-C++ only) โ warn whenever an Objective-C assignment is being intercepted by the garbage collector.-Wno-property-assign-default(Objective-C and Objective-C++ only) โ do not warn if a property for an Objective-C object has no assign semantics specified.-Wno-protocol(Objective-C and Objective-C++ only) โ if a class is declared to implement a protocol, a warning is issued for every method in the protocol that isn't implemented by the class. The default behavior is to issue a warning for every method not explicitly implemented in the class, even if a method implementation is inherited from the superclass. If you use the-Wno-protocoloption, then methods inherited from the superclass are considered to be implemented, and no warning is issued for them. ๐ซถ-Wobjc-root-class(Objective-C and Objective-C++ only) โ warn if a class interface lacks a superclass. Most classes will inherit fromNSObject(orObject) for example. When declaring classes intended to be root classes, the warning can be suppressed by marking their interfaces with__attribute__((objc_root_class)).-Wselector(Objective-C and Objective-C++ only) โ warn if multiple methods of different types for the same selector are found during compilation. The check is performed on the list of methods in the final stage of compilation. Additionally, a check is performed for each selector appearing in a@selector(...)expression, and a corresponding method for that selector has been found during compilation. Because these checks scan the method table only at the end of compilation, these warnings are not produced if the final stage of compilation isn't reached โ for example because an error is found during compilation, or because the-fsyntax-onlyoption is being used. ๐ญ-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warn if multiple methods with differing argument and/or return types are found for a given selector when attempting to send a message using this selector to a receiver of typeidorClass. When this flag is off (which is the default behavior), the compiler omits such warnings if any differences found are confined to types that share the same size and alignment.-Wundeclared-selector(Objective-C and Objective-C++ only) โ warn if a@selector(...)expression referring to an undeclared selector is found. A selector is considered undeclared if no method with that name has been declared before the@selector(...)expression, either explicitly in an@interfaceor@protocoldeclaration, or implicitly in an@implementationsection. This option always performs its checks as soon as a@selector(...)expression is found, while-Wselectoronly performs its checks in the final stage of compilation. This also enforces the coding style convention that methods and selectors must be declared before being used. ๐-print-objc-runtime-infoโ generate C header describing the largest structure that is passed by value, if any.
โจ Options to Control Diagnostic Messages Formatting โจ
Traditionally, diagnostic messages have been formatted irrespective of the output device's aspect (e.g. its width, ...). You can use the options described below to control the formatting algorithm for diagnostic messages โ like how many characters per line, how often source location information should be reported. Note that some language front ends may not honor these options. ๐
-fmessage-length=nโ try to format error messages so that they fit on lines of about n characters. If n is zero, then no line-wrapping is done; each error message appears on a single line. This is the default for all front ends.
Note โ this option also affects the display of the #error and #warning pre-processor directives, and the deprecated function/type/variable attribute. It does not however affect the pragma GCC warning and pragma GCC error pragmas. ๐
-fdiagnostics-plain-outputโ this option requests that diagnostic output look as plain as possible, which may be useful when runningdejagnuor other utilities that need to parse diagnostics output and prefer that it remain more stable over time.-fdiagnostics-plain-outputis currently equivalent to the following options:
-fno-diagnostics-show-caret
-fno-diagnostics-show-line-numbers
-fdiagnostics-color=never
-fdiagnostics-urls=never
-fdiagnostics-path-format=separate-events
In the future, if GCC changes the default appearance of its diagnostics, the corresponding option to disable the new behavior will be added to this list. โญ
-fdiagnostics-show-location=onceโ only does anything in line-wrapping mode, bestie. It tells the diagnostic reporter to drop the source location once โ meaning if the message is too long for one physical line and has to wrap, the source location won't be spammed as a prefix again and again on every continuation line. This is the default behavior. ๐-fdiagnostics-show-location=every-lineโ also only meaningful in line-wrapping mode. This one tells the reporter to emit that same source location info (as a prefix) on every physical line that comes out of breaking a message too long for a single line. ๐ธ-fdiagnostics-color[=WHEN]-fno-diagnostics-colorโ use color in diagnostics, periodt.WHENisnever,always, orauto. The default depends on how the compiler has been configured โ it can be any of the aboveWHENoptions, or alsoneverif theGCC_COLORSenvironment variable isn't present in the environment, andautootherwise.automakes GCC use color only when the standard error is a terminal, and when not executing in an emacs shell. The forms-fdiagnostics-colorand-fno-diagnostics-colorare aliases for-fdiagnostics-color=alwaysand-fdiagnostics-color=never, respectively. ๐
The colors are defined by the environment variable GCC_COLORS. Its value is a colon-separated list of capabilities and Select Graphic Rendition (SGR) substrings. SGR commands are interpreted by the terminal or terminal emulator. (See the section in the documentation of your text terminal for permitted values and their meanings as character attributes.) These substring values are integers in decimal representation and can be concatenated with semicolons. Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. ๐
The default GCC_COLORS is
error=01;31:warning=01;35:note=01;36:range1=32:range2=34:locus=01:\
quote=01:path=01;36:fixit-insert=32:fixit-delete=31:\
diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32:\
type-diff=01;32
where 01;31 is bold red, 01;35 is bold magenta, 01;36 is bold cyan, 32 is green, 34 is blue, 01 is bold, and 31 is red. Setting GCC_COLORS to the empty string disables colors. Supported capabilities are as follows. โจ
"error="โ SGR substring forerror:markers."warning="โ SGR substring forwarning:markers."note="โ SGR substring fornote:markers."path="โ SGR substring for colorizing paths of control-flow events as printed via-fdiagnostics-path-format=, such as the identifiers of individual events and lines indicating interprocedural calls and returns."range1="โ SGR substring for first additional range."range2="โ SGR substring for second additional range."locus="โ SGR substring for location information,file:lineorfile:line:columnetc."quote="โ SGR substring for information printed within quotes."fixit-insert="โ SGR substring for fix-it hints suggesting text to be inserted or replaced."fixit-delete="โ SGR substring for fix-it hints suggesting text to be deleted."diff-filename="โ SGR substring for filename headers within generated patches."diff-hunk="โ SGR substring for the starts of hunks within generated patches."diff-delete="โ SGR substring for deleted lines within generated patches."diff-insert="โ SGR substring for inserted lines within generated patches."type-diff="โ SGR substring for highlighting mismatching types within template arguments in the C++ frontend.
-fdiagnostics-urls[=WHEN]โ use escape sequences to embed URLs in diagnostics, iconic behavior honestly. For example, when-fdiagnostics-show-optionemits text showing the command-line option controlling a diagnostic, embed a URL for documentation of that option. ๐
WHEN is never, always, or auto. auto makes GCC use URL escape sequences only when the standard error is a terminal, and when not executing in an emacs shell or any graphical terminal which is known to be incompatible with this feature, see below.
The default depends on how the compiler has been configured. It can be any of the above WHEN options.
GCC can also be configured (via the --with-diagnostics-urls=auto-if-env configure-time option) so that the default is affected by environment variables. Under such a configuration, GCC defaults to using auto if either GCC_URLS or TERM_URLS environment variables are present and non-empty in the environment of the compiler, or never if neither are. ๐ฆ
However, even with -fdiagnostics-urls=always the behavior is dependent on those environment variables: If GCC_URLS is set to empty or no, do not embed URLs in diagnostics. If set to st, URLs use ST escape sequences. If set to bel, the default, URLs use BEL escape sequences. Any other non-empty value enables the feature. If GCC_URLS is not set, use TERM_URLS as a fallback. Note: ST is an ANSI escape sequence, string terminator ESC , BEL is an ASCII character, CTRL-G that usually sounds like a beep. ๐
At this time GCC tries to detect also a few terminals that are known to not implement the URL feature, and have bugs or at least had bugs in some versions that are still in use, where the URL escapes are likely to misbehave, i.e. print garbage on the screen. That list is currently xfce4-terminal, certain known to be buggy gnome-terminal versions, the linux console, and mingw. This check can be skipped with the -fdiagnostics-urls=always. ๐ซถ
-fno-diagnostics-show-optionโ by default, each diagnostic emitted includes text indicating the command-line option that directly controls the diagnostic (if such an option is known to the diagnostic machinery). Specifying the-fno-diagnostics-show-optionflag suppresses that behavior.-fno-diagnostics-show-caretโ by default, each diagnostic emitted includes the original source line and a caret^indicating the column. This option suppresses this information. The source line is truncated to n characters, if the-fmessage-length=noption is given. When the output is done to the terminal, the width is limited to the width given by theCOLUMNSenvironment variable or, if not set, to the terminal width. ๐ธ-fno-diagnostics-show-labelsโ by default, when printing source code (via-fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent information, such as the types of expressions:
printf ("foo %s bar", long_i + long_j);
~^ ~~~~~~~~~~~~~~~
| |
char * long int
This option suppresses the printing of these labels (in the example above, the vertical bars and the "char *" and "long int" text).
-fno-diagnostics-show-cweโ diagnostic messages can optionally have an associated@url{https://cwe.mitre.org/index.html, CWE}identifier. GCC itself only provides such metadata for some of the-fanalyzerdiagnostics. GCC plugins may also provide diagnostics with such metadata. By default, if this information is present, it will be printed with the diagnostic. This option suppresses the printing of this metadata.-fno-diagnostics-show-line-numbersโ by default, when printing source code (via-fdiagnostics-show-caret), a left margin is printed, showing line numbers. This option suppresses this left margin.-fdiagnostics-minimum-margin-width=widthโ this option controls the minimum width of the left margin printed by-fdiagnostics-show-line-numbers. It defaults to6. โจ-fdiagnostics-parseable-fixitsโ emit fix-it hints in a machine-parseable format, suitable for consumption by IDEs. For each fix-it, a line will be printed after the relevant diagnostic, starting with the string"fix-it:". For example:
fix-it:"test.c":{45:3-45:21}:"gtk_widget_show_all"
The location is expressed as a half-open range, expressed as a count of bytes, starting at byte 1 for the initial column. In the above example, bytes 3 through 20 of line 45 of "test.c" are to be replaced with the given string:
00000000011111111112222222222
12345678901234567890123456789
gtk_widget_showall (dlg);
^^^^^^^^^^^^^^^^^^
gtk_widget_show_all
The filename and replacement string escape backslash as "\\", tab as "\t", newline as "\n", double quotes as "\"", non-printable characters as octal (e.g. vertical tab as "\013").
An empty replacement string indicates that the given range is to be removed. An empty range (e.g. "45:3-45:3") indicates that the string is to be inserted at the given position. ๐
-fdiagnostics-generate-patchโ print fix-it hints to stderr in unified diff format, after any diagnostics are printed. For example:
--- test.c
+++ test.c
@ -42,5 +42,5 @
void show_cb(GtkDialog *dlg)
{
- gtk_widget_showall(dlg);
+ gtk_widget_show_all(dlg);
}
The diff may or may not be colorized, following the same rules as for diagnostics (see -fdiagnostics-color).
-fdiagnostics-show-template-treeโ in the C++ frontend, when printing diagnostics showing mismatching template types, such as:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
the -fdiagnostics-show-template-tree flag enables printing a tree-like structure showing the common and differing parts of the types, such as:
map<
[...],
vector<
[double != float]>>
๐
The parts that differ are highlighted with color ("double" and "float" in this case). cute AND useful, we love a color-coded moment ๐
-fno-elide-typeโ okay so by default, when the C++ frontend prints diagnostics showing mismatching template types, the common parts of the types get printed as"[...]"to simplify the error message, right? Like:
could not convert 'std::map<int, std::vector<double> >()'
from 'map<[...],vector<double>>' to 'map<[...],vector<float>>
Specifying the -fno-elide-type flag suppresses that behavior. Bestie it also affects the output of the -fdiagnostics-show-template-tree flag, so keep that in mind.
-fdiagnostics-path-format=KINDโ specify how to print paths of control-flow events for diagnostics that have such a path associated with them.
KIND is none, separate-events, or inline-events, the default.
none means to not print diagnostic paths.
separate-events means to print a separate "note" diagnostic for each event within the diagnostic. For example:
test.c:29:5: error: passing NULL as argument 1 to 'PyList_Append' which requires a non-NULL parameter
test.c:25:10: note: (1) when 'PyList_New' fails, returning NULL
test.c:27:3: note: (2) when 'i < count'
test.c:29:5: note: (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
inline-events means to print the events "inline" within the source code. This view attempts to consolidate the events into runs of sufficiently-close events, printing them as labelled ranges within the source.
For example, the same events as above might be printed as:
'test': events 1-3
|
| 25 | list = PyList_New(0);
| | ^~~~~~~~~~~~~
| | |
| | (1) when 'PyList_New' fails, returning NULL
| 26 |
| 27 | for (i = 0; i < count; i++) {
| | ~~~
| | |
| | (2) when 'i < count'
| 28 | item = PyLong_FromLong(random());
| 29 | PyList_Append(list, item);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (3) when calling 'PyList_Append', passing NULL from (1) as argument 1
|
Interprocedural control flow is shown by grouping the events by stack frame, and using indentation to show how stack frames are nested, pushed, and popped. the way it just... nests them?? iconic
For example:
'test': events 1-2
|
| 133 | {
| | ^
| | |
| | (1) entering 'test'
| 134 | boxed_int *obj = make_boxed_int (i);
| | ~~~~~~~~~~~~~~~~~~
| | |
| | (2) calling 'make_boxed_int'
|
+--> 'make_boxed_int': events 3-4
|
| 120 | {
| | ^
| | |
| | (3) entering 'make_boxed_int'
| 121 | boxed_int *result = (boxed_int *)wrapped_malloc (sizeof (boxed_int));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling 'wrapped_malloc'
|
+--> 'wrapped_malloc': events 5-6
|
| 7 | {
| | ^
| | |
| | (5) entering 'wrapped_malloc'
| 8 | return malloc (size);
| | ~~~~~~~~~~~~~
| | |
| | (6) calling 'malloc'
|
<-------------+
|
'test': event 7
|
| 138 | free_boxed_int (obj);
| | ^~~~~~~~~~~~~~~~~~~~
| | |
| | (7) calling 'free_boxed_int'
|
(etc)
-fdiagnostics-show-path-depthsโ this option provides additional information when printing control-flow paths associated with a diagnostic.
If this option is provided then the stack depth will be printed for each run of events within -fdiagnostics-path-format=separate-events.
This is intended for use by GCC developers and plugin developers when debugging diagnostics that report interprocedural control flow. So like, if that's not you, it's giving "not your lane" bestie ๐
-fno-show-columnโ do not print column numbers in diagnostics. This may be necessary if diagnostics are being scanned by a program that does not understand the column numbers, such asdejagnu.-fdiagnostics-column-unit=UNITโ select the units for the column number. This affects traditional diagnostics (in the absence of-fno-show-column), as well as JSON format diagnostics if requested.
The default UNIT, display, considers the number of display columns occupied by each character. This may be larger than the number of bytes required to encode the character, in the case of tab characters, or it may be smaller, in the case of multibyte characters. For example, the character "GREEK SMALL LETTER PI (U+03C0)" occupies one display column, and its UTF-8 encoding requires two bytes; the character "SLIGHTLY SMILING FACE (U+1F642)" occupies two display columns, and its UTF-8 encoding requires four bytes. byte girlies stay losing, display girlies stay winning ๐
Setting UNIT to byte changes the column number to the raw byte count in all cases, as was traditionally output by GCC prior to version 11.1.0.
-fdiagnostics-column-origin=ORIGINโ select the origin for column numbers, i.e. the column number assigned to the first column. The default value of1corresponds to traditional GCC behavior and to the GNU style guide. Some utilities may perform better with an origin of0; any non-negative value may be specified.-fdiagnostics-escape-format=FORMATโ okay so when GCC prints pertinent source lines for a diagnostic it normally attempts to print the source bytes directly. But some diagnostics relate to encoding issues in the source file, such as malformed UTF-8, or issues with Unicode normalization. These diagnostics are flagged so that GCC will escape bytes that are not printable ASCII when printing their pertinent source lines.
This option controls how such bytes should be escaped.
The default FORMAT, unicode displays Unicode characters that are not printable ASCII in the form <U+XXXX>, and bytes that do not correspond to a Unicode character validly-encoded in UTF-8-encoded will be displayed as hexadecimal in the form <XX>.
For example, a source line containing the string before followed by the Unicode character U+03C0 ("GREEK SMALL LETTER PI", with UTF-8 encoding 0xCF 0x80) followed by the byte 0xBF (a stray UTF-8 trailing byte), followed by the string after will be printed for such a diagnostic as:
before<U+03C0><BF>after
Setting FORMAT to bytes will display all non-printable-ASCII bytes in the form <XX>, thus showing the underlying encoding of non-ASCII Unicode characters. For the example above, the following will be printed:
before<CF><80><BF>after
-fdiagnostics-format=FORMATโ select a different format for printing diagnostics.FORMATistextorjson. The default istext.
The json format consists of a top-level JSON array containing JSON objects representing the diagnostics. yes bestie, it's giving API energy โจ
The JSON is emitted as one line, without formatting; the examples below have been formatted for clarity.
Diagnostics can have child diagnostics. For example, this error and note:
misleading-indentation.c:15:3: warning: this 'if' clause does not
guard... [-Wmisleading-indentation]
15 | if (flag)
| ^~
misleading-indentation.c:17:5: note: ...this statement, but the latter
is misleadingly indented as if it were guarded by the 'if'
17 | y = 2;
| ^
might be printed in JSON form (after formatting) like this:
...where the "note" is a child of the "warning". ๐
A diagnostic has a "kind". If that's "warning", then there's an "option" key describing the command-line option that controls the warning.
A diagnostic can contain zero or more locations. Each location has an optional "label" string and up to three positions inside it: a "caret" position, plus optional "start" and "finish" positions. A position is described by a "file" name, a "line" number, and three numbers telling you about the column:
"display-column"โ counts display columns, so it accounts for tabs and multibyte characters."byte-column"โ counts raw bytes."column"โ equals one of the previous two, whichever one is dictated by the-fdiagnostics-column-unitoption.
All three columns are relative to the origin set by -fdiagnostics-column-origin, which is typically 1 but can be set to, like, 0 if you want compatibility with other utilities that number columns from 0. The column origin gets recorded in the JSON output in the "column-origin" tag. In the remaining examples below, the extra column number outputs are omitted for brevity, bestie.
So, for example, this error:
bad-binary-ops.c:64:23: error: invalid operands to binary + (have 'S' {aka
'struct s'} and 'T' {aka 'struct t'})
64 | return callee_4a () + callee_4b ();
| ~~~~~~~~~~~~ ^ ~~~~~~~~~~~~
| | |
| | T {aka struct t}
| S {aka struct s}
has three locations. Its primary location is at the + token at column 23. It has two secondary locations describing the left and right-hand sides of the expression, and those ones have labels. It might be printed in JSON form as:
{
"children": [],
"kind": "error",
"locations": [
{
"caret": {
"column": 23, "file": "bad-binary-ops.c", "line": 64
}
},
{
"caret": {
"column": 10, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 21, "file": "bad-binary-ops.c", "line": 64
},
"label": "S {aka struct s}"
},
{
"caret": {
"column": 25, "file": "bad-binary-ops.c", "line": 64
},
"finish": {
"column": 36, "file": "bad-binary-ops.c", "line": 64
},
"label": "T {aka struct t}"
}
],
"escape-source": false,
"message": "invalid operands to binary + ..."
}
If a diagnostic contains fix-it hints, it has a "fixits" array, made of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. For example, this diagnostic with a replacement fix-it hint:
demo.c:8:15: error: 'struct s' has no member named 'colour'; did you
mean 'color'?
8 | return ptr->colour;
| ^~~~~~
| color
might be printed in JSON form as:
{
"children": [],
"fixits": [
{
"next": {
"column": 21,
"file": "demo.c",
"line": 8
},
"start": {
"column": 15,
"file": "demo.c",
"line": 8
},
"string": "color"
}
],
"kind": "error",
"locations": [
{
"caret": {
"column": 15,
"file": "demo.c",
"line": 8
},
"finish": {
"column": 20,
"file": "demo.c",
"line": 8
}
}
],
"escape-source": false,
"message": "\u2018struct s\u2019 has no member named ..."
}
where the fix-it hint suggests replacing the text from "start" up to but not including "next" with "string"'s value. Deletions are expressed via an empty value for "string", and insertions by having "start" equal "next". ๐
If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing the events. Each event object has a "description" string, a "location" object, plus a "function" string and a "depth" number for representing interprocedural paths. The "function" represents the current function at that event, and the "depth" represents the stack depth relative to some baseline โ the higher it is, the more frames are within the stack.
For example, the intraprocedural example shown for -fdiagnostics-path-format= might have this JSON for its path:
"path": [
{
"depth": 0,
"description": "when 'PyList_New' fails, returning NULL",
"function": "test",
"location": {
"column": 10,
"file": "test.c",
"line": 25
}
},
{
"depth": 0,
"description": "when 'i < count'",
"function": "test",
"location": {
"column": 3,
"file": "test.c",
"line": 27
}
},
{
"depth": 0,
"description": "when calling 'PyList_Append', passing NULL from (1) as argument 1",
"function": "test",
"location": {
"column": 5,
"file": "test.c",
"line": 29
}
}
]
Diagnostics also have a boolean attribute called "escape-source", which hints whether non-ASCII bytes should be escaped when printing the pertinent lines of source code โ it's "true" for diagnostics involving source encoding issues. ๐ฆ
๐ฅ Options to Request or Suppress Warnings ๐ฅ
Warnings are diagnostic messages that report constructions that aren't inherently erroneous but that are risky or suggest there may have been an error. It's giving "hey bestie, maybe double-check this" energy. ๐
The following language-independent options don't enable specific warnings โ they just control the kinds of diagnostics GCC produces.
-fsyntax-onlyโ Check the code for syntax errors, but don't do anything beyond that. That's it, that's the whole job. โจ- *
-fmax-errors=n* โ Caps the maximum number of error messages at n, and once you hit that, GCC bails out instead of trying to keep processing the source code. If n is0(which is the default), there's no limit on the number of error messages produced. And if-Wfatal-errorsis also specified, then-Wfatal-errorstakes precedence over this option. Periodt. -wโ Inhibit all warning messages. Not one single warning. Silence. ๐คซ-Werrorโ Make all warnings into errors. Iconic, terrifying, effective. ๐-Werror=โ ok bestie, this one turns a specific warning into an actual error ๐ you tack the warning's specifier on the end. Like,-Werror=switchmakes everything controlled by-Wswitchinto errors. And it's got a negative form too, for negating-Werrorfor just one warning:-Wno-error=switchmakes-Wswitchwarnings not errors, even when-Werroris fully in effect. Periodt.
Every controllable warning's message includes the option that controls it, and you can feed that exact option into -Werror= and -Wno-error= like we just said. (Want to hide the option from the message? -fno-diagnostics-show-option has you covered.)
Heads up: saying-Werror=fooautomatically implies-Wfooโ the way that one works. But-Wno-error=fooimplies nothing. Not a thing. Zero.
-Wfatal-errorsโ makes the compiler rage-quit ๐ it aborts compilation on the first error instead of trying to keep going and printing even more error messages at you.
You can ask for tons of specific warnings with options that start with -W โ like -Wimplicit for warnings about implicit declarations โจ Every one of these specific warning options also has a negative form starting with -Wno- to turn the warning off, like -Wno-implicit. This manual only lists one of the two forms, whichever one isn't the default. For more language-specific options, go peek at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And you can get extra warnings by enabling the static analyzer ๐ฆ
Some options, like -Wall and -Wextra, turn on other options โ like -Wunused, which then turns on further options, like -Wunused-value. The combined effect of positive and negative forms is that more specific options beat less specific ones, no matter where they sit on the command line. If two options are the same specificity, the last one wins. And options turned on or off via pragmas act like they showed up at the very end of the command line ๐
When you ask for a warning option that isn't recognized (say, -Wunknown-warning), GCC emits a diagnostic saying it doesn't know that option. But the -Wno- form is lowkey different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are already being produced. This is so you can use shiny new -Wno- options with old compilers โ but if something goes wrong, the compiler warns you that an unrecognized option is hanging around ๐
The effectiveness of some warnings depends on optimizations being enabled too. For example -Wsuggest-final-types is more effective with link-time optimization, and some instances of other warnings might not get issued at all unless optimization is on. And while optimization generally improves the efficacy of control- and data-flow-sensitive warnings, in some cases it may also cause false positives ๐ญ
-Wpedantic,-pedanticโ issues all the warnings demanded by strict ISO C and ISO C++ ๐ธ It rejects every program that uses forbidden extensions, plus some other programs that just don't follow ISO C and ISO C++. For ISO C, it follows the version of the ISO C standard specified by whatever-stdoption you used.
Valid ISO C and ISO C++ programs should compile properly with or without this option (though a rare few need -ansi or a -std option specifying the required version of ISO C). Without this option, though, certain GNU extensions and traditional C and C++ features are supported too โ and with this option, they get rejected ๐
-Wpedantic does not warn about use of the alternate keywords whose names begin and end with __. That same alternate format can also be used to disable warnings for non-ISO __intN types, i.e. __intN__. Pedantic warnings are also disabled in the expression that follows __extension__. But bestie, only system header files should use these escape routes โ application programs should avoid them ๐ซถ
Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find it doesn't quite do what they want: it finds some non-ISO practices, but not all โ only those for which ISO C requires a diagnostic, and some others for which diagnostics have been added.
A feature to report any failure to conform to ISO C might be useful in some instances, but it'd require considerable additional work and would be quite different from -Wpedantic. We don't have plans to support such a feature in the near future.
Where the standard specified with -std represents a GNU extended dialect of C, like gnu90 or gnu99, there's a corresponding base standard โ the version of ISO C the GNU extended dialect is based on. Warnings from -Wpedantic are given where they're required by the base standard. (It doesn't make sense for such warnings to be given only for features not in the specified GNU C dialect, since by definition the GNU dialects of C include all features the compiler supports with the given option, and there'd be nothing to warn about ๐)
-pedantic-errorsโ gives an error whenever the base standard (see-Wpedantic) requires a diagnostic, in some cases where there's undefined behavior at compile-time, and in some other cases that don't prevent compilation of programs that are valid according to the standard ๐ฅ And ngl, this is not equivalent to-Werror=pedantic, because there are errors enabled by this option that aren't enabled by that one, and vice versa.-Wallโ turns on all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros โจ It also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.
-Wall turns on these warning flags:
-Waddress -Warray-bounds=1 (only with -O2) -Warray-compare
-Warray-parameter=2 (C and Objective-C only) -Wbool-compare
-Wbool-operation -Wc++11-compat -Wc++14-compat -Wcatch-value (C++
and Objective-C++ only) -Wchar-subscripts -Wcomment
-Wdangling-pointer=2 -Wduplicate-decl-specifier (C and Objective-C
only) -Wenum-compare (in C/ObjC; this is on by default in C++)
-Wformat -Wformat-overflow -Wformat-truncation -Wint-in-bool-context
-Wimplicit (C and Objective-C only) -Wimplicit-int (C and Objective-C
only) -Wimplicit-function-declaration (C and Objective-C only)
-Winit-self (only for C++) -Wlogical-not-parentheses -Wmain (only
for C/ObjC and unless -ffreestanding) -Wmaybe-uninitialized
-Wmemset-elt-size -Wmemset-transposed-args -Wmisleading-indentation
(only for C/C++) -Wmismatched-dealloc -Wmismatched-new-delete (only
for C/C++) -Wmissing-attributes -Wmissing-braces (only for C/ObjC)
-Wmultistatement-macros -Wnarrowing (only for C++) -Wnonnull
-Wnonnull-compare -Wopenmp-simd -Wparentheses -Wpessimizing-move
(only for C++) -Wpointer-sign -Wrange-loop-construct (only for C++)
-Wreorder -Wrestrict -Wreturn-type -Wsequence-point -Wsign-compare
(only in C++) -Wsizeof-array-div -Wsizeof-pointer-div
-Wsizeof-pointer-memaccess -Wstrict-aliasing -Wstrict-overflow=1
-Wswitch -Wtautological-compare -Wtrigraphs -Wuninitialized
-Wunknown-pragmas -Wunused-function -Wunused-label -Wunused-value
-Wunused-variable -Wuse-after-free=3 -Wvla-parameter (C and
Objective-C only) -Wvolatile-register-var -Wzero-length-bounds
Note that some warning flags are not implied by -Wall ๐ Some of them warn about constructions users generally don't consider questionable, but that you might occasionally want to check for; others warn about constructions that are necessary or hard to avoid in some cases, where there's no simple way to modify the code to suppress the warning. Some of them are enabled by -Wextra, but many of them must be enabled individually.
-Wextraโ enables some extra warning flags that aren't enabled by-Wall๐ (This option used to be called-W. The older name is still supported, but the newer name is more descriptive.)
-Wclobbered -Wcast-function-type -Wdeprecated-copy (C++ only)
-Wempty-body -Wenum-conversion (C only) -Wignored-qualifiers
-Wimplicit-fallthrough=3 -Wmissing-field-initializers
-Wmissing-parameter-type (C only) -Wold-style-declaration (C only)
-Woverride-init -Wsign-compare (C only) -Wstring-compare
-Wredundant-move (only for C++) -Wtype-limits -Wuninitialized
-Wshift-negative-value (in C++11 to C++17 and in C99 and newer)
-Wunused-parameter (only with -Wunused or -Wall)
-Wunused-but-set-parameter (only with -Wunused or -Wall)
The option -Wextra also prints warning messages for these cases:
- A pointer is compared against integer zero with
"<","<=",">", or">=". - (C++ only) An enumerator and a non-enumerator both appear in a conditional expression.
- (C++ only) Ambiguous virtual bases.
- (C++ only) Subscripting an array that has been declared
"register". - (C++ only) Taking the address of a variable that has been declared
"register". - (C++ only) A base class is not initialized in the copy constructor of a derived class.
-Wabi(C, Objective-C, C++ and Objective-C++ only) โ warns about code affected by ABI changes ๐ This includes code that may not be compatible with the vendor-neutral C++ ABI, as well as the psABI for the particular target.
Since G++ now defaults to updating the ABI with each major release, normally -Wabi warns only about C++ ABI compatibility problems if a check was added later in a release series for an ABI issue discovered since the initial release. -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).
-Wabi can also be used with an explicit version number to warn about C++ ABI compatibility with a particular -fabi-version level, e.g. -Wabi=2 to warn about changes relative to -fabi-version=2.
If an explicit version number is provided and -fabi-compat-version is not specified, the version number from this option is used for compatibility aliases. If no explicit version number is provided with this option, but -fabi-compat-version is specified, that version number is used for C++ ABI warnings ๐
okay so bestie, they tried to warn you about every single one of these cases, but lowkey there are probably still some sneaky ones that don't get a warning even though G++ is out here generating incompatible code. ๐ญ And sometimes the opposite happens too โ you get a warning even though the code it generates is actually compatible. ๐คทโโ๏ธ
If you're stressed about the fact that G++-generated code might not be binary compatible with code from other compilers, you should fr rewrite your code to dodge these warnings. ๐
Here's the tea on known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9): โ๏ธ
- A template with a non-type template parameter of reference type was mangled incorrectly:
extern int N;
template <int &> struct S {};
void n (S<N>) {2}
This was fixed in -fabi-version=3. โจ
- SIMD vector types declared using
"__attribute ((vector_size))"were mangled in a non-standard way that does not allow for overloading of functions taking vectors of different sizes.
The mangling was changed in -fabi-version=4. ๐
"__attribute ((const))"andnoreturnwere mangled as type qualifiers, anddecltypeof a plain declaration was folded away.
These mangling issues were fixed in -fabi-version=5. ๐
- Scoped enumerators passed as arguments to a variadic function are promoted like unscoped enumerators, causing
va_argto complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller thanint.
Also, the ABI changed the mangling of template argument packs, const_cast, static_cast, prefix increment/decrement, and a class scope function used as a template argument.
These issues were corrected in -fabi-version=6. ๐
- Lambdas in default argument scope were mangled incorrectly, and the ABI changed the mangling of
nullptr_t.
These issues were corrected in -fabi-version=7. ๐ฆ
- When mangling a function type with function-cv-qualifiers, the un-qualified function type was incorrectly treated as a substitution candidate.
This was fixed in -fabi-version=8, the default for GCC 5.1. ๐ธ
decltype(nullptr)incorrectly had an alignment of 1, leading to unaligned accesses. Note that this did not affect the ABI of a function with anullptr_tparameter, as parameters have a minimum alignment.
This was fixed in -fabi-version=9, the default for GCC 5.2. โญ
- Target-specific attributes that affect the identity of a type, such as ia32 calling conventions on a function type (stdcall, regparm, etc.), did not affect the mangled name, leading to name collisions when function pointers were used as template arguments.
This was fixed in -fabi-version=10, the default for GCC 6.1. ๐
This option also turns on warnings about psABI-related changes. The known psABI changes at this point include: ๐
- For SysV/x86-64, unions with
long doublemembers are passed in memory as specified in psABI. Prior to GCC 4.4, this was not the case. For example:
union U {
long double ld;
int i;
};
union U is now always passed in memory. ๐ง
-Wchar-subscriptsโ Warn if an array subscript has typechar. This is a common cause of error, as programmers often forget that this type is signed on some machines. This warning is enabled by-Wall. ๐-Wno-coverage-mismatchโ Warn if feedback profiles do not match when using the-fprofile-useoption. If a source file is changed between compiling with-fprofile-generateand with-fprofile-use, the files with the profile feedback can fail to match the source file and GCC cannot use the profile feedback information. By default, this warning is enabled and is treated as an error.-Wno-coverage-mismatchcan be used to disable the warning or-Wno-error=coverage-mismatchcan be used to disable the error. Disabling the error for this warning can result in poorly optimized code and is useful only in the case of very minor changes such as bug fixes to an existing code-base. Completely disabling the warning is not recommended. ๐ฌ-Wno-coverage-invalid-line-numberโ Warn in case a function ends earlier than it begins due to an invalid linenum macros. The warning is emitted only with--coverageenabled.
By default, this warning is enabled and is treated as an error. -Wno-coverage-invalid-line-number can be used to disable the warning or -Wno-error=coverage-invalid-line-number can be used to disable the error. ๐ซถ
-Wno-cpp(C, Objective-C, C++, Objective-C++ and Fortran only) โ Suppress warning messages emitted by"#warning"directives.-Wdouble-promotion(C, C++, Objective-C and Objective-C++ only) โ Give a warning when a value of typefloatis implicitly promoted todouble. CPUs with a 32-bit "single-precision" floating-point unit implementfloatin hardware, but emulatedoublein software. On such a machine, doing computations usingdoublevalues is much more expensive because of the overhead required for software emulation.
It is easy to accidentally do computations with double because floating-point literals are implicitly of type double. For example, in:
float area(float radius)
{
return 3.14159 * radius * radius;
}
the compiler performs the entire computation with double because the floating-point literal is a double. ๐ญ
-Wduplicate-decl-specifier(C and Objective-C only) โ Warn if a declaration has duplicateconst,volatile,restrictor_Atomicspecifier. This warning is enabled by-Wall. ๐ฅ-Wformat,-Wformat=nโ Check calls toprintfandscanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense. This includes standard functions, and others specified by format attributes, in theprintf,scanf,strftimeandstrfmon(an X/Open extension, not in the C standard) families (or other target-specific families). Which functions are checked without format attributes having been specified depends on the standard version selected, and such checks of functions without the attribute specified are disabled by-ffreestandingor-fno-builtin.
The formats are checked against the format features supported by GNU libc version 2.2. These include all ISO C90 and C99 features, as well as features from the Single Unix Specification and some BSD and GNU extensions. Other library implementations may not support all these features; GCC does not support warning about features that go beyond a particular library's limitations. However, if -Wpedantic is used with -Wformat, warnings are given about format features not in the selected standard version (but not for strfmon formats, since those are not in any version of the C standard).
-Wformat=1-Wformatโ Option-Wformatis equivalent to-Wformat=1, and-Wno-formatis equivalent to-Wformat=0. Since-Wformatalso checks for null format arguments for several functions,-Wformatalso implies-Wnonnull. Some aspects of this level of format checking can be disabled by the options:-Wno-format-contains-nul,-Wno-format-extra-args, and-Wno-format-zero-length.-Wformatis enabled by-Wall.-Wformat=2โ Enable-Wformatplus additional format checks. Currently equivalent to-Wformat -Wformat-nonliteral -Wformat-security -Wformat-y2k. ๐
-Wno-format-contains-nulโ If-Wformatis specified, do not warn about format strings that contain NUL bytes.-Wno-format-extra-argsโ If-Wformatis specified, do not warn about excess arguments to aprintforscanfformat function. The C standard specifies that such arguments are ignored.
Where the unused arguments lie between used arguments that are specified with $ operand number specifications, normally warnings are still given, since the implementation could not know what type to pass to va_arg to skip the unused arguments. However, in the case of scanf formats, this option suppresses the warning if the unused arguments are all pointers, since the Single Unix Specification says that such unused arguments are allowed. ๐ฆ
-Wformat-overflow,-Wformat-overflow=levelโ Warn about calls to formatted input/output functions such assprintfandvsprintfthat might overflow the destination buffer. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives.-Wformat-overflow-Wformat-overflow=1โ Level 1 of-Wformat-overflowenabled by-Wformatemploys a conservative approach that warns only about calls that most likely overflow the buffer. At this level, numeric arguments to format directives with unknown values are assumed to have the value of one, and strings of unknown length to be empty. Numeric arguments that are known to be bounded to a subrange of their type, or string arguments whose output is bounded either by their directive's precision or by a finite set of string literals, are assumed to take on the value within the range that results in the most bytes on output. For example, the call tosprintfbelow is diagnosed because even with both a and b equal to zero, the terminating NUL character ('\0') appended by the function to the destination buffer will be written past its end. Increasing the size of the buffer by a single byte is sufficient to avoid the warning, though it may not be sufficient to avoid the overflow.
void f (int a, int b)
{
char buf [13];
sprintf (buf, "a = %i, b = %i\n", a, b);
}
-Wformat-overflow=2โ bestie, level 2 is the extra version: it also warns about calls that might overflow the destination buffer given an argument of sufficient length or magnitude. At level 2, unknown numeric arguments are assumed to have the minimum representable value for signed types with a precision greater than 1, and the maximum representable value otherwise. Unknown string arguments whose length cannot be assumed to be bounded either by the directive's precision, or by a finite set of string literals they may evaluate to, or the character array they may point to, are assumed to be 1 character long. ๐ญ
At level 2, the call in the example above is again diagnosed, but this time because with a equal to a 32-bit INT_MIN the first %i directive will write some of its digits beyond the end of the destination buffer. To make the call safe regardless of the values of the two variables, the size of the destination buffer must be increased to at least 34 bytes. GCC includes the minimum size of the buffer in an informational note following the warning. 34 bytes, no cap.
An alternative to increasing the size of the destination buffer is to constrain the range of formatted values. The maximum length of string arguments can be bounded by specifying the precision in the format directive. When numeric arguments of format directives can be assumed to be bounded by less than the precision of their type, choosing an appropriate length modifier to the format specifier will reduce the required buffer size. For example, if a and b in the example above can be assumed to be within the precision of the short int type then using either the %hi format directive or casting the argument to short reduces the maximum required size of the buffer to 24 bytes. 24 bytes, we love a glow-down.
void f (int a, int b)
{
char buf [23];
sprintf (buf, "a = %hi, b = %i\n", a, (short)b);
}
-Wno-format-zero-lengthโ if-Wformatis specified, don't warn about zero-length formats. The C standard specifies that zero-length formats are allowed. ๐ so like, they're legal, chill.-Wformat-nonliteralโ if-Wformatis specified, also warn if the format string is not a string literal and so cannot be checked, unless the format function takes its format arguments as ava_list.-Wformat-securityโ if-Wformatis specified, also warn about uses of format functions that represent possible security problems. At present, this warns about calls toprintfandscanffunctions where the format string is not a string literal and there are no format arguments, as inprintf (foo);. This may be a security hole if the format string came from untrusted input and contains%n. ๐จ security hole energy, be careful bestie. (This is currently a subset of what-Wformat-nonliteralwarns about, but in future warnings may be added to-Wformat-securitythat are not included in-Wformat-nonliteral.)-Wformat-signednessโ if-Wformatis specified, also warn if the format string requires an unsigned argument and the argument is signed and vice versa. signed? unsigned? pick a lane โจ-Wformat-truncation- *
-Wformat-truncation=level* โ warn about calls to formatted input/output functions such assnprintfandvsnprintfthat might result in output truncation. When the exact number of bytes written by a format directive cannot be determined at compile-time it is estimated based on heuristics that depend on the level argument and on optimization. While enabling optimization will in most cases improve the accuracy of the warning, it may also result in false positives. Except as noted otherwise, the option uses the same logic-Wformat-overflow. ๐ฆ-Wformat-truncation-Wformat-truncation=1โ level 1 of-Wformat-truncationenabled by-Wformatemploys a conservative approach that warns only about calls to bounded functions whose return value is unused and that will most likely result in output truncation.-Wformat-truncation=2โ level 2 warns also about calls to bounded functions whose return value is used and that might result in truncation given an argument of sufficient length or magnitude.
-Wformat-y2kโ if-Wformatis specified, also warn aboutstrftimeformats that may yield only a two-digit year. the year 2000 called, it wants its bug back ๐-Wnonnullโ warn about passing a null pointer for arguments marked as requiring a non-null value by thenonnullfunction attribute. passing NULL when it said non-null? not the vibe.
-Wnonnull is included in -Wall and -Wformat. It can be disabled with the -Wno-nonnull option.
-Wnonnull-compareโ warn when comparing an argument marked with thenonnullfunction attribute against null inside the function. comparing a definitely-not-null thing to null? make it make sense ๐ญ
-Wnonnull-compare is included in -Wall. It can be disabled with the -Wno-nonnull-compare option.
-Wnull-dereferenceโ warn if the compiler detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer. This option is only active when-fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. The precision of the warnings depends on the optimization options used. undefined behavior is NOT the moment, fr fr.-Winfinite-recursionโ warn about infinitely recursive calls. The warning is effective at all optimization levels but requires optimization in order to detect infinite recursion in calls between two or more functions.-Winfinite-recursionis included in-Wall. it's giving "function calls itself forever" main character energy ๐-Winit-self(C, C++, Objective-C and Objective-C++ only) โ warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the-Wuninitializedoption. you cannot initializeiwithi, bestie, that's not how this works ๐ญ
For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:
int f()
{
int i = i;
return i;
}
This warning is enabled by -Wall in C++.
-Wno-implicit-int(C and Objective-C only) โ this option controls warnings when a declaration does not specify a type. This warning is enabled by default in C99 and later dialects of C, and also by-Wall.-Wno-implicit-function-declaration(C and Objective-C only) โ this option controls warnings when a function is used before being declared. This warning is enabled by default in C99 and later dialects of C, and also by-Wall. The warning is made into an error by-pedantic-errors. yes, it becomes a full ERROR. periodt.-Wimplicit(C and Objective-C only) โ same as-Wimplicit-intand-Wimplicit-function-declaration. This warning is enabled by-Wall.-Wimplicit-fallthroughโ-Wimplicit-fallthroughis the same as-Wimplicit-fallthrough=3and-Wno-implicit-fallthroughis the same as-Wimplicit-fallthrough=0.- *
-Wimplicit-fallthrough=n* โ warn when a switch case falls through. For example: the "oops I forgot a break" classic ๐
switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;
case 3:
a = 3;
break;
}
This warning does not warn when the last statement of a case cannot fall through, e.g. when there is a return statement or a call to function declared with the noreturn attribute. -Wimplicit-fallthrough= also takes into account control flow statements, such as ifs, and only warns when appropriate. E.g.
switch (cond)
{
case 1:
if (i > 3) {
bar (5);
break;
} else if (i < 1) {
bar (0);
} else
return;
default:
...
}
Since there are occasions where a switch case fall through is desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that is to be used along with a null statement to suppress this warning that would normally occur:
switch (cond)
{
case 1:
bar (0);
__attribute__ ((fallthrough));
default:
...
}
C++17 provides a standard way to suppress the -Wimplicit-fallthrough warning using [[fallthrough]]; instead of the GNU attribute. In C++11 or C++14 users can use [[gnu::fallthrough]];, which is a GNU extension. Instead of these attributes, it is also possible to add a fallthrough comment to silence the warning. The whole body of the C or C++ style comment should match the given regular expressions listed below. The option argument n specifies what kind of comments are accepted:
-Wimplicit-fallthrough=0disables the warning altogether. silence, iconic.-Wimplicit-fallthrough=1matches.*regular expression, any comment is used as fallthrough comment.-Wimplicit-fallthrough=2case insensitively matches.*falls?[ \t-]*thr(ough|u).*regular expression.-Wimplicit-fallthrough=3case sensitively matches one of the following regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t.!]*(ELSE,? |INTENTIONAL(LY)? )?FALL(S | |-)?THR(OUGH|U)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*(Else,? |Intentional(ly)? )?Fall((s | |-)[Tt]|t)hr(ough|u)[ \t.!]*(-[^\n\r]*)?""[ \t.!]*([Ee]lse,? |[Ii]ntentional(ly)? )?fall(s | |-)?thr(ough|u)[ \t.!]*(-[^\n\r]*)?"
-Wimplicit-fallthrough=4case sensitively matches one of the following regular expressions:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5doesn't recognize any comments as fallthrough comments, only attributes disable the warning.
The comment needs to be followed after optional whitespace and other comments by case or default keywords or by a user label that precedes some case or default label. like this, bestie:
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra. โจ the default one, the moment, the icon โจ
๐ธ -Wno-if-not-aligned (C, C++, Objective-C and Objective-C++ only)
okay so this one is the vibe check for warnings triggered by the warn_if_not_aligned attribute โ it controls whether they get issued at all. and bestie, heads up: these warnings are enabled by default. ๐
๐ธ -Wignored-qualifiers (C and C++ only)
warn if the return type of a function has a type qualifier like const. for ISO C that qualifier literally does nothing, because the value a function returns isn't an lvalue โ it's giving pointless. for C++, the warning only fires for scalar types or void. and ISO C flat-out prohibits qualified void return types on function definitions, so those return types always get a warning, even without this option. rude but fair.
this warning is also enabled by -Wextra.
โจ -Wno-ignored-attributes (C and C++ only)
this option controls warnings when an attribute is ignored. and it's different from -Wattributes, bestie โ this one yells whenever the compiler decides to drop an attribute, not when the attribute is unknown or used in a wrong place or whatever. this warning is enabled by default. ๐
๐ฅ -Wmain
warn if the type of main is suspicious. main should be a function with external linkage, returning int, taking either zero arguments, two, or three arguments of appropriate types. main character energy only, no impostors. ๐
this warning is enabled by default in C++ and is enabled by either -Wall or -Wpedantic.
๐ฆ -Wmisleading-indentation (C and C++ only)
warn when the indentation of the code does not reflect the block structure. specifically, a warning is issued for if, else, while, and for clauses with a guarded statement that doesn't use braces, followed by an unguarded statement with the same indentation. likeโฆ the code is lying to your face about its structure. ๐ญ
in the following example, the call to bar is misleadingly indented as if it were guarded by the if conditional.
if (some_condition ())
foo ();
bar (); /* Gotcha: this is not guarded by the "if". */
in the case of mixed tabs and spaces, the warning uses the -ftabstop= option to determine if the statements line up (defaulting to 8).
the warning is not issued for code involving multiline preprocessor logic such as the following example.
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
the warning is also not issued after a #line directive, since that typically means autogenerated code, and no assumptions can be made about the layout of the file the directive references. we simply do not know her. ๐
this warning is enabled by -Wall in C and C++.
๐ -Wmissing-attributes
warn when a declaration of a function is missing one or more attributes that a related function is declared with, and whose absence may adversely affect the correctness or efficiency of generated code. for example, the warning is issued for declarations of aliases that use attributes to specify less restrictive requirements than those of their targets. this typically represents a potential optimization opportunity โ free glow-up just sitting there. โจ
by contrast, the -Wattribute-alias=2 option controls warnings issued when the alias is more restrictive than the target, which could lead to incorrect code generation. ๐ฌ
attributes considered include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice.
in C++, the warning is issued when an explicit specialization of a primary template declared with attribute alloc_align, alloc_size, assume_aligned, format, format_arg, malloc, or nonnull is declared without it. attributes deprecated, error, and warning suppress the warning.
you can use the copy attribute to apply the same set of attributes to a declaration as that on another declaration, without explicitly enumerating the attributes. this attribute can be applied to declarations of functions, variables, or types.
-Wmissing-attributes is enabled by -Wall.
for example, since the declaration of the primary function template below makes use of both attribute malloc and alloc_size, the declaration of the explicit specialization of the template is diagnosed because it's missing one of the attributes.
template <class T>
T* __attribute__ ((malloc, alloc_size (1)))
allocate (size_t);
template <>
void* __attribute__ ((malloc)) // missing alloc_size
allocate<void> (size_t);
๐ -Wmissing-braces
warn if an aggregate or union initializer isn't fully bracketed. in the following example, the initializer for a is not fully bracketed, but the one for b is fully bracketed. b ate and left no crumbs. ๐
int a[2][2] = { 0, 1, 2, 3 };
int b[2][2] = { { 0, 1 }, { 2, 3 } };
this warning is enabled by -Wall.
๐ -Wmissing-include-dirs (C, C++, Objective-C, Objective-C++ and Fortran only)
warn if a user-supplied include directory does not exist. this option is disabled by default for C, C++, Objective-C and Objective-C++. for Fortran, it is partially enabled by default, by warning for -I and -J only. so, like, not all dirs get the vibe check.
๐ญ -Wno-missing-profile
this option controls warnings if feedback profiles are missing when using the -fprofile-use option. it diagnoses those cases where a new function or a new file is added between compiling with -fprofile-generate and with -fprofile-use, without regenerating the profiles. in these cases, the profile feedback data files don't contain any profile feedback information for the newly added function or file respectively. also, when profile count data (.gcda) files are removed, GCC cannot use any profile feedback information. in all these cases, warnings are issued to inform you that a profile generation step is due. ๐
ignoring the warning can result in poorly optimized code. -Wno-missing-profile can be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified.
๐ -Wmismatched-dealloc
warn for calls to deallocation functions with pointer arguments returned from allocation functions for which the former isn't a suitable deallocator. a pair of functions can be associated as matching allocators and deallocators by use of attribute malloc.
unless disabled by the -fno-builtin option, the standard functions calloc, malloc, realloc, and free, as well as the corresponding forms of C++ operator new and operator delete, are implicitly associated as matching allocators and deallocators. in the following example, mydealloc is the deallocator for pointers returned from myalloc.
void mydealloc (void*);
__attribute__ ((malloc (mydealloc, 1))) void*
myalloc (size_t);
void f (void)
{
void *p = myalloc (32);
// ...use p...
free (p); // warning: not a matching deallocator for myalloc
mydealloc (p); // ok
}
in C++, the related option -Wmismatched-new-delete diagnoses mismatches involving either operator new or operator delete.
option -Wmismatched-dealloc is included in -Wall. โจ
๐
-Wmultistatement-macros
warn about unsafe multiple statement macros that appear to be guarded by a clause such as if, else, for, switch, or while, in which only the first statement is actually guarded after the macro is expanded. the macro is out here pretending to be one thing and doing another. ๐
for example:
#define DOIT x++; y++
if (c)
DOIT;
will increment y unconditionally, not just when c holds. this can usually be fixed by wrapping the macro in a do-while loop:
#define DOIT do { x++; y++; } while (0)
if (c)
DOIT;
this warning is enabled by -Wall in C and C++.
๐ฅ -Wparentheses
warn if parentheses are omitted in certain contexts, such as when there's an assignment in a context where a truth value is expected, or when operators are nested whose precedence people often get confused about. ngl, operator precedence has ended friendships.
also warn if a comparison like x<=y<=z appears; this is equivalent to (x<=y ? 1 : 0) <= z, which is a different interpretation from that of ordinary mathematical notation. math girlies, stay calm. ๐ญ
also warn for dangerous uses of the GNU extension to ?: with an omitted middle operand. when the condition in the ?: operator is a boolean expression, the omitted value is always 1. often programmers expect it to be a value computed inside the conditional expression instead. it is not. that's the whole trap.
for C++, this also warns for some cases of unnecessary parentheses in declarations, which can indicate an attempt at a function call instead of a declaration:
{
// Declares a local variable called mymutex.
std::unique_lock<std::mutex> (mymutex);
// User meant std::unique_lock<std::mutex> lock (mymutex);
}
this warning is enabled by -Wall.
๐ฆ -Wsequence-point
warn about code that may have undefined semantics because of violations of sequence point rules in the C and C++ standards. ๐
the C and C++ standards define the order in which expressions in a C/C++ program are evaluated in terms of sequence points, which represent a partial ordering between the execution of parts of the program: those executed before the sequence point, and those executed after it. these occur:
- after the evaluation of a full expression (one which is not part of a larger expression),
- after the evaluation of the first operand of a
&&,||,? :or,(comma) operator, - before a function is called (but after the evaluation of its arguments and the expression denoting the called function),
- and in certain other places.
other than as expressed by the sequence point rules, the order of evaluation of subexpressions of an expression is not specified. all these rules describe only a partial order rather than a total order, since, for example, if two functions are called within one expression with no sequence point between them, the order in which the functions are called is not specified. however, the standards committee have ruled that function calls do not overlap. so likeโฆ no cutting in line, but also no promises about who's first. ๐
It's not, like, specified when between sequence points your modifications to object values actually take effect? So if your program's behavior depends on that, congrats bestie, that's undefined behavior. The C and C++ standards literally say: "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored." Break those rules and the results on any particular implementation are entirely unpredictable. ๐
Classic examples of code with undefined behavior: a = a++;, a[n] = b[n++] and a[i++] = i;. Some messier cases don't get caught by this option, and it can throw the occasional false positive, but ngl it's been found pretty effective at sniffing out this kind of problem in real programs. โจ
The C++17 standard is gonna define the order of evaluation of operands in more cases โ specifically it requires that the right-hand side of an assignment be evaluated before the left-hand side, so those examples above stop being undefined. But this option will still warn about them, to help people avoid writing code that's undefined in C and earlier revisions of C++. ๐ซถ
The standard is worded confusingly, so there's some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem (including proposed formal definitions) live on the GCC readings page at <https://gcc.gnu.org/readings.html>.
This warning is enabled by -Wall for C and C++.
-Wno-return-local-addrโ Don't warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. Bye to that warning ๐-Wreturn-typeโ Warn whenever a function is defined with a return type that defaults toint. Also warn about anyreturnstatement with no return value in a function whose return type isn'tvoid(falling off the end of the function body counts as returning without a value).
For C only, warn about a return statement with an expression in a function whose return type is void, unless the expression type is also void. As a GNU extension, that latter case is accepted without a warning unless -Wpedantic is used. Attempting to use the return value of a non-void function other than main that flows off the end by reaching the closing curly brace that terminates the function is undefined.
Unlike in C, in C++, flowing off the end of a non-void function other than main results in undefined behavior even when the value of the function is not used. ๐ญ
This warning is enabled by default in C++ and by -Wall otherwise.
-Wno-shift-count-negativeโ Controls warnings if a shift count is negative. This warning is enabled by default.-Wno-shift-count-overflowโ Controls warnings if a shift count is greater than or equal to the bit width of the type. This warning is enabled by default.-Wshift-negative-valueโ Warn if left shifting a negative value. This warning is enabled by-Wextrain C99 (and newer) and C++11 to C++17 modes.-Wno-shift-overflow-Wshift-overflow=nโ These options control warnings about left shift overflows.-Wshift-overflow=1โ This is the warning level of-Wshift-overflowand is enabled by default in C99 and C++11 modes (and newer). This warning level does not warn about left-shifting 1 into the sign bit. (However, in C, such an overflow is still rejected in contexts where an integer constant expression is required.) No warning is emitted in C++20 mode (and newer), as signed left shifts always wrap. ๐-Wshift-overflow=2โ This warning level also warns about left-shifting 1 into the sign bit, unless C++14 mode (or newer) is active.
-Wswitchโ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration. (The presence of adefaultlabel prevents this warning.)caselabels outside the enumeration range also provoke warnings when this option is used (even if there is adefaultlabel). This warning is enabled by-Wall.-Wswitch-defaultโ Warn whenever aswitchstatement does not have adefaultcase.-Wswitch-enumโ Warn whenever aswitchstatement has an index of enumerated type and lacks acasefor one or more of the named codes of that enumeration.caselabels outside the enumeration range also provoke warnings when this option is used. The only difference between-Wswitchand this option is that this one gives a warning about an omitted enumeration code even if there's adefaultlabel. no escape ๐-Wno-switch-boolโ Do not warn when aswitchstatement has an index of boolean type and the case values are outside the range of a boolean type. You can also suppress this warning by casting the controlling expression to a type other thanbool. For example:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs.
-Wno-switch-outside-rangeโ This option controls warnings when aswitchcase has a value that is outside of its respective type range. This warning is enabled by default for C and C++ programs.-Wno-switch-unreachableโ Do not warn when aswitchstatement contains statements between the controlling expression and the first case label, which will never be executed. For example:
switch (cond)
{
i = 15;
...
case 5:
...
}
-Wswitch-unreachable does not warn if the statement between the controlling expression and the first case label is just a declaration:
switch (cond)
{
int i;
...
case 5:
i = 5;
...
}
This warning is enabled by default for C and C++ programs.
-Wsync-nand(C and C++ only) โ Warn when__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions are used. These functions changed semantics in GCC 4.4. ๐ฐ๏ธ-Wtrivial-auto-var-initโ Warn when-ftrivial-auto-var-initcannot initialize the automatic variable. A common situation is an automatic variable that is declared between the controlling expression and the first case label of aswitchstatement.-Wunused-but-set-parameterโ Warn whenever a function parameter is assigned to, but otherwise unused (aside from its declaration).
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused together with -Wextra.
-Wunused-but-set-variableโ Warn whenever a local variable is assigned to, but otherwise unused (aside from its declaration). This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
This warning is also enabled by -Wunused, which is enabled by -Wall.
-Wunused-functionโ Warn whenever a static function is declared but not defined, or a non-inline static function is unused. This warning is enabled by-Wall.-Wunused-labelโ Warn whenever a label is declared but not used. This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
-Wunused-local-typedefs(C, Objective-C, C++ and Objective-C++ only) โ Warn when a typedef locally defined in a function is not used. This warning is enabled by-Wall.-Wunused-parameterโ Warn whenever a function parameter is unused aside from its declaration.
To suppress this warning use the unused attribute.
-Wno-unused-resultโ Do not warn if a caller of a function marked with attributewarn_unused_resultdoes not use its return value. The default is-Wunused-result.-Wunused-variableโ Warn whenever a local or static variable is unused aside from its declaration. This option implies-Wunused-const-variable=1for C, but not for C++. This warning is enabled by-Wall.
To suppress this warning use the unused attribute.
-Wunused-const-variable-Wunused-const-variable=nโ Warn whenever a constant static variable is unused aside from its declaration.-Wunused-const-variable=1is enabled by-Wunused-variablefor C, but not for C++. In C this declares variable storage, but in C++ this is not an error since const variables take the place of#defines.
To suppress this warning use the unused attribute.
-Wunused-const-variable=1โ This is the warning level that is enabled by-Wunused-variablefor C. It warns only about unused static const variables defined in the main compilation unit, but not about static const variables declared in any header included.-Wunused-const-variable=2โ This warning level also warns for unused constant static variables in headers (excluding system headers). This is the warning level of-Wunused-const-variableand must be explicitly requested, since in C++ this isn't an error and in C it might be harder to clean up all headers included. ๐ฎโ๐จ
-Wunused-valueโ Warn whenever a statement computes a result that is explicitly not used. To suppress this warning, cast the unused expression tovoid. This includes an expression-statement or the left-hand side of a comma expression that contains no side effects. For example, an expression such asx[i,j]causes a warning, whilex[(void)i,j]does not. ๐ฏ
This warning is enabled by -Wall.
-Wunusedโ All the above-Wunusedoptions combined. โจ
In order to get a warning about an unused function parameter, you must either specify -Wextra -Wunused (note that -Wall implies -Wunused), or separately specify -Wunused-parameter.
-Wuninitializedโ Warn if an object with automatic or allocated storage duration is used without having been initialized. In C++, also warn if a non-static reference or non-staticconstmember appears in a class without constructors.
In addition, if you pass a pointer (or, in C++, a reference) to an uninitialized object into a const-qualified argument of a built-in function that's known to read that object, this warning clocks it too. (For ordinary functions, you get -Wmaybe-uninitialized instead.)
If you want to catch code that uses a variable's own uninitialized value in its own initializer, bestie, that's a whole separate option: -Winit-self. Go look at it.
These warnings pop off for individual uninitialized elements of structs, unions, or array variables, and also for variables that are uninitialized as a whole. They do not happen for variables or elements declared volatile. And because these warnings depend on optimization, the exact variables or elements you get warned about depends on the precise optimization options and the version of GCC you're running. So like, results may vary ๐
Also note: there may be no warning about a variable that's only used to compute a value that itself is never used โ because those computations may get deleted by data flow analysis before the warnings even print. Gone. Deleted. Not me getting optimized out of existence ๐
In C++, this warning also drags uninitialized objects used in member-initializer-lists. For example, GCC warns about b being uninitialized in this little snippet:
struct A {
int a;
int b;
A() : a(b) { }
};
๐ง -Wno-invalid-memory-model
This one controls warnings for invocations of __atomic Builtins, __sync Builtins, and the C11 atomic generic functions whenever the memory consistency argument is either invalid for the operation or outside the range of values of the memory_order enumeration. Example time: since __atomic_store and __atomic_store_n are only defined for the relaxed, release, and sequentially consistent memory orders, this next bit of code gets diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default. It's just on. Always. Periodt.
๐ -Wmaybe-uninitialized
Okay so picture this: you've got an object with automatic or allocated storage duration. If there exists a path from the function entry to a use of the object that is initialized, but there also exist some other paths where the object is not initialized โ the compiler emits a warning if it can't prove those uninitialized paths never actually get executed at run time. Like, it's suspicious. It's giving "probably fine but I'm not signing off on this".
Plus: passing a pointer (or in C++, a reference) to an uninitialized object into a const-qualified function argument also gets diagnosed by this warning. (-Wuninitialized is the one that fires for built-in functions known to read the object.) And if you annotate the function with the attribute access (none), that tells GCC the argument isn't used to access the object, and boom โ warning avoided. ๐
These warnings are only possible in optimizing compilation, because otherwise GCC isn't even keeping track of the state of your variables. No optimization, no surveillance, no receipts.
They're made optional because GCC might not be able to tell when the code is correct even though it looks like it's got an error. Here's one example of how that can happen:
{
int x;
switch (y)
{
case 1: x = 1;
break;
case 2: x = 4;
break;
case 3: x = 5;
}
foo (x);
}
If the value of y is always 1, 2 or 3, then x is always initialized โ but GCC doesn't know that. It's not psychic, bestie. To suppress the warning, you need to provide a default case with assert(0) or similar code. Give it a lil safety net. ๐ซถ
This option also warns when a non-volatile automatic variable might be changed by a call to longjmp. The compiler only sees the calls to setjmp. It cannot know where longjmp will be called; honestly, a signal handler could call it at any point in the code. Which means you may get a warning even when there's genuinely no problem, because longjmp can't in fact be called at the place that would cause a problem. False alarm energy. ๐
Some spurious warnings can be avoided if you declare all the functions you use that never return as noreturn.
This warning is enabled by -Wall or -Wextra.
๐ป -Wunknown-pragmas
Warn when a #pragma directive shows up that GCC does not understand. And heads up: if this command-line option is used, warnings are issued even for unknown pragmas in system header files. That does not happen if the warnings are only enabled by the -Wall command-line option. So this one is the loud version. ๐ฅ
๐คซ -Wno-pragmas
Do not warn about misuses of pragmas โ stuff like incorrect parameters, invalid syntax, or conflicts between pragmas. See also -Wunknown-pragmas.
๐ซ -Wno-prio-ctor-dtor
Do not warn if a priority from 0 to 100 is used for a constructor or destructor. Here's the tea: the constructor and destructor attributes let you assign a priority to the constructor/destructor to control its order of execution before main is called or after it returns. But the priority values must be greater than 100, because the compiler reserves priority values between 0--100 for the implementation. Those numbers are taken, bestie. Not yours. ๐
โจ -Wstrict-aliasing
This option is only active when -fstrict-aliasing is active. It warns about code that might break the strict aliasing rules that the compiler is using for optimization. It doesn't catch all the cases, but it does attempt to catch the more common pitfalls. It's included in -Wall. And it is equivalent to -Wstrict-aliasing=3.
๐๏ธ -Wstrict-aliasing=n
Also only active when -fstrict-aliasing is active. Same deal: warns about code that might break the strict aliasing rules the compiler is using for optimization. Higher levels = higher accuracy (fewer false positives). Higher levels also = more effort, kind of like the way -O works. And just so we're clear: -Wstrict-aliasing is equivalent to -Wstrict-aliasing=3.
- Level 1 โ Most aggressive, quick, least accurate. Possibly useful when higher levels don't warn but
-fstrict-aliasingstill breaks the code, since it has very few false negatives. However, it has many false positives. Warns for all pointer conversions between possibly incompatible types, even if never dereferenced. Runs in the front end only. - Level 2 โ Aggressive, quick, not too precise. May still have many false positives (not as many as level 1 though), and few false negatives (but possibly more than level 1). Unlike level 1, it only warns when an address is taken. Warns about incomplete types. Runs in the front end only.
- Level 3 (default for
-Wstrict-aliasing) โ Should have very few false positives and few false negatives. Slightly slower than levels 1 or 2 when optimization is enabled. Takes care of the common pun+dereference pattern in the front end:*(int*)&some_float. If optimization is enabled, it also runs in the back end, where it deals with multiple statement cases using flow-sensitive points-to information. Only warns when the converted pointer is dereferenced. Does not warn about incomplete types.
๐ -Wstrict-overflow
๐ -Wstrict-overflow=n
This option is only active when signed overflow is undefined. It warns about cases where the compiler optimizes based on the assumption that signed overflow does not occur. Now, it does not warn about all cases where the code might overflow โ it only warns about cases where the compiler implements some optimization. So this warning depends on the optimization level. Lowkey the vibes are conditional.
An optimization that assumes signed overflow doesn't occur is perfectly safe if the values of the variables involved are such that overflow never does, in fact, occur. Which means this warning can easily give a false positive: a warning about code that isn't actually a problem. To help focus on important issues, several warning levels are defined. No warnings are issued for the use of undefined signed overflow when estimating how many iterations a loop requires โ in particular, when determining whether a loop will be executed at all.
-Wstrict-overflow=1โ Warn about cases that are both questionable and easy to avoid. For example, the compiler simplifiesx + 1 > xto 1. This level of-Wstrict-overflowis enabled by-Wall; higher levels are not, and must be explicitly requested.-Wstrict-overflow=2โ Also warn about other cases where a comparison is simplified to a constant. For example:abs (x) >= 0. This can only be simplified when signed integer overflow is undefined, becauseabs (INT_MIN)overflows toINT_MIN, which is less than zero.-Wstrict-overflow(with no level) is the same as-Wstrict-overflow=2.-Wstrict-overflow=3โ Also warn about other cases where a comparison is simplified. For example:x + 1 > 1is simplified tox > 0.-Wstrict-overflow=4โ Also warn about other simplifications not covered by the above cases. For example:(x * 10) / 5is simplified tox * 2.-Wstrict-overflow=5โ Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison. For example:x + 2 > yis simplified tox + 1 >= y. This is reported only at the highest warning level because this simplification applies to many comparisons, so this warning level gives a very large number of false positives. Like, an absurd amount. Buckle up. ๐ญ
๐ค -Wstring-compare
Warn for calls to strcmp and strncmp whose result is determined to be either zero or non-zero in tests for such equality โ owing to the length of one argument being greater than the size of the array the other argument is stored in (or the bound, in the case of strncmp). Such calls could be mistakes. For example, the call to strcmp below is diagnosed because its result is necessarily non-zero, irrespective of the contents of the array a.
extern char a[4];
void f (char *d)
{
strcpy (d, "string");
...
if (0 == strcmp (a, d)) // cannot be true
puts ("a and d are the same");
}
-Wstring-compare is enabled by -Wextra. ๐
-Wno-stringop-overflow-Wstringop-overflow-Wstringop-overflow=type
okay bestie this one is the buffer-overflow babysitter ๐
It yells at you when you call string-wrangling functions like memcpy and strcpy and the compiler can tell you're about to overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking used to figure out how big the destination actually is. That argument only means anything for functions that operate on character arrays โ it does nothing for raw memory functions like memcpy, which always use Object Size type-0, periodt.
The option also claps back at calls that specify a size bigger than the largest possible object, or at most SIZE_MAX / 2 bytes. It gives its best results with optimization turned on, but it can still catch a small subset of simple buffer overflows even without optimization, in calls to GCC built-in functions like __builtin_memcpy that correspond to the standard functions. In any case โ no cap โ the option warns about just a subset of the buffer overflows that the corresponding overflow checking built-ins detect.
For example, the option issues a warning for the strcpy call below because it copies at least 5 characters (the string "blue" including the terminating NUL) into the buffer of size 4. the audacity ๐ญ
enum Color { blue, purple, yellow };
const char* f (enum Color clr)
{
static char buf [4];
const char *str;
switch (clr)
{
case blue: str = "blue"; break;
case purple: str = "purple"; break;
case yellow: str = "yellow"; break;
}
return strcpy (buf, str); // warning here
}
Option -Wstringop-overflow=2 is enabled by default. ๐
-Wstringop-overflow-Wstringop-overflow=1
The -Wstringop-overflow=1 option uses type-zero Object Size Checking to figure out the sizes of destination objects. At this setting the option does not warn for writes past the end of subobjects of larger objects accessed by pointers, unless the size of the largest surrounding object is known. When the destination might be one of several objects, it's assumed to be the largest one of them. On Linux systems, with optimization enabled at this setting, the option warns for the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value. iykyk โจ
-Wstringop-overflow=2
The -Wstringop-overflow=2 option uses type-one Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflows when writing to members of the largest complete objects whose exact size is known. But โ plot twist โ it does not warn for excessive writes to those same members of unknown objects referenced by pointers, because those pointers might point to arrays containing unknown numbers of elements. This is the default setting of the option. ๐ซถ
-Wstringop-overflow=3
The -Wstringop-overflow=3 option uses type-two Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflowing the smallest object or data member. This is the most restrictive setting of the option, and it may result in warnings for safe code. drama alert ๐
-Wstringop-overflow=4
The -Wstringop-overflow=4 option uses type-three Object Size Checking to figure out the sizes of destination objects. At this setting the option warns about overflowing any data members, and when the destination is one of several objects it uses the size of the largest of them to decide whether to issue a warning. Similarly to -Wstringop-overflow=3, this setting of the option may result in warnings for benign code. it's giving overprotective bestie energy
-Wno-stringop-overread
Warns for calls to string manipulation functions like memchr, or strcpy, that are determined to read past the end of the source sequence. ๐
Option -Wstringop-overread is enabled by default. โจ
-Wno-stringop-truncation
Do not warn for calls to bounded string manipulation functions like strncat, strncpy, and stpncpy that may either truncate the copied string or leave the destination unchanged.
In the following example, the call to strncat specifies a bound that is less than the length of the source string. So the copy of the source gets truncated, and the call is diagnosed. To dodge the warning, use bufsize - strlen (buf) - 1) as the bound.
void append (char *buf, size_t bufsize)
{
strncat (buf, ".txt", 3);
}
Another example: the following call to strncpy copies to d just the characters preceding the terminating NUL, without appending the NUL to the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a common mistake, so the call is diagnosed. To avoid the warning when the result isn't expected to be NUL-terminated, call memcpy instead.
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
And in this next one, the call to strncpy specifies the size of the destination buffer as the bound. If the length of the source string is equal to or greater than this size, the result of the copy won't be NUL-terminated. So yeah, that call is diagnosed too. To avoid the warning, specify sizeof buf - 1 as the bound and set the last element of the buffer to NUL.
void copy (const char *s)
{
char buf[80];
strncpy (buf, s, sizeof buf);
...
}
When a character array is meant to store a sequence of bytes with no terminating NUL, you can annotate that array with attribute nonstring to avoid this warning. cute fix, right? But heads up: such arrays are not suitable arguments to functions that expect NUL-terminated strings. To help catch accidental misuses of those arrays, GCC issues warnings unless it can prove the use is safe. ๐ฆ
-Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc]
Warns for cases where adding an attribute might be beneficial. The attributes currently supported are listed below. let's go one by one bestie โจ
-Wsuggest-attribute=pure-Wsuggest-attribute=const-Wsuggest-attribute=noreturn-Wmissing-noreturn-Wsuggest-attribute=malloc
Warns about functions that might be candidates for attributes pure, const or noreturn or malloc. The compiler only warns for functions visible in other compilation units, or โ in the case of pure and const โ if it can't prove that the function returns normally. A function returns normally if it doesn't contain an infinite loop or return abnormally by throwing, calling abort or trapping. This analysis needs option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels improve the accuracy of the analysis. ๐ฅ
-Wsuggest-attribute=format-Wmissing-format-attribute
Warns about function pointers that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. GCC guesses that function pointers with format attributes that are used in assignment, initialization, parameter passing or return statements should have a corresponding format attribute in the resulting type. I.e. the left-hand side of the assignment or initialization, the type of the parameter variable, or the return type of the containing function respectively should also have a format attribute to avoid the warning.
GCC also warns about function definitions that might be candidates for format attributes. Again, these are only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls a function like vprintf or vscanf, but that might not always be the case, and some functions for which format attributes are appropriate may not be detected. it's a vibe guess, not a verdict ๐
-Wsuggest-attribute=cold
Warns about functions that might be candidates for cold attribute. This is based on static detection and generally only warns about functions which always lead to a call to another cold function, like wrappers of C++ throw or fatal error reporting functions leading to abort. ๐ฅถ
-Walloc-zero
Warns about calls to allocation functions decorated with attribute alloc_size that specify zero bytes, including calls to the built-in forms of the functions aligned_alloc, alloca, calloc, malloc, and realloc. Because the behavior of these functions when called with a zero size differs among implementations (and in the case of realloc has been deprecated), relying on it may result in subtle portability bugs and should be avoided. just don't do it bestie ๐ญ
-Walloc-size-larger-than=byte-size
Warns about calls to functions decorated with attribute alloc_size that attempt to allocate objects larger than the specified number of bytes, or where the result of the size computation in an integer type with infinite precision would exceed the value of PTRDIFF_MAX on the target. -Walloc-size-larger-than=PTRDIFF_MAX is enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size of SIZE_MAX or more, or by -Wno-alloc-size-larger-than. โจ
-Wno-alloc-size-larger-than
Disables -Walloc-size-larger-than= warnings. The option is equivalent to -Walloc-size-larger-than=SIZE_MAX or larger. ๐
-Walloca
This option warns on all uses of alloca in the source. every. single. one. ๐
-Walloca-larger-than=byte-size
This option warns on calls to alloca with an integer argument whose value is either zero, or that is not bounded by a controlling predicate that limits its value to at most byte-size. It also warns for calls to alloca where the bound value is unknown. Arguments of non-integer types are considered unbounded even if they appear to be constrained to the expected range.
For example, a bounded case of alloca could be:
void func (size_t n)
{
void *p;
if (n <= 1000)
p = alloca (n);
else
p = malloc (n);
f (p);
}
okay so in that lil example up there, if you passed -Walloca-larger-than=1000 it would NOT yell at you, because the call to alloca is known to be at most 1000 bytes. bestie it did the math. but if you passed -Walloca-larger-than=500 instead? ๐จ the compiler would emit a warning. caught in 4k.
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. like, nothing is holding it back. it's giving chaos. for example:
void func ()
{
void *p = alloca (n);
f (p);
}
If -Walloca-larger-than=500 were passed, the above would trigger a warning โ but this time because of the lack of bounds checking. no bounds, no vibes, no peace. ๐ญ
Note, that even seemingly correct code involving signed integers could cause a warning:
void func (signed int n)
{
if (n < 500)
{
p = alloca (n);
f (p);
}
}
In the above example, n could be negative, causing a larger than expected argument to be implicitly cast into the alloca call. sneaky!! signed integers stay lying. ๐
This option also warns when alloca is used in a loop. ๐ yes bestie, loops count.
-Walloca-larger-than=PTRDIFF_MAX is enabled by default but is usually only effective when -ftree-vrp is active (default for -O2 and above).
See also -Wvla-larger-than=byte-size. ๐ซถ
-Wno-alloca-larger-thanโ Disable-Walloca-larger-than=warnings. The option is equivalent to-Walloca-larger-than=SIZE_MAXor larger. aka: turning the whole thing off off. โจ-Warith-conversionโ Do warn about implicit conversions from arithmetic operations even when conversion of the operands to the same type cannot change their values. This affects warnings from-Wconversion,-Wfloat-conversion, and-Wsign-conversion.
void f (char c, int i)
{
c = c + i; // warns with B<-Wconversion>
c = c + 1; // only warns with B<-Warith-conversion>
}
-Warray-bounds-Warray-bounds=nโ Warn about out of bounds subscripts or offsets into arrays. This warning is enabled by-Wall. It is more effective when-ftree-vrpis active (the default for-O2and above) but a subset of instances are issued even without optimization. ๐-Warray-bounds=1โ This is the default warning level of-Warray-boundsand is enabled by-Wall; higher levels are not, and must be explicitly requested. (ask nicely or it's not happening ๐)-Warray-bounds=2โ This warning level also warns about out of bounds accesses to trailing struct members of one-element array types and about the intermediate results of pointer arithmetic that may yield out of bounds values. This warning level may give a larger number of false positives and is deactivated by default. ๐
-Warray-compareโ Warn about equality and relational comparisons between two operands of array type. This comparison was deprecated in C++20. For example:
int arr1[5];
int arr2[5];
bool same = arr1 == arr2;
-Warray-compare is enabled by -Wall. ๐ธ
-Warray-parameter-Warray-parameter=nโ Warn about redeclarations of functions involving arguments of array or pointer types of inconsistent kinds or forms, and enable the detection of out-of-bounds accesses to such parameters by warnings such as-Warray-bounds. ๐ต๏ธ
If the first function declaration uses the array form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size or accessing more than the maximum number of elements may be diagnosed by warnings such as -Warray-bounds. At level 1 the warning diagnoses inconsistencies involving array parameters declared using the T[static N] form.
For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f while the second one with the keyword static specifies that the array argument must have at least four elements. iconic mismatch energy:
void f (int[static 4]);
void f (int[]); // warning (inconsistent array form)
void g (void)
{
int *p = (int *)malloc (4);
f (p); // warning (array too small)
...
}
At level 2 the warning also triggers for redeclarations involving any other inconsistency in array or pointer argument forms denoting array sizes. Pointers and arrays of unspecified bound are considered equivalent and do not trigger a warning. ๐
void g (int*);
void g (int[]); // no warning
void g (int[8]); // warning (inconsistent array bound)
-Warray-parameter=2 is included in -Wall. The -Wvla-parameter option triggers warnings for similar inconsistencies involving Variable Length Array arguments. ๐ฆ
-Wattribute-alias=n-Wno-attribute-aliasโ Warn about declarations using thealiasand similar attributes whose target is incompatible with the type of the alias.-Wattribute-alias=1โ The default warning level of the-Wattribute-aliasoption diagnoses incompatibilities between the type of the alias declaration and that of its target. Such incompatibilities are typically indicative of bugs. ๐-Wattribute-alias=2โ At this level-Wattribute-aliasalso diagnoses cases where the attributes of the alias declaration are more restrictive than the attributes applied to its target. These mismatches can potentially result in incorrect code generation. In other cases they may be benign and could be resolved simply by adding the missing attribute to the target. For comparison, see the-Wmissing-attributesoption, which controls diagnostics when the alias declaration is less restrictive than the target, rather than more restrictive.
Attributes considered include alloc_align, alloc_size, cold, const, hot, leaf, malloc, nonnull, noreturn, nothrow, pure, returns_nonnull, and returns_twice. โญ
-Wattribute-alias is equivalent to -Wattribute-alias=1. This is the default. You can disable these warnings with either -Wno-attribute-alias or -Wattribute-alias=0. periodt.
-Wbidi-chars=[none|unpaired|any|ucn]โ Warn about possibly misleading UTF-8 bidirectional control characters in comments, string literals, character constants, and identifiers. Such characters can change left-to-right writing direction into right-to-left (and vice versa), which can cause confusion between the logical order and visual order. This may be dangerous; for instance, it may seem that a piece of code is not commented out, whereas it in fact is. ๐ฑ lowkey terrifying bestie.
There are three levels of warning supported by GCC. The default is -Wbidi-chars=unpaired, which warns about improperly terminated bidi contexts. -Wbidi-chars=none turns the warning off. -Wbidi-chars=any warns about any use of bidirectional control characters.
By default, this warning does not warn about UCNs. It is, however, possible to turn on such checking by using -Wbidi-chars=unpaired,ucn or -Wbidi-chars=any,ucn. Using -Wbidi-chars=ucn is valid, and is equivalent to -Wbidi-chars=unpaired,ucn, if no previous -Wbidi-chars=any was specified. ๐
-Wbool-compareโ Warn about boolean expression compared with an integer value different fromtrue/false. For instance, the following comparison is always false:
int n = 5;
...
if ((n > 1) == 2) { ... }
This warning is enabled by -Wall. ๐
-Wbool-operationโ Warn about suspicious operations on expressions of a boolean type. For instance, bitwise negation of a boolean is very likely a bug in the program. For C, this warning also warns about incrementing or decrementing a boolean, which rarely makes sense. (In C++, decrementing a boolean is always invalid. Incrementing a boolean is invalid in C++17, and deprecated otherwise.) ๐ฌ
This warning is enabled by -Wall.
-Wduplicated-branchesโ Warn when an if-else has identical branches. This warning detects cases like
if (p != NULL)
return 0;
else
return 0;
It doesn't warn when both branches contain just a null statement. This warning also warn for conditional operators:
int i = x ? *p : *p;
like bestie why are we even doing this ๐ญ
-Wduplicated-condโ Warn about duplicated conditions in an if-else-if chain. For instance, warn for the following code:
if (p->q != NULL) { ... }
else if (p->q != NULL) { ... }
the way that second one is literally the first one. ๐
-Wframe-addressโ Warn when the__builtin_frame_addressor__builtin_return_addressis called with an argument greater than0. Such calls may return indeterminate values or crash the program. The warning is included in-Wall. ๐จ-Wno-discarded-qualifiers(C and Objective-C only) โ Do not warn if type qualifiers on pointers are being discarded. Typically, the compiler warns if aconst char *variable is passed to a function that takes achar *parameter. This option can be used to suppress such a warning. ๐คซ-Wno-discarded-array-qualifiers(C and Objective-C only) โ Do not warn if type qualifiers on arrays which are pointer targets are being discarded. Typically, the compiler warns if aconst int (*)[]variable is passed to a function that takes aint (*)[]parameter. This option can be used to suppress such a warning. ๐-Wno-incompatible-pointer-types(C and Objective-C only) โ Do not warn when there is a conversion between pointers that have incompatible types. This warning is for cases not covered by-Wno-pointer-sign, which warns for pointer argument passing or assignment with different signedness. ๐ฆ-Wno-int-conversion(C and Objective-C only) โ bestie, this is the โdo not warnโ switch for incompatible integer-to-pointer and pointer-to-integer conversions. Itโs about implicit conversions, okay? For explicit conversions you can use-Wno-int-to-pointer-castand-Wno-pointer-to-int-cast. ๐-Wzero-length-boundsโ warn about accesses to elements of zero-length array members that might overlap other members of the same object. Declaring interior zero-length arrays is discouraged because accesses to them are undefined. See
struct X { int a[0]; int b, c; };
struct X x;
void bad (void)
{
x.a[0] = 0; // -Wzero-length-bounds
x.a[1] = 1; // -Wzero-length-bounds
x.a[2] = 2; // -Warray-bounds
}
For example, the first two stores in function bad are diagnosed because the array elements overlap the subsequent members b and c. The third store is diagnosed by -Warray-bounds because it is beyond the bounds of the enclosing object. Option -Wzero-length-bounds is enabled by -Warray-bounds. ๐ซถ
-Wno-div-by-zeroโ do not warn about compile-time integer division by zero. Floating-point division by zero is not warned about, because it can be a totally legit way of obtaining infinities and NaNs. โจ-Wsystem-headersโ print warning messages for constructs found in system header files. Warnings from system headers are normally suppressed, on the assumption that they usually do not indicate real problems and would only make the compiler output harder to read. Using this command-line option tells GCC to emit warnings from system headers as if they occurred in user code. However, note that using-Wallin conjunction with this option does not warn about unknown pragmas in system headersโfor that,-Wunknown-pragmasmust also be used. ๐-Wtautological-compareโ warn if a self-comparison always evaluates to true or false. This warning detects various mistakes such as:
int i = 1;
...
if (i > i) { ... }
This warning also warns about bitwise comparisons that always evaluate to true or false, for instance:
if ((a & 16) == 10) { ... }
will always be false. This warning is enabled by -Wall. ๐ฅ
-Wtrampolinesโ warn about trampolines generated for pointers to nested functions. A trampoline is a small piece of data or code that is created at run time on the stack when the address of a nested function is taken, and is used to call the nested function indirectly. For some targets, it is made up of data only and thus requires no special treatment. But, for most targets, it is made up of code and thus requires the stack to be made executable in order for the program to work properly. ๐-Wfloat-equalโ warn if floating-point values are used in equality comparisons.
The idea behind this is that sometimes it is convenient (for the programmer) to consider floating-point values as approximations to infinitely precise real numbers. If you are doing this, then you need to compute (by analyzing the code, or in some other way) the maximum or likely maximum error that the computation introduces, and allow for it when performing comparisons (and when producing output, but thatโs a different problem). In particular, instead of testing for equality, you should check to see whether the two values have ranges that overlap; and this is done with the relational operators, so equality comparisons are probably mistaken. ๐ธ
-Wtraditional(C and Objective-C only) โ warn about certain constructs that behave differently in traditional and ISO C. Also warn about ISO C constructs that have no traditional C equivalent, and/or problematic constructs that should be avoided. ๐ฆ- Macro parameters that appear within string literals in the macro body. In traditional C macro replacement takes place within string literals, but in ISO C it does not.
- In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line to be a directive if the
#appeared in column 1 on the line. Therefore-Wtraditionalwarns about directives that traditional C understands but ignores because the#does not appear as the first character on the line. It also suggests you hide directives like#pragmanot understood by traditional C by indenting them. Some traditional implementations do not recognize#elif, so this option suggests avoiding it altogether. - A function-like macro that appears without arguments.
- The unary plus operator.
- The
Uinteger constant suffix, or theForLfloating-point constant suffixes. (Traditional C does support theLsuffix on integer constants.) Note, these suffixes appear in macros defined in the system headers of most modern systems, e.g. the_MIN/_MAXmacros in<limits.h>. Use of these macros in user code might normally lead to spurious warnings, however GCCโs integrated preprocessor has enough context to avoid warning in these cases. - A function declared external in one block and then used after the end of the block.
- A
switchstatement has an operand of typelong. - A non-
staticfunction declaration follows astaticone. This construct is not accepted by some traditional C compilers. - The ISO type of an integer constant has a different width or signedness from its traditional type. This warning is only issued if the base of the constant is ten. I.e. hexadecimal or octal values, which typically represent bit patterns, are not warned about.
- Usage of ISO string concatenation is detected.
- Initialization of automatic aggregates.
- Identifier conflicts with labels. Traditional C lacks a separate namespace for labels.
- Initialization of unions. If the initializer is zero, the warning is omitted. This is done under the assumption that the zero initializer in user code appears conditioned on e.g.
__STDC__to avoid missing initializer warnings and relies on default initialization to zero in the traditional C case. - Conversions by prototypes between fixed/floating-point values and vice versa. The absence of these prototypes when compiling with traditional C causes serious problems. This is a subset of the possible conversion warnings; for the full set use
-Wtraditional-conversion. - Use of ISO C style function definitions. This warning intentionally is not issued for prototype declarations or variadic functions because these ISO C features appear in your code when using libibertyโs traditional C compatibility macros,
PARAMSandVPARAMS. This warning is also bypassed for nested functions because that feature is already a GCC extension and thus not relevant to traditional C compatibility.
-Wtraditional-conversion(C and Objective-C only) โ warn if a prototype causes a type conversion that is different from what would happen to the same argument in the absence of a prototype. This includes conversions of fixed point to floating and vice versa, and conversions changing the width or signedness of a fixed-point argument except when the same as the default promotion. ๐-Wdeclaration-after-statement(C and Objective-C only) โ warn when a declaration is found after a statement in a block. This construct, known from C++, was introduced with ISO C99 and is by default allowed in GCC. It is not supported by ISO C90. ๐ญ-Wshadowโ warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum. If this warning is enabled, it includes also all instances of local shadowing. This means that-Wno-shadow=localand-Wno-shadow=compatible-localare ignored when-Wshadowis used. Same as-Wshadow=global. ๐-Wno-shadow-ivar(Objective-C only) โ do not warn whenever a local variable shadows an instance variable in an Objective-C method. ๐-Wshadow=globalโ warn for any shadowing. Same as-Wshadow. ๐-Wshadow=localโ warn when a local variable shadows another local variable or parameter. โญ-Wshadow=compatible-localโ warn when a local variable shadows another local variable or parameter whose type is compatible with that of the shadowing variable. In C++, type compatibility here means the type of the shadowing variable can be converted to that of the shadowed variable. The creation of this flag (in addition to-Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it is most likely intentional, not a bug or typo, as shown in the following example:
for (SomeIterator i = SomeObj.begin(); i != SomeObj.end(); ++i)
{
for (int i = 0; i < N; ++i)
{
...
}
...
}
Since the two variable i in the example above have incompatible types, enabling only -Wshadow=compatible-local does not emit a warning. Because their types are incompatible, if a programmer accidentally uses one in place of the other, type checking is expected to catch that and emit an error or warning. Use of this flag instead of -Wshadow=local can possibly reduce the number of warnings triggered by intentional shadowing. Note that this also means that shadowing const char *i by char *i does not emit a warning. This warning is also enabled by -Wshadow=local. ๐
-Wlarger-than=byte-size โ warn whenever an object is defined whose size exceeds byte-size.-Wlarger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by the option can be disabled either by specifying byte-size ofSIZE_MAXor more or by-Wno-larger-than. ๐-Wlarger-than=byte-size(cont.) โ also yell at you when you call bounded functions likememchrorstrnlenand hand them a bound that's bigger than the biggest object that could ever exist, which isPTRDIFF_MAXbytes by default. bestie these warnings have exactly one off-switch and it's-Wno-larger-than, no cap ๐-Wno-larger-thanโ turns off the-Wlarger-than=warnings. it's literally the same thing as saying-Wlarger-than=SIZE_MAXor bigger.-Wframe-larger-than=byte-sizeโ warns you if a function's frame gets bigger than byte-size. ok so heads up: the math it does to figure out the stack frame size is approximate and NOT conservative ๐ so your actual stack needs might be a little bigger than byte-size even when you get zero warnings. also, anything you allocate withalloca, variable-length arrays, or related constructs is not counted by the compiler when it decides whether to warn or not.-Wframe-larger-than=PTRDIFF_MAXis on by default. you can silence these by passing a byte-size ofSIZE_MAXor more, or just by using-Wno-frame-larger-than.-Wno-frame-larger-thanโ kills the-Wframe-larger-than=warnings. same energy as-Wframe-larger-than=SIZE_MAXor larger. โจ-Wfree-nonheap-objectโ warns when you try to deallocate something that was never allocated on the heap, or that you're freeing through a pointer that didn't come back from the matching allocation function. example:stpcpyreturns a pointer to the terminating nul character, not the start of the object, so thefreecall below gets diagnosed. iconic behavior honestly:
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is part of -Wall.
-Wstack-usage=byte-sizeโ warns if a function's stack usage might exceed byte-size. unlike the frame one, this computation is conservative, and any space fromalloca, variable-length arrays, or related constructs is included when the compiler decides whether to warn. the message matches the output of-fstack-usage. so:- if the stack usage is fully static but goes over the amount, you get:
warning: stack usage is 1120 bytes
- if it's (partly) dynamic but bounded, you get:
warning: stack usage might be 1648 bytes
- if it's (partly) dynamic and not bounded, you get:
warning: stack usage might be unbounded
-Wstack-usage=PTRDIFF_MAX is enabled by default. you can turn the warnings off by specifying a byte-size of SIZE_MAX or more, or with -Wno-stack-usage. ๐ซถ
-Wno-stack-usageโ disables the-Wstack-usage=warnings. equivalent to-Wstack-usage=SIZE_MAXor larger.-Wunsafe-loop-optimizationsโ warns if a loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. and with-funsafe-loop-optimizationsit warns if the compiler does go ahead and make those assumptions ๐-Wno-pedantic-ms-format(MinGW targets only) โ when you pair it with-Wformatand-pedanticbut without GNU extensions, this one shuts off the warnings about non-ISOprintf/scanfformat width specifiersI32,I64, andI, which get used on Windows targets and depend on the MS runtime.-Wpointer-arithโ warns about anything that leans on the "size of" a function type or ofvoid. GNU C gives those types a size of 1, purely for convenience when doing math withvoid *pointers and function pointers. in C++ it also warns when an arithmetic operation involvesNULL. this one's also enabled by-Wpedantic.-Wno-pointer-compareโ don't warn if a pointer is compared with a zero character constant. ngl when that happens it usually means the pointer was supposed to be dereferenced. like:
const char *p = foo ();
if (p == '\0')
return 42;
quick note: the code above is invalid in C++11 ๐
this warning is enabled by default.
-Wtsanโ warns about unsupported features in ThreadSanitizer. ThreadSanitizer does not supportstd::atomic_thread_fenceand can report false positives. this warning is enabled by default.-Wtype-limitsโ warns if a comparison is always true or always false because the data type's range is too small, but it does not warn for constant expressions. so like, it'll warn if you compare an unsigned variable against zero with<or>=. this one's also enabled by-Wextra. ๐ฆ-Wabsolute-value(C and Objective-C only) โ warns when you call a standard function that computes the absolute value of an argument but a better-suited standard function exists. for example,abs(3.14)triggers the warning because the right function for a double argument isfabs. it also fires when the argument in such a call has an unsigned type. you can suppress it with an explicit type cast, and it's also enabled by-Wextra.-Wcomment-Wcommentsโ warns whenever a comment-start sequence/*shows up inside a/*comment, or whenever a backslash-newline shows up inside a//comment. enabled by-Wall.-Wtrigraphsโ warns if any trigraphs pop up that might change the meaning of the program. trigraphs inside comments don't get warned about, except the ones that would form escaped newlines. this option is implied by-Wall. if-Wallisn't given, it's still on unless trigraphs are enabled. so if you want trigraph conversion with no warnings but still want the other-Wallwarnings, use-trigraphs -Wall -Wno-trigraphs.-Wundefโ warns if an undefined identifier gets evaluated in an#ifdirective. those identifiers get replaced with zero, fyi.-Wexpansion-to-definedโ warns wheneverdefinedshows up in the expansion of a macro (including when the macro is expanded by an#ifdirective). that usage isn't portable, bestie. this one's also enabled by-Wpedanticand-Wextra.-Wunused-macrosโ warns about macros defined in the main file that never get used. a macro counts as used if it's expanded or tested for existence at least once. the preprocessor will also warn if the macro hasn't been used by the time it gets redefined or undefined. built-in macros, macros defined on the command line, and macros defined in include files are not warned about. โจ note: if a macro is actually used but only inside skipped conditional blocks, the preprocessor still reports it as unused ๐ญ to dodge the warning in that case you could tighten the macro's scope by, say, moving it into the first skipped block. or you could give it a dummy use like:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsโ don't warn whenever an#elseor an#endifis followed by text. this happens in older programs with code shaped like:
#if FOO
...
#else FOO
...
#endif FOO
the second and third FOO should be inside comments. this warning is on by default.
-Wbad-function-cast(C and Objective-C only) โ warns when a function call is cast to a type that doesn't match. like, warns if you cast a call to a function returning an integer type into a pointer type. ๐-Wc90-c99-compat(C and Objective-C only) โ warns about features that aren't in ISO C90 but are in ISO C99. so like, variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, all that. this option is independent of the standards mode. warnings are disabled in the expression that follows__extension__.-Wc99-c11-compat(C and Objective-C only) โ warns about features that aren't in ISO C99 but are in ISO C11. for instance anonymous structures and unions, the_Atomictype qualifier, the_Thread_localstorage-class specifier, the_Alignasspecifier, theAlignofoperator, the_Generickeyword, and so on. independent of the standards mode. warnings are disabled in the expression that follows__extension__.-Wc11-c2x-compat(C and Objective-C only) โ warns about features not in ISO C11 but present in ISO C2X. like omitting the string in_Static_assert, using the[[]]syntax for attributes, using decimal floating-point types, etc. independent of the standards mode, and warnings are disabled in the expression that follows__extension__. ๐-Wc++-compat(C and Objective-C only) โ warns about ISO C constructs that live outside the common subset of ISO C and ISO C++, e.g. asking for an implicit conversion fromvoid *to a pointer to a non-voidtype.-Wc++11-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 1998 and ISO C++ 2011, e.g. identifiers that were fine in ISO C++ 1998 but became keywords in ISO C++ 2011. this warning turns on-Wnarrowingand is enabled by-Wall.-Wc++14-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2011 and ISO C++ 2014. enabled by-Wall.-Wc++17-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2014 and ISO C++ 2017. enabled by-Wall.-Wc++20-compat(C++ and Objective-C++ only) โ warns about C++ constructs whose meaning differs between ISO C++ 2017 and ISO C++ 2020. enabled by-Wall. ๐-Wno-c++11-extensions(C++ and Objective-C++ only) โ don't warn about C++11 constructs in code you're compiling with an older C++ standard. even without this option, some C++11 constructs will only get diagnosed if-Wpedanticis used.-Wno-c++14-extensions(C++ and Objective-C++ only) โ don't warn about C++14 constructs in code you're compiling with an older C++ standard. and yeah, even without this option, some C++14 constructs only get diagnosed when-Wpedanticis used. ๐ธ-Wno-c++17-extensions(C++ and Objective-C++ only) โ bestie, this one shuts OFF the warning about C++17 constructs showing up in code you're compiling with an older C++ standard. And heads up: even without this flag, some C++17 constructs only get diagnosed if you're using-Wpedantic. iykyk โจ-Wno-c++20-extensions(C++ and Objective-C++ only) โ same vibe, different year: no warning about C++20 constructs in code being compiled with an older C++ standard. And same caveat, some C++20 constructs are only diagnosed with-Wpedantic. ๐ฆ-Wno-c++23-extensions(C++ and Objective-C++ only) โ you guessed it, the C++23 version. No warning about C++23 constructs in code compiled with an older C++ standard. And again: some C++23 constructs only get diagnosed if-Wpedanticis in the mix. ๐-Wcast-qualโ warns whenever you cast a pointer in a way that removes a type qualifier from the target type. Like, if aconst char *gets cast to a plain oldchar *? Yeah, it's giving red flag ๐ฉ
It ALSO warns when you make a cast that introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe, and here's the receipts:
/* p is char ** value. */
const char **q = (const char **) p;
/* Assignment of readonly string to const char * is OK. */
*q = "string";
/* Now char** pointer points to read-only memory. */
**p = 'b';
-Wcast-alignโ warns whenever a pointer cast bumps up the required alignment of the target. Example: casting achar *to anint *on machines where integers can only be accessed at two- or four-byte boundaries. the way that machine will simply Not Have It ๐ญ-Wcast-align=strictโ same energy as above, but with zero chill about the target machine. Warns whenever a pointer is cast such that the required alignment of the target is increased โ for example, achar *cast to anint *โ regardless of what machine you're targeting. โจ-Wcast-function-typeโ warns when a function pointer gets cast to an incompatible function pointer. The deets:- In a cast involving function types with a variable argument list, only the types of the initial arguments that are provided are considered.
- Any parameter of pointer-type matches any other pointer-type.
- Any benign differences in integral types are ignored โ like
intvs.longon ILP32 targets. - Type qualifiers are also ignored.
- The function type
void (*) (void)is special and matches everything, which you can use to suppress this warning. ๐ - In a cast involving pointer to member types, this warning fires whenever the type cast is changing the pointer to member type.
This warning is enabled by -Wextra.
-Wwrite-stringsโ when compiling C, this gives string constants the typeconst char[length], so copying the address of one into a non-constchar *pointer produces a warning. These warnings help you catch, at compile time, code that might try to write into a string constant โ but ONLY if you've been very careful about usingconstin declarations and prototypes. Otherwise it's just a nuisance. Which is literally why-Walldoesn't request these warnings. ๐
When compiling C++, it warns about the deprecated conversion from string literals to char *. This warning is enabled by default for C++ programs.
-Wclobberedโ warns for variables that might get changed bylongjmporvfork. Also enabled by-Wextra. ๐-Wconversionโ warns for implicit conversions that may alter a value. The whole roster:- conversions between real and integer, like
abs (x)whenxisdouble; - conversions between signed and unsigned, like
unsigned ui = -1; - conversions to smaller types, like
sqrtf (M_PI).
- conversions between real and integer, like
It does not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value isn't changed by the conversion, like in abs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion.
For C++, it also warns for confusing overload resolution for user-defined conversions, and conversions that never use a type conversion operator: conversions to void, the same type, a base class or a reference to them. Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.
Oh and p.s. โ warnings about conversion from arithmetic on a small type back to that type are only given with -Warith-conversion. ๐ซถ
-Wdangling-elseโ warns about constructions where there might be confusion over whichifstatement anelsebranch belongs to. Exhibit A:
{
if (a)
if (b)
foo ();
else
bar ();
}
In C/C++, every else branch belongs to the innermost possible if statement, which in this example is if (b). That is often NOT what the programmer expected โ as the indentation in the example above snitches on. ๐ญ When there's potential for this confusion, GCC issues a warning when this flag is specified. To make the warning go away, add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. The glow-up:
{
if (a)
{
if (b)
foo ();
else
bar ();
}
}
This warning is enabled by -Wparentheses.
-Wdangling-pointer-Wdangling-pointer=nโ warns about uses of pointers (or C++ references) to objects with automatic storage duration after their lifetime has ended. That includes local variables declared in nested blocks, compound literals and other unnamed temporary objects. On top of that, it warns about storing the address of such objects in escaped pointers. The warning is enabled at all optimization levels, but may yield different results with optimization than without. โจ
-Wdangling-pointer=1
At level 1, the warning diagnoses only unconditional uses of dangling pointers. For example:
int f (int c1, int c2, x)
{
char *p = strchr ((char[]){ c1, c2 }, c3);
return p ? *p : 'x'; // warning: dangling pointer to a compound literal
}
In the following function, the store of the address of the local variable x in the escaped pointer *p also triggers the warning.
void g (int **p)
{
int x = 7;
*p = &x; // warning: storing the address of a local variable in *p
}
-Wdangling-pointer=2
At level 2, in addition to unconditional uses, the warning also diagnoses conditional uses of dangling pointers.
For example, because the array a in the following function is out of scope when the pointer s that was set to point is used, the warning triggers at this level.
void f (char *s)
{
if (!s)
{
char a[12] = "tmpname";
s = a;
}
strcat (s, ".tmp"); // warning: dangling pointer to a may be used
...
}
-Wdangling-pointer=2 is included in -Wall. ๐
-Wdate-timeโ warns when the macros__TIME__,__DATE__or__TIMESTAMP__show up, because they might prevent bit-wise-identical reproducible compilations. no cap, reproducibility girlies stay winning ๐-Wempty-bodyโ warns if an empty body occurs in anif,elseordo whilestatement. Also enabled by-Wextra. ๐-Wno-endif-labelsโ do NOT warn about stray tokens after#elseand#endif.-Wenum-compareโ warns about a comparison between values of different enumerated types. In C++, enumerated type mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C, this warning is enabled by-Wall.-Wenum-conversionโ warns when a value of enumerated type is implicitly converted to a different enumerated type. In C, this warning is enabled by-Wextra.-Wjump-misses-init(C, Objective-C only) โ warns if agotostatement or aswitchstatement jumps forward across the initialization of a variable, or jumps backward to a label after the variable has been initialized. It only warns about variables that are initialized when they're declared. And it's only supported for C and Objective-C โ in C++, this sort of branch is an error in any case. ๐ณ
-Wjump-misses-init is included in -Wc++-compat. It can be disabled with the -Wno-jump-misses-init option.
-Wsign-compareโ warns when a comparison between signed and unsigned values could produce an incorrect result when the signed value gets converted to unsigned. In C++, this warning is also enabled by-Wall. In C, it's also enabled by-Wextra. ๐ฆ-Wsign-conversionโ warns for implicit conversions that may change the sign of an integer value, like assigning a signed integer expression to an unsigned integer variable. An explicit cast silences the warning. In C, this option is also enabled by-Wconversion.-Wfloat-conversionโ warns for implicit conversions that reduce the precision of a real value. That includes conversions from real to integer, and from higher precision real to lower precision real values. Also enabled by-Wconversion. โจ-Wno-scalar-storage-orderโ do not warn on suspicious constructs involving reverse scalar storage order. ๐-Wsizeof-array-divโ warns about divisions of twosizeofoperators when the first one is applied to an array and the divisor does not equal the size of the array element. In that case, the computation will not yield the number of elements in the array โ which is, like, almost certainly what the user intended. This warning warns about e.g.:
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall. ๐
-Wsizeof-pointer-divโ bestie, this one's for the iconic classic: dividing twosizeofexpressions where you're dividing the pointer size by the element size. That's the standard way to compute an array's length, and it works *great*โฆ unlessptrisn't an array at all but a pointer, in which case it does not work out correctly at all. ๐ So it flags stuff likesizeof (ptr) / sizeof (ptr[0])whenptris a pointer, not an array. Enabled by-Wall.-Wsizeof-pointer-memaccessโ this cutie sniffs out suspicious length parameters passed to certain string and memory built-in functions when the argument usessizeof. Like, it triggers onmemset (ptr, 0, sizeof (ptr));ifptris a pointer instead of an array โ and it even suggests a possible fix ๐ซถ โ and also onmemcpy (&foo, ptr, sizeof (&foo));.
It also side-eyes calls to bounded string copy functions like strncat or strncpy that use a sizeof expression of the source array as the bound. Example: in this function the strncat call passes the size of the source string as the bound. That is almost certainly a mistake, so the call gets diagnosed. ๐
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
-Wsizeof-pointer-memaccess is enabled by -Wall. โจ
-Wno-sizeof-array-argumentโ okay so do not warn when thesizeofoperator gets applied to a parameter that's declared as an array in a function definition. This warning is enabled by default for C and C++ programs. ๐-Wmemset-elt-sizeโ warns about suspicious calls to thememsetbuilt-in when the first argument references an array and the third argument is a number equal to the number of elements but not equal to the size of the array in memory. That's a big ol' tell that the user forgot to multiply by the element size. ๐ Enabled by-Wall.-Wmemset-transposed-argsโ the "you flipped your args, babe" detector. ๐ Warns about suspiciousmemsetcalls where the second argument is not zero and the third argument is zero. Somemset (buf, sizeof buf, 0)gets diagnosed, becausememset (buf, 0, sizeof buf)was clearly what you meant.
Important nuance, no cap: the diagnostic is only emitted if the third argument is a literal zero. If it's an expression that gets folded to zero, or a cast of zero to some type, then it's far less likely the arguments were mistakenly transposed, so no warning is emitted. Enabled by -Wall.
-Waddressโ warns about suspicious uses of address expressions, and there are three flavours here:- Comparing the address of a function or a declared object to the null pointer constant, like:
void f (void);
void g (void)
{
if (!func) // warning: expression evaluates to false
abort ();
}
- Comparing a pointer to a string literal, like:
void f (const char *x)
{
if (x == "abc") // warning: expression evaluates to false
puts ("equal");
}
- Testing the results of pointer addition or subtraction for equality to null, like:
void f (const int *p, int i)
{
return p + i == NULL;
}
These uses typically mean a programmer error, fr: the address of most functions and objects necessarily evaluates to true (the exceptions are weak symbols), so using one in a conditional might mean you're missing parentheses in a function call, or missing a dereference in an array expression. The subset of the warning for object pointers can be suppressed by casting the pointer operand to an integer type such as inptr_t or uinptr_t. Comparisons against string literals give unspecified behavior and aren't portable, and they suggest the intent was to call strcmp. The warning is suppressed if the suspicious expression is the result of macro expansion. -Waddress is enabled by -Wall.
-Wno-address-of-packed-memberโ do not warn when the address of a packed member of a struct or union gets taken, which usually results in an unaligned pointer value. Enabled by default. ๐-Wlogical-opโ warns about suspicious uses of logical operators in expressions. This includes using logical operators in contexts where a bit-wise operator is probably what you wanted. It also warns when the operands of a logical operator are literally the same thing:
extern int a;
if (a < 0 && a < 0) { ... }
-Wlogical-not-parenthesesโ warns about a logical not used on the left hand side operand of a comparison. It does not warn if the right operand is considered to be a boolean expression. Its whole purpose is catching suspicious code like this:
int a;
...
if (!a > 1) { ... }
And you can suppress the warning by wrapping the LHS in parentheses:
if ((!a) > 1) { ... }
Enabled by -Wall. โจ
-Waggregate-returnโ warns if any functions that return structures or unions are defined or called. And in languages where you can return an array, that also elicits a warning. ๐ซ-Wno-aggressive-loop-optimizationsโ warns if, in a loop with a constant number of iterations, the compiler detects undefined behavior in some statement during one or more of the iterations.-Wno-attributesโ do not warn if an unexpected__attribute__is used, like unrecognized attributes, function attributes applied to variables, etc. This does not stop errors for incorrect use of supported attributes.
Also, using -Wno-attributes=, it's possible to suppress warnings about unknown scoped attributes (in C++11 and C2X). For example, -Wno-attributes=vendor::attr disables the warning about this declaration:
[[vendor::attr]] void f();
And you can disable the warning about all attributes in a namespace using -Wno-attributes=vendor::, which prevents warnings about both of these declarations:
[[vendor::safe]] void f();
[[vendor::unsafe]] void f2();
Note that -Wno-attributes= does not imply -Wno-attributes. โ ๏ธ
-Wno-builtin-declaration-mismatchโ warns if a built-in function is declared with an incompatible signature or as a non-function, or when a built-in function declared with a type that doesn't include a prototype gets called with arguments whose promoted types don't match what the function expects. When-Wextrais specified, it also warns when a built-in function that takes arguments is declared without a prototype.-Wbuiltin-declaration-mismatchis enabled by default. To dodge the warning, include the appropriate header to bring the prototypes of built-in functions into scope. ๐
For example, the memset call below gets diagnosed because the function expects a value of type size_t as its argument, but the type of 32 is int. With -Wextra, the declaration of the function gets diagnosed as well.
extern void* memset ();
void f (void *d)
{
memset (d, '\0', 32);
}
-Wno-builtin-macro-redefinedโ do not warn if certain built-in macros are redefined. This suppresses warnings for redefinition of__TIMESTAMP__,__TIME__,__DATE__,__FILE__, and__BASE_FILE__.-Wstrict-prototypes(C and Objective-C only) โ warns if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if it's preceded by a declaration that specifies the argument types.)-Wold-style-declaration(C and Objective-C only) โ warns for obsolescent usages in a declaration, according to the C Standard. For example, it warns if storage-class specifiers likestaticaren't the first things in a declaration. This warning is also enabled by-Wextra.-Wold-style-definition(C and Objective-C only) โ warns if an old-style function definition is used. A warning is given even if there's a previous prototype. A definition using()is not considered an old-style definition in C2X mode, because it's equivalent to(void)in that case, but it is considered an old-style definition for older standards. ๐-Wmissing-parameter-type(C and Objective-C only) โ for when a function parameter is declared without a type specifier in K&R-style functions:
void foo(bar) { }
This warning is also enabled by -Wextra.
-Wmissing-prototypes(C and Objective-C only) โ warns if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. Use this option to detect global functions that don't have a matching prototype declaration in a header file. This option is not valid for C++, because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflicting with an earlier declaration. Use-Wmissing-declarationsto detect missing declarations in C++.-Wmissing-declarationsโ warns if a global function is defined without a previous declaration, and does so even if the definition itself provides a prototype. Use this option to detect global functions that aren't declared in header files. In C, no warnings are issued for functions with previous non-prototype declarations โ use-Wmissing-prototypesto detect missing prototypes. In C++, no warnings are issued for function templates, or for inline functions, or for functions in anonymous namespaces. ๐ง-Wmissing-field-initializersโ warns if a structure's initializer has some fields missing. For example, this code causes such a warning, becausex.his implicitly zero:
struct s { int f, g, h; };
struct s x = { 3, 4 };
This option does not warn about designated initializers, so this modification does not trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
And in C, this option does not warn about the universal zero initializer { 0 }:
struct s { int f, g, h; };
struct s x = { 0 };
Likewise, in C++ this option doesn't even yell about the empty { } initializer, bestie, like:
struct s { int f, g, h; };
s x = { };
This warning is lowkey part of -Wextra. Want the other -Wextra warnings but not this one? Just do -Wextra -Wno-missing-field-initializers. โจ
-Wno-missing-requiresโ so by default the compiler clocks a concept-id showing up as a C++20 simple-requirement:
bool satisfied = requires { C<T> };
Here satisfied is gonna be true if C<T> is a valid expression, which it literally is for all T. So presumably the user meant to write
bool satisfied = requires { requires C<T> };
so that satisfied is only true if concept C is actually satisfied for type T.
This warning can be switched off with -Wno-missing-requires.
-Wno-missing-template-keywordโ the member access tokens.,->and::have to be followed by the"template"keyword if the parent object is dependent and the member being named is a template.
template <class X>
void DoStuff (X x)
{
x.template DoSomeOtherStuff<X>(); // Good.
x.DoMoreStuff<X>(); // Warning, x is dependent.
}
In rare cases you can get false positives. To silence those, wrap the expression in parentheses. Like, the following is treated as a template, even where m and N are integers:
void NotATemplate (my_class t)
{
int N = 5;
bool test = t.m < N > (0); // Treated as a template.
test = (t.m < N) > (0); // Same meaning, but not treated as a template.
}
This warning can be disabled with -Wno-missing-template-keyword.
-Wno-multicharโ don't warn if a multicharacter constant ('FOOF') gets used. Usually they're giving "oops, typo" energy in the user's code, because they have implementation-defined values, and honestly they should not be used in portable code, periodt.-Wnormalized=[none|id|nfc|nfkc]โ okay so in ISO C and ISO C++, two identifiers are different if they're different sequences of characters. But sometimes, when characters outside the basic ASCII character set show up, you can have two different character sequences that look the same. ๐ To avoid the confusion, the ISO 10646 standard sets out some normalization rules which, when applied, make sure two sequences that look the same get turned into the same sequence. GCC can warn you if you're using identifiers that haven't been normalized, and this option controls that warning.
There are four levels of warning GCC supports. The default is -Wnormalized=nfc, which warns about any identifier that isn't in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It's equivalent to -Wnormalized.
Unfortunately, there are some characters allowed in identifiers by ISO C and ISO C++ that, when turned into NFC, are not allowed in identifiers. Which is to say, there's no way to use these symbols in portable ISO C or C++ and have all your identifiers in NFC. -Wnormalized=id suppresses the warning for these characters. The hope is that future versions of the standards involved will fix this, which is exactly why this option isn't the default.
You can switch the warning off for all characters by writing -Wnormalized=none or -Wno-normalized. You should only do this if you're using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. ๐
Some characters in ISO 10646 have distinct meanings but look identical in some fonts or display methodologies, especially once formatting has been applied. For instance "\u207F", "SUPERSCRIPT LATIN SMALL LETTER N", displays just like a regular "n" that's been placed in a superscript. ISO 10646 defines the NFKC normalization scheme to convert all these into a standard form as well, and GCC warns if your code isn't in NFKC when you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might get confused with the digit 0, so it's not the default โ but it may be useful as a local coding convention if the programming environment can't be fixed to display these characters distinctly.
-Wno-attribute-warningโ don't warn about usage of functions declared with the"warning"attribute. By default, this warning is enabled.-Wno-attribute-warningcan be used to disable the warning, or-Wno-error=attribute-warningcan be used to disable the error when compiled with the-Werrorflag.-Wno-deprecatedโ don't warn about usage of deprecated features.-Wno-deprecated-declarationsโ don't warn about uses of functions, variables, and types marked as deprecated by using the"deprecated"attribute.-Wno-overflowโ don't warn about compile-time overflow in constant expressions.-Wno-odrโ warn about One Definition Rule violations during link-time optimization. Enabled by default. ๐-Wopenacc-parallelismโ warn about potentially suboptimal choices related to OpenACC parallelism.-Wopenmp-simdโ warn if the vectorizer cost model overrides the OpenMP simd directive set by user. The-fsimd-cost-model=unlimitedoption can be used to relax the cost model.-Woverride-init(C and Objective-C only) โ warn if an initialized field without side effects is overridden when using designated initializers.
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-override-init.
-Wno-override-init-side-effects(C and Objective-C only) โ do not warn if an initialized field with side effects is overridden when using designated initializers. This warning is enabled by default.-Wpackedโ warn if a structure is given the packed attribute, but the packed attribute has no effect on the layout or size of the structure. Such structures may be mis-aligned for little benefit. For instance, in this code, the variablef.xinstruct baris misaligned even thoughstruct bardoes not itself have the packed attribute:
struct foo {
int x;
char a, b, c, d;
} __attribute__((packed));
struct bar {
char z;
struct foo f;
};
-Wnopacked-bitfield-compatโ the 4.1, 4.2 and 4.3 series of GCC ignore the"packed"attribute on bit-fields of type"char". This was fixed in GCC 4.4, but the change can lead to differences in the structure layout. GCC informs you when the offset of such a field has changed in GCC 4.4. For example there's no longer a 4-bit padding between fieldaandbin this structure:
struct foo
{
char a:4;
char b:8;
} __attribute__ ((packed));
This warning is enabled by default. Use -Wno-packed-bitfield-compat to disable this warning.
-Wpacked-not-aligned(C, C++, Objective-C and Objective-C++ only) โ warn if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning will be issued onstruct S, like,warning: alignment 1 of 'struct S' is less than 8, in this code:
struct __attribute__ ((aligned (8))) S8 { char a[8]; };
struct __attribute__ ((packed)) S {
struct S8 s8;
};
This warning is enabled by -Wall.
-Wpaddedโ warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Sometimes when this happens it's possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller.-Wredundant-declsโ warn if anything is declared more than once in the same scope, even in cases where the multiple declaration is valid and changes literally nothing.-Wrestrictโ warn when an object referenced by a"restrict"-qualified parameter (or, in C++, a"__restrict"-qualified parameter) is aliased by another argument, or when copies between such objects overlap. For example, the call to the"strcpy"function below attempts to truncate the string by replacing its initial characters with the last four. But because the call writes the terminating NUL intoa[4], the copies overlap and the call gets diagnosed. ๐ซถ
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
The -Wrestrict option detects some instances of simple overlap even without optimization, but it works best at -O2 and above. It's included in -Wall.
-Wnested-externs(C and Objective-C only) โ warn if an"extern"declaration is encountered within a function.-Winlineโ warn if a function that's declared as inline cannot be inlined. Even with this option, the compiler doesn't warn about failures to inline functions declared in system headers.
The compiler uses a whole variety of heuristics to determine whether or not to inline a function. For example, the compiler takes into account the size of the function being inlined and the amount of inlining that's already been done in the current function. So, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear. ๐ญ
-Winterference-sizeโ warn about use of C++17std::hardware_destructive_interference_sizewithout specifying its value with--param destructive-interference-size. Also warn about questionable values for that option.
This variable is intended to be used for controlling class layout, to avoid false sharing in concurrent code:
struct independent_fields {
alignas(std::hardware_destructive_interference_size) std::atomic<int> one;
alignas(std::hardware_destructive_interference_size) std::atomic<int> two;
};
Here one and two are intended to be far enough apart that stores to one won't require accesses to the other to reload the cache line. ๐
okay so quick recap bestie: these two knobs, --param destructive-interference-size and --param constructive-interference-size, get their default values from whatever -mtune you're currently using โ usually it's the L1 cache line size for your specific target CPU, and sometimes it's a whole range if you're tuning for something generic. โจ
Which means: every single translation unit that cares about ABI compatibility for these variables must be compiled with the same -mtune (or -mcpu). No mixing. That's the whole vibe. ๐ซถ
If ABI stability actually matters to you โ like, say, this thing lives in a header for a library โ you should probably just not use the hardware interference size variables at all. fr fr. Or, alternatively, you can force a specific value with --param.
And if you're fully confident that your use of the variable doesn't touch ABI outside a single build of your project? You can just turn the warning off with -Wno-interference-size. slay, problem solved.
-Wint-in-bool-contextโ Warns you about suspicious use of integer values in places where booleans are expected ๐ โ like conditional expressions (?:) using non-boolean integer constants in a boolean context, e.g.if (a <= b ? 2 : 3). Also left shifting signed integers in a boolean context, likefor (a = 0; 1 << a; a++);. Same deal for every kind of multiplication, no matter the data type. This one is enabled by-Wall. โญ-Wno-int-to-pointer-castโ Suppresses warnings from casting an integer of a different size to a pointer type. In C++, casting to a pointer type of smaller size is an error.Wint-to-pointer-castis enabled by default. ๐-Wno-pointer-to-int-cast(C and Objective-C only) โ Suppresses warnings from casting from a pointer to an integer type of a different size. ๐-Winvalid-pchโ Warns if a precompiled header is found in the search path but it can't be used. ๐ญ-Wlong-longโ Warns if thelong longtype is used. Enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. To shut the warning messages up, use-Wno-long-long. ๐-Wvariadic-macrosโ Warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. Enabled by either-Wpedanticor-Wtraditional. To inhibit the warning messages, use-Wno-variadic-macros. ๐ธ-Wno-varargsโ Don't warn on questionable usage of the macros used to handle variable arguments, likeva_start. These warnings are enabled by default. ๐ฆ-Wvector-operation-performanceโ Warns if a vector operation isn't implemented via the SIMD capabilities of the architecture. Mainly useful for performance tuning. Vector operations can be implemented:- "piecewise" โ the scalar operation is performed on every vector element
- "in parallel" โ the vector operation uses scalars of a wider type, which normally is more performance efficient
- "as a single scalar" โ the vector fits into a scalar type
iykyk. ๐ฅ
-Wvlaโ Warns if a variable-length array is used in the code.-Wno-vlaprevents the-Wpedanticwarning about the variable-length array. ๐-Wvla-larger-than=byte-sizeโ If you use this, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that lets the array size exceed byte-size bytes. Works kind of like-Walloca-larger-than=byte-size, but for variable-length arrays. ๐
Heads up: GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not even trigger for those. not me being sneaky.
-Wvla-larger-than=PTRDIFF_MAX is enabled by default, but it's typically only effective when -ftree-vrp is active (which is the default for -O2 and above).
See also -Walloca-larger-than=byte-size.
-Wno-vla-larger-thanโ Disables-Wvla-larger-than=warnings. It's equivalent to-Wvla-larger-than=SIZE_MAXor larger. ๐-Wvla-parameterโ Warns about redeclarations of functions involving arguments of Variable Length Array types of inconsistent kinds or forms, and enables the detection of out-of-bounds accesses to such parameters via warnings like-Warray-bounds. ๐
If the first function declaration uses the VLA form, the bound specified in the array is assumed to be the minimum number of elements expected to be provided in calls to the function, and the maximum number of elements accessed by it. Failing to provide arguments of sufficient size, or accessing more than the maximum number of elements, may be diagnosed.
For example, the warning triggers for the following redeclarations because the first one allows an array of any size to be passed to f, while the second one specifies that the array argument must have at least n elements. In addition, calling f with the associated VLA bound parameter in excess of the actual VLA bound triggers a warning as well.
void f (int n, int[n]);
void f (int, int[]); // warning: argument 2 previously declared as a VLA
void g (int n)
{
if (n > 4)
return;
int a[n];
f (sizeof a, a); // warning: access to a by f may be out of bounds
...
}
-Wvla-parameter is included in -Wall. The -Warray-parameter option triggers warnings for similar problems involving ordinary array arguments. ๐ซถ
-Wvolatile-register-varโ Warns if a register variable is declaredvolatile. Thevolatilemodifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. Enabled by-Wall. โ ๏ธ-Wdisabled-optimizationโ Warns if a requested optimization pass is disabled. This warning generally does not mean something is wrong with your code โ it just means GCC's optimizers can't handle the code effectively. Often the issue is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take an inordinate amount of time. ๐ฎโ๐จ-Wpointer-sign(C and Objective-C only) โ Warns for pointer argument passing or assignment with different signedness. Only supported for C and Objective-C. It's implied by-Walland by-Wpedantic, which can be disabled with-Wno-pointer-sign. ๐-Wstack-protectorโ This option is only active when-fstack-protectoris active. It warns about functions that aren't protected against stack smashing. ๐ก๏ธ-Woverlength-stringsโ Warns about string constants longer than the "minimum maximum" length specified in the C standard. Modern compilers generally allow string constants much longer than the standard's minimum limit, but very portable programs should avoid using longer strings. ๐
The limit applies after string constant concatenation, and doesn't count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 doesn't specify a normative minimum maximum, so we don't diagnose overlength strings in C++.
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings.
-Wunsuffixed-float-constants(C and Objective-C only) โ Issues a warning for any floating constant that doesn't have a suffix. When used together with-Wsystem-headers, it warns about such constants in system header files too. Handy when preparing code to use with theFLOAT_CONST_DECIMAL64pragma from the decimal floating-point extension to C99. ๐-Wno-lto-type-mismatchโ During link-time optimization, don't warn about type mismatches in global declarations from different compilation units. Requires-fltoto be enabled. Enabled by default. โจ-Wno-designated-init(C and Objective-C only) โ Suppresses warnings when a positional initializer is used to initialize a structure that's been marked with thedesignated_initattribute. ๐ง
๐ Options That Control Static Analysis ๐
-fanalyzerโ This enables a static analysis of program flow that looks for "interesting" interprocedural paths through the code and issues warnings for problems found on them. ๐ต๏ธโโ๏ธ
This analysis is much more expensive than other GCC warnings. like, brace yourself.
In technical terms, it performs coverage-guided symbolic execution of the code being compiled. It is neither sound nor complete: it can have false positives and false negatives. It is a bug-finding tool, rather than a tool for proving program correctness. ๐
The analyzer is only suitable for use on C code in this release.
Enabling this option effectively enables the following warnings:
-Wanalyzer-double-fclose -Wanalyzer-double-free
-Wanalyzer-exposure-through-output-file -Wanalyzer-file-leak
-Wanalyzer-free-of-non-heap -Wanalyzer-malloc-leak
-Wanalyzer-mismatching-deallocation -Wanalyzer-null-argument
-Wanalyzer-null-dereference -Wanalyzer-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-shift-count-negative
-Wanalyzer-shift-count-overflow -Wanalyzer-stale-setjmp-buffer
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-use-of-uninitialized-value -Wanalyzer-write-to-const
-Wanalyzer-write-to-string-literal
This option is only available if GCC was configured with analyzer support enabled. ๐
-Wanalyzer-too-complexโ If-fanalyzeris enabled, the analyzer uses various heuristics to try to explore the control flow and data flow in the program, but these can be defeated by sufficiently complicated code. ๐ตโ๐ซ
By default, the analysis silently stops if the code is too complicated for the analyzer to fully explore and it reaches an internal limit. The -Wanalyzer-too-complex option warns if this occurs.
-Wno-analyzer-double-fcloseโ This warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-fcloseto disable it. ๐
This diagnostic warns for paths through the code in which a FILE * can have fclose called on it more than once. ๐ญ
-Wno-analyzer-double-freeโ This warning requires-fanalyzer, which enables it; use-Wno-analyzer-double-freeto disable it. ๐
This diagnostic warns for paths through the code in which a pointer can have a deallocator called on it more than once โ either free, or a deallocator referenced by attribute malloc. ๐
Okay bestie, buckle up, because this chunk is the analyzer warning wall and it is long โ but every single one of these is a real one, so no skimming, iykyk ๐
-Wno-analyzer-exposure-through-output-fileโ this one needs-fanalyzerto switch it on; use-Wno-analyzer-exposure-through-output-fileto switch it off. This diagnostic warns about paths through the code where a security-sensitive value gets written to an output file (think: writing a password into a log file ๐ญ).-Wno-analyzer-file-leakโ needs-fanalyzer, which enables it; use-Wno-analyzer-file-leakto disable it. Warns about paths through the code where a<stdio.h>FILE *stream object gets leaked.-Wno-analyzer-free-of-non-heapโ needs-fanalyzer, which enables it; use-Wno-analyzer-free-of-non-heapto disable it. Warns about paths through the code wherefreeis called on a non-heap pointer (like an on-stack buffer, or a global). Not the vibe.-Wno-analyzer-malloc-leakโ needs-fanalyzer, which enables it; use-Wno-analyzer-malloc-leakto disable it. Warns about paths through the code where a pointer allocated via an allocator gets leaked: eithermalloc, or a function marked with attributemalloc.-Wno-analyzer-mismatching-deallocationโ needs-fanalyzer, which enables it; use-Wno-analyzer-mismatching-deallocationto disable it. Warns about paths through the code where the wrong deallocation function is called on a pointer value, based on which function was used to allocate that pointer value. It'll flag mismatches betweenfree, scalardeleteand vectordelete[], plus anything marked as an allocator/deallocator pair using attributemalloc.-Wno-analyzer-possible-null-argumentโ needs-fanalyzer, which enables it; use-Wno-analyzer-possible-null-argumentto disable it. Warns about paths through the code where a possibly-NULL value gets passed to a function argument marked with__attribute__((nonnull)), which is out here demanding a non-NULL value.-Wno-analyzer-possible-null-dereferenceโ needs-fanalyzer, which enables it; use-Wno-analyzer-possible-null-dereferenceto disable it. Warns about paths through the code where a possibly-NULL value gets dereferenced. ๐-Wno-analyzer-null-argumentโ needs-fanalyzer, which enables it; use-Wno-analyzer-null-argumentto disable it. Warns about paths through the code where a value known to be NULL gets passed to a function argument marked with__attribute__((nonnull))as requiring a non-NULL value.-Wno-analyzer-null-dereferenceโ needs-fanalyzer, which enables it; use-Wno-analyzer-null-dereferenceto disable it. Warns about paths through the code where a value known to be NULL gets dereferenced.-Wno-analyzer-shift-count-negativeโ needs-fanalyzer, which enables it; use-Wno-analyzer-shift-count-negativeto disable it. Warns about paths through the code where a shift is attempted with a negative count. It's analogous to the-Wshift-count-negativediagnostic implemented in the C/C++ front ends, but it's implemented based on analyzing interprocedural paths, rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.-Wno-analyzer-shift-count-overflowโ needs-fanalyzer, which enables it; use-Wno-analyzer-shift-count-overflowto disable it. Warns about paths through the code where a shift is attempted with a count greater than or equal to the precision of the operand's type. Analogous to the-Wshift-count-overflowdiagnostic in the C/C++ front ends, but again it's implemented based on analyzing interprocedural paths rather than merely parsing the syntax tree. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.-Wno-analyzer-stale-setjmp-bufferโ needs-fanalyzer, which enables it; use-Wno-analyzer-stale-setjmp-bufferto disable it. Warns about paths through the code wherelongjmpis called to rewind to ajmp_bufrelating to asetjmpcall in a function that has returned.
When setjmp is called on a jmp_buf to record a rewind location, it records the stack frame. That stack frame becomes invalid when the function containing the setjmp call returns. Trying to rewind to it via longjmp would reference a stack frame that no longer exists, and likely lead to a crash (or worse). Or worse!! ๐
-Wno-analyzer-tainted-allocation-sizeโ this one needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-allocation-sizeto disable it. Warns about paths through the code where a value that could be under an attacker's control is used as the size of an allocation without being sanitized, so that an attacker could inject an excessively large allocation and potentially cause a denial of service attack.
See https://cwe.mitre.org/data/definitions/789.html, CWE-789: Memory Allocation with Excessive Size Value.
-Wno-analyzer-tainted-array-indexโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-array-indexto disable it. Warns about paths through the code where a value that could be under an attacker's control is used as the index of an array access without being sanitized, so that an attacker could inject an out-of-bounds access.
See https://cwe.mitre.org/data/definitions/129.html, CWE-129: Improper Validation of Array Index.
-Wno-analyzer-tainted-divisorโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-divisorto disable it. Warns about paths through the code where a value that could be under an attacker's control is used as the divisor in a division or modulus operation without being sanitized, so that an attacker could inject a division-by-zero. rude tbh-Wno-analyzer-tainted-offsetโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-offsetto disable it. Warns about paths through the code where a value that could be under an attacker's control is used as a pointer offset without being sanitized, so that an attacker could inject an out-of-bounds access.
See https://cwe.mitre.org/data/definitions/823.html, CWE-823: Use of Out-of-range Pointer Offset.
-Wno-analyzer-tainted-sizeโ needs both-fanalyzerand-fanalyzer-checker=taintto enable it; use-Wno-analyzer-tainted-sizeto disable it. Warns about paths through the code where a value that could be under an attacker's control is used as the size of an operation such asmemsetwithout being sanitized, so that an attacker could inject an out-of-bounds access.-Wno-analyzer-unsafe-call-within-signal-handlerโ needs-fanalyzer, which enables it; use-Wno-analyzer-unsafe-call-within-signal-handlerto disable it. Warns about paths through the code where a function known to be async-signal-unsafe (such asfprintf) is called from a signal handler. Ma'am, that is not allowed.-Wno-analyzer-use-after-freeโ needs-fanalyzer, which enables it; use-Wno-analyzer-use-after-freeto disable it. Warns about paths through the code where a pointer is used after a deallocator has been called on it: eitherfree, or a deallocator referenced by attributemalloc.-Wno-analyzer-use-of-pointer-in-stale-stack-frameโ needs-fanalyzer, which enables it; use-Wno-analyzer-use-of-pointer-in-stale-stack-frameto disable it. Warns about paths through the code where a pointer is dereferenced that points to a variable in a stale stack frame. ๐ชฆ-Wno-analyzer-write-to-constโ needs-fanalyzer, which enables it; use-Wno-analyzer-write-to-constto disable it. Warns about paths through the code where the analyzer detects an attempt to write through a pointer to aconstobject. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.-Wno-analyzer-write-to-string-literalโ needs-fanalyzer, which enables it; use-Wno-analyzer-write-to-string-literalto disable it. Warns about paths through the code where the analyzer detects an attempt to write through a pointer to a string literal. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings.-Wno-analyzer-use-of-uninitialized-valueโ needs-fanalyzer, which enables it; use-Wno-analyzer-use-of-uninitialized-valueto disable it. Warns about paths through the code where an uninitialized value is used.
Pertinent parameters for controlling the exploration are: --param analyzer-bb-explosion-factor=value, --param analyzer-max-enodes-per-program-point=value, --param analyzer-max-recursion-depth=value, and --param analyzer-min-snodes-for-call-summary=value.
The following options control the analyzer. ๐
-fanalyzer-call-summariesโ simplify interprocedural analysis by computing the effect of certain calls, rather than exploring all paths through the function from callsite to each possible return.
If enabled, call summaries are only used for functions with more than one call site, and that are sufficiently complicated (as per --param analyzer-min-snodes-for-call-summary=value). Efficiency era. โจ
-fanalyzer-checker=nameโ restrict the analyzer to run just the named checker, and enable it.
Some checkers are disabled by default (even with -fanalyzer), such as the taint checker that implements -Wanalyzer-tainted-array-index, and this option is required to enable them.
Note: currently, -fanalyzer-checker=taint disables the following warnings from -fanalyzer:
-Wanalyzer-double-fclose,-Wanalyzer-double-free,-Wanalyzer-exposure-through-output-file,-Wanalyzer-file-leak,-Wanalyzer-free-of-non-heap,-Wanalyzer-malloc-leak,-Wanalyzer-mismatching-deallocation,-Wanalyzer-null-argument,-Wanalyzer-null-dereference,-Wanalyzer-possible-null-argument,-Wanalyzer-possible-null-dereference,-Wanalyzer-unsafe-call-within-signal-handler,-Wanalyzer-use-after-free-fno-analyzer-feasibilityโ bestie this one is literally for the analyzer devs, not us ๐. Here's the tea: by default the analyzer double-checks that there's actually a feasible control flow path for every diagnostic it hands you โ like, the conditions that hold aren't mutually exclusive, no cap. Any diagnostic where it can't find a feasible path gets straight up rejected. Wanna kill that filtering?-fno-analyzer-feasibilitydoes it, for debugging issues in this code.-fanalyzer-fine-grainedโ also an analyzer-developer-only vibe ๐ ๏ธ. So internally the analyzer builds an "exploded graph" that combines control flow graphs with data flow information. Normally an edge in that graph can carry the effects of a whole run of multiple statements inside one basic block. With-fanalyzer-fine-grained, every single statement gets its own edge. Every one. ๐-fanalyzer-show-duplicate-countโ devs only again โจ. If multiple diagnostics got detected as being duplicates of each other, this makes it emit a note when reporting the best diagnostic, and that note tells you the number of extra diagnostics that got suppressed by the deduplication logic. Receipts, basically ๐งพ.-fno-analyzer-state-mergeโ analyzer developers, you know the drill. By default the analyzer tries to simplify analysis by merging sufficiently similar states at each program point while it's building its "exploded graph". With-fno-analyzer-state-mergethat merging gets suppressed, for debugging state-handling issues.-fno-analyzer-state-purgeโ devs only ๐ซถ. By default the analyzer tries to simplify analysis by purging aspects of state at a program point that appear to no longer be relevant โ e.g. the values of locals that aren't accessed later in the function and which aren't relevant to leak analysis. With-fno-analyzer-state-purgethis purging of state can be suppressed, for debugging state-handling issues.-fanalyzer-transitivityโ this one enables transitivity of constraints within the analyzer. That's it, that's the whole vibe โญ.-fanalyzer-verbose-edgesโ analyzer developers โจ. It enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. More words, more detail, more chaos.-fanalyzer-verbose-state-changesโ analyzer developers again ๐. It enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths.-fanalyzer-verbosity=levelโ this icon controls how complex the control flow paths are that get emitted for analyzer diagnostics. And level can be one of:- At this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
freediagnostic, both calls tofreewill be shown. - As per the previous level, but also show events for the entry to each function.
- As per the previous level, but also show events relating to control flow that are significant to triggering the issue (e.g. "true path taken" at a conditional). This level is the default ๐.
- As per the previous level, but show all control flow events, not just significant ones.
- This level is intended for analyzer developers; it adds various other events intended for debugging the analyzer.
- At this level, interprocedural call and return events are displayed, along with the most pertinent state-change events relating to a diagnostic. For example, for a double-
-fdump-analyzerโ dumps internal details about what the analyzer is doing tofile.analyzer.txt. Heads up though: this option is overridden by-fdump-analyzer-stderr.-fdump-analyzer-stderrโ dumps internal details about what the analyzer is doing tostderr. And this one overrides-fdump-analyzer. They're beefing, basically ๐.-fdump-analyzer-callgraphโ dumps a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot. Pretty picture time ๐.-fdump-analyzer-exploded-graphโ dumps a representation of the "exploded graph" suitable for viewing with GraphViz tofile.eg.dot. Nodes are color-coded based on state-machine states to emphasize state changes. Gorgeous, honestly.-fdump-analyzer-exploded-nodesโ emits diagnostics showing where nodes in the "exploded graph" are in relation to the program source.-fdump-analyzer-exploded-nodes-2โ dumps a textual representation of the "exploded graph" tofile.eg.txt.-fdump-analyzer-exploded-nodes-3โ dumps a textual representation of the "exploded graph" to one dump file per node, tofile.eg-id.txt. Ngl this is typically a large number of dump files ๐ญ. You've been warned.-fdump-analyzer-exploded-pathsโ dumps a textual representation of the "exploded path" for each diagnostic tofile.idx.kind.epath.txt.-fdump-analyzer-feasibilityโ dumps internal details about the analyzer's search for feasible paths. The details are written in a form suitable for viewing with GraphViz to filenames of the formfile.*.fg.dot,file.*.tg.dot, andfile.*.fpath.txt.-fdump-analyzer-jsonโ dumps a compressed JSON representation of analyzer internals tofile.analyzer.json.gz. The precise format is subject to change โ so don't go building your whole life around it fr fr.-fdump-analyzer-state-purgeโ as per-fdump-analyzer-supergraph, dumps a representation of the "supergraph" suitable for viewing with GraphViz, but annotates the graph with information on what state will be purged at each node. The graph is written tofile.state-purge.dot.-fdump-analyzer-supergraphโ dumps representations of the "supergraph" suitable for viewing with GraphViz tofile.supergraph.dotand tofile.supergraph-eg.dot. These show all of the control flow graphs in the program, with interprocedural edges for calls and returns. The second dump contains annotations showing nodes in the "exploded graph" and diagnostics associated with them. So much lore in two files ๐ฆ.-fdump-analyzer-untrackedโ emits custom warnings with internal details intended for analyzer developers.
๐ Options for Debugging Your Program ๐
Okay bestie, so you want your debugger to actually understand your program? In almost all cases you literally just need to add -g to your other options and you're done ๐
. Some debug formats can co-exist (like DWARF with CTF) when each of them is enabled explicitly by adding the respective command line option to your other options.
GCC lets you use -g with -O. But the shortcuts taken by optimized code may occasionally be surprising, and I need you to be so serious about this list:
- some variables you declared may not exist at all ๐ญ
- flow of control may briefly move where you did not expect it
- some statements may not be executed because they compute constant results or their values are already at hand
- some statements may execute in different places because they have been moved out of loops
Nevertheless it is possible to debug optimized output. This makes it reasonable to use the optimizer for programs that might have bugs. So like, it's giving chaos but it's fine, it works.
If you are not using some other optimization option, consider using -Og with -g. Here's why: with no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so -Og may result in a better debugging experience. Main character debugging energy โจ.
-gโ produce debugging information in the operating system's native format (stabs, COFF, XCOFF, or DWARF). GDB can work with this debugging information.
On most systems that use stabs format, -g enables use of extra debugging information that only GDB can use; this extra information makes debugging work better in GDB but probably makes other debuggers crash or refuse to read the program ๐. If you want to control for certain whether to generate the extra information, use -gstabs+, -gstabs, -gxcoff+, -gxcoff, or -gvms (see below).
-ggdbโ produce debugging information for use by GDB. This means to use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible. Going all out, basically ๐ซถ.-gdwarf-gdwarf-version
Produce debugging information in DWARF format (if that is supported). The value of version may be either 2, 3, 4 or 5; the default version for most targets is 5 (with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version 2, and AIX, which defaults to version 4).
Note that with DWARF Version 2, some ports require and always use some non-conflicting DWARF 3 extensions in the unwind tables.
Version 4 may require GDB 7.0 and -fvar-tracking-assignments for maximum benefit. Version 5 requires GDB 8.0 or higher.
GCC no longer supports DWARF Version 1, which is substantially different than Version 2 and later. For historical reasons, some other DWARF-related options such as -fno-dwarf2-cfi-asm) retain a reference to DWARF Version 2 in their names, but apply to all currently-supported versions of DWARF. (Yes, that's the vibe of legacy naming, we don't question it ๐.)
-gbtfโ request BTF debug information. BTF is the default debugging format for the eBPF target. On other targets, like x86, BTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.-gctf-gctflevel
Request CTF debug information and use level to specify how much CTF debug information should be produced. If -gctf is specified without a value for level, the default level of CTF debug information is 2.
CTF debug information can be generated along with DWARF debug information when both of the debug formats are enabled explicitly via their respective command line options.
Level 0 produces no CTF debug information at all. Thus, -gctf0 negates -gctf.
Level 1 produces CTF information for tracebacks only. This includes callsite information, but does not include type information.
Level 2 produces type information for entities (functions, data objects etc.) at file-scope or global-scope only.
-gstabsโ okay so this one makes debugging info in stabs format (if it's even supported), and like, without GDB extensions. It's the format DBX uses on most BSD systems. BUT bestie, heads up ๐: on MIPS, Alpha and System V Release 4 systems this option makes stabs debugging output that DBX literally cannot understand. And on System V Release 4 systems? This option needs the GNU assembler. No cap.-gstabs+โ same stabs vibe, but this time with the GNU extensions that only the GNU debugger (GDB) gets. The way these extensions work... other debuggers will probably crash or just flat-out refuse to read your program. It's giving exclusive ๐ .-gxcoffโ debugging info in XCOFF format (if supported). This is the one DBX uses on IBM RS/6000 systems. Periodt.-gxcoff+โ XCOFF format (if supported) but with GNU extensions understood only by GDB. And like... using these extensions is likely to make other debuggers crash or refuse to read the program, AND it may cause assemblers that aren't the GNU assembler (GAS) to fail with an error. So cute but dangerous ๐ซถ.-gvmsโ debugging info in Alpha/VMS debug format (if supported). This is what DEBUG uses on Alpha/VMS systems. Iconic in its own niche way.-glevel,-ggdblevel,-gstabslevel,-gxcofflevel,-gvmslevelโ ask for debugging info AND use level to say how much info you want. Default level is2, slay.- Level
0produces literally no debug information at all. So-g0negates-g. bye ๐ - Level
1is minimal โ enough for backtraces in parts of the program you don't plan to debug. It includes descriptions of functions and external variables, and line number tables, but NO info about local variables. - Level
3has extra info, like all the macro definitions present in the program. Some debuggers support macro expansion when you use-g3โจ.
- Level
If you use multiple -g options, with or without level numbers, the last such option is the one that's effective. Last one wins, always.
Lowkey important:-gdwarfdoes not accept a concatenated debug level, to avoid confusion with-gdwarf-level. Instead use an additional-gleveloption to change the debug level for DWARF. Don't fight it ๐.
-fno-eliminate-unused-debug-symbolsโ by default, no debug info is produced for symbols that aren't actually used. Use this if you want debug info for all the symbols. Main character energy for every symbol, fr fr.-femit-class-debug-alwaysโ instead of emitting debugging info for a C++ class in only one object file, emit it in all object files using the class. Use this only with debuggers that can't handle the way GCC normally emits debugging info for classes, because using it increases the size of debugging info by as much as a factor of two. That's a lot ๐ญ.-fno-merge-debug-stringsโ tells the linker to not merge together strings in the debugging info that are identical in different object files. Merging isn't supported by all assemblers or linkers. Merging decreases the size of the debug info in the output file at the cost of increasing link processing time. And btw, merging is enabled by default.-fdebug-prefix-map=old=newโ when compiling files living in directory old, record debugging info describing them as if they lived in directory new instead. You can use this to swap a build-time path for an install-time path in the debug info. You can also use it to turn an absolute path into a relative path by using.for new. This gives more reproducible builds that are location independent, but it may need an extra command to tell GDB where to find the source files. See also-ffile-prefix-map๐.-fvar-trackingโ runs the variable tracking pass. It computes where variables are stored at each position in code, and then better debugging info gets generated (if the debugging info format supports this info). It's enabled by default when compiling with optimization (-Os,-O,-O2, ...), debugging information (-g), and the debug info format supports it. Chef's kiss ๐ค.-fvar-tracking-assignmentsโ annotates assignments to user variables early in compilation and tries to carry those annotations all the way to the end, in an attempt to improve debug info while optimizing. Using-gdwarf-4alongside it is recommended, bestie.
It can be enabled even if var-tracking is disabled โ in that case the annotations get created and maintained, but discarded at the end. By default this flag is enabled together with -fvar-tracking, except when selective scheduling is enabled.
-gsplit-dwarfโ if DWARF debugging info is enabled, this separates as much debug info as possible into a separate output file with the.dwoextension. It lets the build system avoid linking files with debug info. To actually be useful, this option requires a debugger capable of reading.dwofiles. iykyk ๐ฆ.-gdwarf32,-gdwarf64โ if DWARF debugging info is enabled,-gdwarf32selects the 32-bit DWARF format and-gdwarf64selects the 64-bit DWARF format. The default is target specific, but on most targets it's-gdwarf32. The 32-bit format is smaller, but can't support more than 2GiB of debug info in any of the DWARF debug info sections. The 64-bit format allows larger debug info and might not be well supported by all consumers yet. Trade-offs, always trade-offs ๐ .-gdescribe-diesโ adds description attributes to some DWARF DIEs that have no name attribute, like artificial variables, external references and call site parameter DIEs. Little glow-up for the nameless ones โจ.-gpubnamesโ generates DWARF.debug_pubnamesand.debug_pubtypessections. That's it, that's the whole job.-ggnu-pubnamesโ generates.debug_pubnamesand.debug_pubtypessections in a format suitable for conversion into a GDB index. This is only useful with a linker that can produce GDB index version7.-fdebug-types-sectionโ when using DWARF Version 4 or higher, type DIEs can go into their own.debug_typessection instead of being part of the.debug_infosection. Putting them in a separate comdat section is more efficient since the linker can then remove duplicates. BUT not all DWARF consumers support.debug_typessections yet, and on some objects.debug_typesproduces larger instead of smaller debugging info. So it's giving... mixed results ๐.-grecord-gcc-switches,-gno-record-gcc-switchesโ this switch appends the command-line options used to invoke the compiler that may affect code generation to theDW_AT_producerattribute in DWARF debugging info. The options are concatenated with spaces separating them from each other and from the compiler version. It's enabled by default. See also-frecord-gcc-switchesfor another way of storing compiler options into the object file.-gstrict-dwarfโ disallows using extensions of later DWARF standard versions than the one selected with-gdwarf-version. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed. This one says no ๐.-gno-strict-dwarfโ allows using extensions of later DWARF standard versions than selected with-gdwarf-version. Live a little.-gas-loc-supportโ informs the compiler that the assembler supports.locdirectives. It may then use them for the assembler to generate DWARF2+ line number tables.
This is generally desirable, because assembler-generated line-number tables are a lot more compact than the ones the compiler can generate itself ๐
This option gets enabled by default if, at GCC configure time, the assembler was found to support such directives.
-gno-as-loc-supportโ forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are to be generated. Do it yourself energy.-gas-locview-supportโ informs the compiler that the assembler supports "view" assignment and reset assertion checking in.locdirectives.
This option gets enabled by default if, at GCC configure time, the assembler was found to support them.
-gno-as-locview-supportโ forces GCC to assign view numbers internally, if-gvariable-location-viewsare explicitly requested.-gcolumn-info,-gno-column-infoโ emit location column information into DWARF debugging info, not just file and line. This option is enabled by default. We love a little extra detail ๐ .-gstatement-frontiers,-gno-statement-frontiersโ makes GCC create markers in the internal representation at the beginning of statements, and keep them roughly in place throughout compilation, using them to guide the output ofis_stmtmarkers in the line number table. Enabled by default when compiling with optimization (-Os,-O1,-O2, ...) and outputting DWARF 2 debug info at the normal level.-gvariable-location-views,-gvariable-location-views=incompat5,-gno-variable-location-viewsโ augments variable location lists with progressive view numbers implied from the line number table. This lets debug info consumers inspect state at certain points of the program, even if no instructions associated with the corresponding source locations are present at that point. If the assembler lacks support for view numbers in line number tables, this will cause the compiler to emit the line number table, which generally makes them somewhat less compact. The augmented line number tables and location lists are fully backward-compatible, so they can be consumed by debug info consumers that aren't aware of these augmentations โ but they won't derive any benefit from them either. So like, harmless, just not helpful ๐.
This is enabled by default when outputting DWARF 2 debug info at the normal level, as long as there's assembler support, -fvar-tracking-assignments is enabled and -gstrict-dwarf is not. When assembler support isn't available, this may still be enabled, but it will force GCC to output internal line number tables โ and if -ginternal-reset-location-views isn't enabled, that will most certainly lead to silently mismatching location views. Silent mismatches?? Not the vibe ๐ญ.
There's a proposed way to represent view numbers that is not backward compatible with the location list format introduced in DWARF 5, and you can turn it on with -gvariable-location-views=incompat5. Fair warning bestie: this option may be removed in the future, and it's only there as a reference implementation of the proposed representation. Debug info consumers are not expected to support this extended format, and if they tried, they'd be totally unable to decode location lists using it. It's giving "reference only, do not ship" energy ๐
โจ MORE -g OPTIONS โจ (continued)
-ginternal-reset-location-views/-gno-internal-reset-location-viewsโ tries to figure out which location views can be left out of the location view lists. The catch? This needs the compiler to have super accurate insn length estimates, which isn't always the vibe, and it can silently generate wrong view lists when you're using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a "view number mismatch". It's only enabled on ports that define a reliable estimation function. ๐-ginline-points/-gno-inline-pointsโ generates extended debug info for inlined functions. Location view tracking markers get inserted at inlined entry points, so address and view numbers can be computed and written out in the debug info. You can enable this independently of location views โ in which case the view numbers just won't be output โ but it can only be enabled along with statement frontiers, and it's only on by default if location views are enabled. cute, layered, conditional โจ-gz[=type]โ produces compressed debug sections in DWARF format, if that's supported. If type isn't given, the default depends on what the assembler and linker you're using can actually do. type can be one ofnone(don't compress debug sections, bestie, we're rawdogging it),zlib(use zlib compression in ELF gABI format), orzlib-gnu(use zlib compression in traditional GNU format). If the linker doesn't support writing compressed debug sections, the option gets rejected outright. Otherwise, if the assembler doesn't support them,-gzis silently ignored when producing object files. ๐-femit-struct-debug-baseonlyโ emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file where the struct is defined.
This one substantially shrinks your debugging info, but at significant potential loss of type information for the debugger. Peep -femit-struct-debug-reduced for a less aggressive option, or -femit-struct-debug-detailed for the full granular control. iykyk
Heads up: this option works only with DWARF debug output.
-femit-struct-debug-reducedโ emits debug info for struct-like types only when the base name of the compilation source file matches the base name of the file where the type is defined โ unless the struct is a template or defined in a system header.
This one significantly shrinks your debugging info, with some potential loss of type info to the debugger. See -femit-struct-debug-baseonly for the more aggressive version, and -femit-struct-debug-detailed for more detailed control. a little less feral than baseonly fr fr
Again, this works only with DWARF debug output.
-femit-struct-debug-detailed[=spec-list]โ lets you specify exactly which struct-like types the compiler generates debug info for. The whole intent is to cut down on duplicate struct debug info across different object files in the same program. deduplication slay
This option is basically the detailed version of -femit-struct-debug-reduced and -femit-struct-debug-baseonly, and honestly it serves most needs.
A specification has the syntax:
[dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word limits the spec to structs used directly (dir:) or used indirectly (ind:). A struct type is used directly when it's the type of a variable or member. Indirect uses come through pointers to structs โ that is, when use of an incomplete struct is valid, the use is indirect. Example bestie: struct one direct; struct two * indirect;.
The optional second word limits the spec to ordinary structs (ord:) or generic structs (gen:). Generic structs are a bit complicated to explain, ngl. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other programming languages have generics, but -femit-struct-debug-detailed doesn't implement them yet. one day maybe
The third word specifies the source files for those structs for which the compiler should emit debug info. The values none and any have their normal meaning. The value base means the base of the name of the file where the type declaration appears must match the base of the name of the main compilation file. In practice that means: when compiling foo.c, debug info is generated for types declared in that file and foo.h, but not other header files. The value sys means those types satisfying base or declared in system or compiler headers.
You may need to experiment to figure out the best settings for your application. fr fr, there's no one-size-fits-all here
The default is -femit-struct-debug-detailed=all.
And yes, this option works only with DWARF debug output.
-fno-dwarf2-cfi-asmโ emits DWARF unwind info as a compiler-generated.eh_framesection instead of using GAS.cfi_*directives. swapping the sauce ๐-fno-eliminate-unused-debug-typesโ normally, when producing DWARF output, GCC avoids producing debug symbol output for types that are used nowhere in the source file being compiled. But sometimes it's useful to have GCC emit debugging info for all types declared in a compilation unit, regardless of whether they're actually used in that compilation unit โ for example, if in the debugger you want to cast a value to a type that isn't actually used in your program (but is declared). More often, though, this just results in a significant amount of wasted space. storage said nope
๐ OPTIONS THAT CONTROL OPTIMIZATION ๐
These options control various sorts of optimizations. the main character section โจ
Without any optimization option, the compiler's goal is to reduce the cost of compilation and to make debugging produce the expected results. Statements are independent: if you stop the program with a breakpoint between statements, you can then assign a new value to any variable or change the program counter to any other statement in the function and get exactly the results you expect from the source code. predictable, honest, no surprises
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
The compiler performs optimization based on the knowledge it has of the program. Compiling multiple files at once to a single output file mode allows the compiler to use info gained from all of the files when compiling each of them. teamwork makes the dream work
Not all optimizations are controlled directly by a flag. Only optimizations that have a flag are listed in this section.
Most optimizations are completely disabled at-O0or if an-Olevel is not set on the command line, even if individual optimization flags are specified. Similarly,-Ogsuppresses many optimization passes.
Depending on the target and how GCC was configured, a slightly different set of optimizations may be enabled at each -O level than those listed here. You can invoke GCC with -Q --help=optimizers to find out the exact set of optimizations that are enabled at each level. go look it up bestie, don't guess โจ
๐ -O / -O1 ๐
-O -O1 โ Optimize. Optimizing compilation takes somewhat more time, and a lot more memory for a large function.
With -O, the compiler tries to reduce code size and execution time, without performing any optimizations that take a great deal of compilation time.
-O turns on the following optimization flags:
-fauto-inc-dec -fbranch-count-reg -fcombine-stack-adjustments
-fcompare-elim -fcprop-registers -fdce -fdefer-pop -fdelayed-branch
-fdse -fforward-propagate -fguess-branch-probability -fif-conversion
-fif-conversion2 -finline-functions-called-once -fipa-modref
-fipa-profile -fipa-pure-const -fipa-reference
-fipa-reference-addressable -fmerge-constants -fmove-loop-invariants
-fmove-loop-stores -fomit-frame-pointer -freorder-blocks
-fshrink-wrap -fshrink-wrap-separate -fsplit-wide-types
-fssa-backprop -fssa-phiopt -ftree-bit-ccp -ftree-ccp -ftree-ch
-ftree-coalesce-vars -ftree-copy-prop -ftree-dce
-ftree-dominator-opts -ftree-dse -ftree-forwprop -ftree-fre
-ftree-phiprop -ftree-pta -ftree-scev-cprop -ftree-sink -ftree-slsr
-ftree-sra -ftree-ter -funit-at-a-time
๐ -O2 ๐
-O2 โ Optimize even more. GCC performs nearly all supported optimizations that don't involve a space-speed tradeoff. Compared to -O, this option increases both compilation time and the performance of the generated code.
-O2 turns on all optimization flags specified by -O1. It also turns on the following optimization flags:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fcaller-saves -fcode-hoisting -fcrossjumping -fcse-follow-jumps
-fcse-skip-blocks -fdelete-null-pointer-checks -fdevirtualize
-fdevirtualize-speculatively -fexpensive-optimizations
-ffinite-loops -fgcse -fgcse-lm -fhoist-adjacent-loads
-finline-functions -finline-small-functions -findirect-inlining
-fipa-bit-cp -fipa-cp -fipa-icf -fipa-ra -fipa-sra -fipa-vrp
-fisolate-erroneous-paths-dereference -flra-remat
-foptimize-sibling-calls -foptimize-strlen -fpartial-inlining
-fpeephole2 -freorder-blocks-algorithm=stc
-freorder-blocks-and-partition -freorder-functions
-frerun-cse-after-loop -fschedule-insns -fschedule-insns2
-fsched-interblock -fsched-spec -fstore-merging -fstrict-aliasing
-fthread-jumps -ftree-builtin-call-dce -ftree-loop-vectorize
-ftree-pre -ftree-slp-vectorize -ftree-switch-conversion
-ftree-tail-merge -ftree-vrp -fvect-cost-model=very-cheap
Please note the warning under-fgcseabout invoking-O2on programs that use computed gotos. don't skip this one bestie
NOTE: In Ubuntu 8.10 and later versions,-D_FORTIFY_SOURCE=2, in Ubuntu 24.04 and later versions,-D_FORTIFY_SOURCE=3, is set by default, and is activated when-Ois set to 2 or higher. This enables additional compile-time and run-time checks for several libc functions. To disable, specify either-U_FORTIFY_SOURCEor-D_FORTIFY_SOURCE=0. Ubuntu said safety first ๐
๐ฅ -O3 ๐ฅ
-O3 โ Optimize yet more. -O3 turns on all optimizations specified by -O2 and also turns on the following optimization flags:
-fgcse-after-reload-fipa-cp-clone-floop-interchange-floop-unroll-and-jam-fpeel-loops-fpredictive-commoning-fsplit-loops-fsplit-paths-ftree-loop-distribution-ftree-partial-pre-funswitch-loops-fvect-cost-model=dynamic-fversion-loops-for-strides
โจ the -O levels, one by one โจ
-O0โ okay so this one says: chill, keep compilation fast, and make debugging actually give you the results you expect. This is the default. ๐-Osโ optimize for size, bestie.-Osturns on all the-O2optimizations except the ones that love to make your code fatter:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, makes the compiler tune for code size instead of execution speed, and does a whole extra round of optimizations that are designed to shrink your code. ๐
-Ofastโ the chaotic one. Disregard strict standards compliance.-Ofastenables all-O3optimizations, and then it ALSO enables optimizations that are not valid for all standard-compliant programs. It turns on-ffast-math,-fallow-store-data-races, and the Fortran-specific-fstack-arrays(unless-fmax-stack-var-sizeis specified), plus-fno-protect-parens. And it turns off-fsemantic-interposition. โจ-Ogโ optimize the debugging experience, fr.-Ogshould be your optimization level of choice for the standard edit-compile-debug cycle: a reasonable level of optimization while keeping compilation fast and debugging good. It's a better pick than-O0for producing debuggable code, because some compiler passes that collect debug info are disabled at-O0. ๐ญ
Like -O0, -Og completely disables a bunch of optimization passes so that the individual options controlling them have no effect. Otherwise, -Og enables all -O1 optimization flags except for the ones that might mess with debugging:
-fbranch-count-reg -fdelayed-branch -fdse -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants -fmove-loop-stores -fssa-phiopt
-ftree-bit-ccp -ftree-dse -ftree-pta -ftree-sra
-Ozโ optimize aggressively for size rather than speed. Note: this may increase the number of instructions executed if those instructions require fewer bytes to encode.-Ozbehaves similarly to-Os, including enabling most-O2optimizations. ๐
Real talk: if you use multiple -O options, with or without level numbers, the last one is the one that's effective. Periodt.
๐ฆ the -fflag situation ๐ฆ
Options of the form -fflag specify machine-independent flags. Most flags have both a positive and a negative form; the negative form of -ffoo is -fno-foo. In the table below, only one of the forms is listed โ the one you typically use. You can figure out the other form by either removing no- or adding it. iykyk. ๐
The following options control specific optimizations. They're either activated by -O options or related to ones that are. You can use these flags in the rare cases when you want to "fine-tune" the optimizations being performed. Fancy.
-fno-defer-popโ for machines that have to pop arguments after a function call, this makes them always pop the arguments as soon as each function returns. At levels-O1and higher,-fdefer-popis the default, which lets the compiler let arguments pile up on the stack over several function calls and pop them all at once. ๐ธ-fforward-propagateโ does a forward propagation pass on RTL. The pass tries to combine two instructions and checks whether the result can be simplified. If loop unrolling is active, two passes happen and the second is scheduled after loop unrolling.
This option is enabled by default at optimization levels -O1, -O2, -O3, -Os.
-ffp-contract=styleโ-ffp-contract=offdisables floating-point expression contraction.-ffp-contract=fastenables floating-point expression contraction, like forming fused multiply-add operations if the target has native support for them.-ffp-contract=onenables floating-point expression contraction if it's allowed by the language standard โ but this is currently not implemented and is treated equal to-ffp-contract=off. ๐
The default is -ffp-contract=fast.
-fomit-frame-pointerโ omit the frame pointer in functions that don't need one. This avoids the instructions to save, set up and restore the frame pointer; on many targets it also frees up an extra register. โจ
On some targets this flag has no effect, because the standard calling sequence always uses a frame pointer, so it can't be omitted.
Note that -fno-omit-frame-pointer doesn't guarantee the frame pointer is used in all functions โ several targets always omit the frame pointer in leaf functions.
Enabled by default at -O1 and higher.
-foptimize-sibling-callsโ optimizes sibling and tail recursive calls.
Enabled at levels -O2, -O3, -Os.
-foptimize-strlenโ optimizes various standard C string functions (e.g.strlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives.
Enabled at levels -O2, -O3.
-fno-inlineโ do not expand any functions inline, apart from those marked with thealways_inlineattribute. This is the default when not optimizing.
Single functions can be exempted from inlining by marking them with the noinline attribute.
-finline-small-functionsโ integrate functions into their callers when their body is smaller than the expected function call code (so the overall size of the program gets smaller). The compiler heuristically decides which functions are simple enough to be worth integrating this way. This inlining applies to all functions, even those not declaredinline. ๐
Enabled at levels -O2, -O3, -Os.
-findirect-inliningโ inline also indirect calls that are discovered to be known at compile time thanks to previous inlining. This option only has any effect when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
Enabled at levels -O2, -O3, -Os.
-finline-functionsโ consider all functions for inlining, even if they're not declaredinline. The compiler heuristically decides which functions are worth integrating this way.
If all calls to a given function are integrated, and the function is declared static, then the function is normally not output as assembler code in its own right.
Enabled at levels -O2, -O3, -Os. Also enabled by -fprofile-use and -fauto-profile.
-finline-functions-called-onceโ consider allstaticfunctions called once for inlining into their caller, even if they're not markedinline. If a call to a given function is integrated, then the function is not output as assembler code in its own right.
Enabled at levels -O1, -O2, -O3 and -Os, but not -Og.
-fearly-inliningโ inline functions marked byalways_inlineand functions whose body seems smaller than the function call overhead early, before doing-fprofile-generateinstrumentation and the real inlining pass. Doing this makes profiling significantly cheaper and usually makes inlining faster on programs with large chains of nested wrapper functions.
Enabled by default. ๐ซถ
-fipa-sraโ perform interprocedural scalar replacement of aggregates, removal of unused parameters, and replacement of parameters passed by reference with parameters passed by value.
Enabled at levels -O2, -O3 and -Os.
-finline-limit=nโ by default, GCC limits the size of functions that can be inlined. This flag allows coarse control of that limit.nis the size of functions that can be inlined, in number of pseudo instructions.
Inlining is actually controlled by a number of parameters, which may be specified individually by using --param name=value. The -finline-limit=n option sets some of these parameters as follows:
max-inline-insns-singleis set ton/2.max-inline-insns-autois set ton/2.
See below for documentation of the individual parameters controlling inlining and for the defaults of these parameters.
Note: there may be no value to -finline-limit that results in default behavior.
Note: a pseudo instruction represents, in this particular context, an abstract measurement of a function's size. In no way does it represent a count of assembly instructions, and as such its exact meaning might change from one release to another. ๐ญ
-fno-keep-inline-dllexportโ this is a more fine-grained version of-fkeep-inline-functions, which applies only to functions that are declared using thedllexportattribute or declspec.-fkeep-inline-functionsโ in C, emitstaticfunctions that are declaredinlineinto the object file, even if the function has been inlined into all of its callers. This switch does not affect functions using theextern inlineextension in GNU C90. In C++, emit any and all inline functions into the object file. ๐-fkeep-static-functionsโ emitstaticfunctions into the object file, even if the function is never used.-fkeep-static-constsโ emit variables declaredstatic constwhen optimization isn't turned on, even if the variables aren't referenced.
GCC enables this option by default. If you want to force the compiler to check whether a variable is referenced, regardless of whether optimization is turned on or not, use the -fno-keep-static-consts option.
-fmerge-constantsโ attempt to merge identical constants (string constants and floating-point constants) across compilation units.
This option is the default for optimized compilation if the assembler and linker support it. Use -fno-merge-constants to inhibit this behavior.
Enabled at levels -O1, -O2, -O3, -Os.
-fmerge-all-constantsโ attempt to merge identical constants and identical variables.
This option implies -fmerge-constants. In addition to -fmerge-constants, this considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types. Languages like C or C++ require each variable, including multiple instances of the same variable in recursive calls, to have distinct locations, so using this option results in non-conforming behavior. ๐
-fmodulo-schedโ perform swing modulo scheduling immediately before the first scheduling pass. This pass looks at innermost loops and reorders their instructions by overlapping different iterations. ๐-fmodulo-sched-allow-regmovesโ bestie, this one is fancy. It does more aggressive SMS-based modulo scheduling, but with register moves allowed. Turning this on deletes certain anti-dependences edges, which then triggers the generation of reg-moves based on the life-range analysis. It's giving "chaotic but make it efficient" ๐ . Heads up tho: this option is only effective if-fmodulo-schedis enabled. Otherwise it's just sitting there, decorative. โจ-fno-branch-count-regโ okay so this one turns OFF the optimization pass that goes looking for chances to use "decrement and branch" instructions on a count register, instead of the whole "decrement a register, compare it against zero, then branch based on the result" instruction sequence. ๐ This option is only meaningful on architectures that actually support such instructions โ that's x86, PowerPC, IA-64 and S/390, no cap. And watch out:-fno-branch-count-regdoes not remove the decrement and branch instructions from the generated instruction stream that other optimization passes introduced. It's not a cleanup crew, it's just a "don't add more" crew. ๐
The default is -fbranch-count-reg at -O1 and higher, except for -Og.
-fno-function-cseโ do not put function addresses in registers, periodt. Every instruction that calls a constant function has to carry the function's address explicitly. ๐ฆ
Downside: this makes for less efficient code. But also โ some strange hacks that alter the assembler output may get confused by the optimizations that happen when this option is not used, so like, sometimes you want the mess. ๐ญ
The default is -ffunction-cse.
-fno-zero-initialized-in-bssโ if the target supports a BSS section, GCC by default drops variables that are initialized to zero into BSS. Saves space in the resulting code, slay. ๐
This option turns that behavior off, because some programs explicitly rely on variables going to the data section โ like, so the resulting executable can find the beginning of that section and/or make assumptions based on that. Iykyk.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ perform optimizations that check whether a jump branches to a location where another comparison subsumed by the first one lives. If it does, the first branch gets redirected to either the destination of the second branch or a point immediately following it, depending on whether the condition is known to be true or false. ๐ฅ
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-typesโ when you're using a type that occupies multiple registers, likelong longon a 32-bit system, this splits the registers apart and allocates them independently. Normally this generates better code for those types, but it may make debugging more difficult. ๐ (the classic trade: fast or debuggable, pick one)
Enabled at levels -O1, -O2, -O3, -Os.
-fsplit-wide-types-earlyโ fully split wide types early, instead of very late. No effect at all unless-fsplit-wide-typesis turned on, so don't bother otherwise bestie.
This is the default on some targets.
-fcse-follow-jumpsโ in common subexpression elimination (CSE), scan through jump instructions when the target of the jump isn't reached by any other path. For example, when CSE encounters anifstatement with anelseclause, CSE follows the jump when the condition tested is false. ๐ง
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ similar to-fcse-follow-jumps, but it makes CSE follow jumps that conditionally skip over blocks. When CSE encounters a simpleifstatement with no else clause,-fcse-skip-blockscauses CSE to follow the jump around the body of theif. โจ
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ re-run common subexpression elimination after loop optimizations are performed. Like, do it again, but smarter this time. ๐
Enabled at levels -O2, -O3, -Os.
-fgcseโ perform a global common subexpression elimination pass. This pass also does global constant and copy propagation. ๐
Note: when compiling a program using computed gotos โ a GCC extension โ you may get better run-time performance if you disable the global common subexpression elimination pass by adding -fno-gcse to the command line.
Enabled at levels -O2, -O3, -Os.
-fgcse-lmโ when-fgcse-lmis enabled, global common subexpression elimination attempts to move loads that are only killed by stores into themselves. This lets a loop containing a load/store sequence get changed into a load outside the loop, plus a copy/store within the loop. ๐ธ
Enabled by default when -fgcse is enabled.
-fgcse-smโ when-fgcse-smis enabled, a store motion pass runs after global common subexpression elimination. This pass attempts to move stores out of loops. When used in conjunction with-fgcse-lm, loops containing a load/store sequence can be changed to a load before the loop and a store after the loop. ๐ฆ
Not enabled at any optimization level. (yes, really โ you gotta ask for it.)
-fgcse-lasโ when-fgcse-lasis enabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location โ both partial and full redundancies. ๐
Not enabled at any optimization level.
-fgcse-after-reloadโ when-fgcse-after-reloadis enabled, a redundant load elimination pass is performed after reload. The whole point of this pass is to clean up redundant spilling. ๐งนโจ
Enabled by -O3, -fprofile-use and -fauto-profile.
-faggressive-loop-optimizationsโ this tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. Which assumes loop code does not invoke undefined behavior โ for example, by causing signed integer overflows or out-of-bound array accesses. ๐ซ The bounds for the number of iterations of a loop get used to guide loop unrolling and peeling and loop exit test optimizations.
This option is enabled by default.
-funconstrained-commonsโ this tells the compiler that variables declared in common blocks (e.g. Fortran) may later be overridden with longer trailing arrays. This prevents certain optimizations that depend on knowing the array bounds. ๐-fcrossjumpingโ perform cross-jumping transformation. This transformation unifies equivalent code and saves code size. The resulting code may or may not perform better than without cross-jumping โ it's giving "vibes unknown, size smaller". ๐
Enabled at levels -O2, -O3, -Os.
-fauto-inc-decโ combine increments or decrements of addresses with memory accesses. This pass is always skipped on architectures that don't have instructions to support it. Enabled by default at-O1and higher on architectures that support this. โญ-fdceโ perform dead code elimination (DCE) on RTL. Enabled by default at-O1and higher. ๐โ๏ธ-fdseโ perform dead store elimination (DSE) on RTL. Enabled by default at-O1and higher. ๐โ๏ธ-fif-conversionโ attempt to transform conditional jumps into branch-less equivalents. This includes the use of conditional moves, min, max, set flags and abs instructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it's available is controlled by-fif-conversion2. ๐ฅ
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fif-conversion2โ use conditional execution (where available) to transform conditional jumps into branch-less equivalents. Same energy, different toolkit. โจ
Enabled at levels -O1, -O2, -O3, -Os, but not with -Og.
-fdeclone-ctor-dtorโ okay so the C++ ABI requires multiple entry points for constructors and destructors: one for a base subobject, one for a complete object, and one for a virtual destructor that callsoperator deleteafterwards. For a hierarchy with virtual bases, the base and complete variants are clones โ meaning two copies of the function. ๐ญ With this option, the base and complete variants are changed to be thunks that call a common implementation. De-cloned, iconic. ๐
Enabled by -Os.
-fdelete-null-pointer-checksโ assume that programs cannot safely dereference null pointers, and that no code or data element resides at address zero. This option enables simple constant folding optimizations at all optimization levels. On top of that, other optimization passes in GCC use this flag to control global dataflow analyses that eliminate useless checks for null pointers; those assume that a memory access to address zero always results in a trap, so if a pointer is checked after it's already been dereferenced, it cannot be null. ๐
Note tho: in some environments this assumption is not true. Use -fno-delete-null-pointer-checks to disable this optimization for programs that depend on that behavior. Don't get caught out bestie.
This option is enabled by default on most targets. On Nios II ELF, it defaults to off. On AVR, CR16, and MSP430, this option is completely disabled.
Passes that use the dataflow information are enabled independently at different optimization levels.
-fdevirtualizeโ attempt to convert calls to virtual functions to direct calls. This happens both within a procedure and interprocedurally, as part of indirect inlining (-findirect-inlining) and interprocedural constant propagation (-fipa-cp). Enabled at levels-O2,-O3,-Os. ๐-fdevirtualize-speculativelyโ attempt to convert calls to virtual functions to speculative direct calls. Based on the analysis of the type inheritance graph, it determines for a given call the set of likely targets. If the set is small โ preferably of size 1 โ it changes the call into a conditional deciding between direct and indirect calls. The speculative calls enable more optimizations, such as inlining. When they seem useless after further optimization, they're converted back into their original form. It's giving "shoot your shot, walk it back if it flops". ๐-fdevirtualize-at-ltransโ stream extra information needed for aggressive devirtualization when running the link-time optimizer in local transformation mode. This option enables more devirtualization but significantly increases the size of streamed data. For this reason it is disabled by default. ๐ซ-fexpensive-optimizationsโ perform a number of minor optimizations that are relatively expensive. Enabled at levels-O2,-O3,-Os. ๐ธโจ-freeโ attempt to remove redundant extension instructions. This is especially helpful for the x86-64 architecture, which implicitly zero-extends in 64-bit registers after writing to their lower 32-bit half. ๐ฆ
Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.
-fno-lifetime-dseโ okay so in C++ an object's value is only affected by changes that happen inside its lifetime ๐ when the constructor begins the object has an indeterminate value, and any changes made during the object's lifetime are dead the moment it's destroyed. Normally dead store elimination is out here eating that up for breakfast. But if your code is lowkey relying on the value of the object storage persisting beyond the lifetime of the object, this flag turns that optimization off, periodt. Wanna keep stores that happen before the constructor starts (like, say, because youroperator newclears the object storage) but still treat the object as dead after the destructor? Use-flifetime-dse=1, bestie. And the default behavior can be explicitly selected with-flifetime-dse=2. Also-flifetime-dse=0is equivalent to-fno-lifetime-dse. slay.-flive-range-shrinkageโ attempts to decrease register pressure through register live range shrinkage โจ super helpful for fast processors that have small or moderate size register sets. it's giving "my register file is tiny but my CPU is fast" energy.- *
-fira-algorithm=algorithm* โ use the specified coloring algorithm for the integrated register allocator ๐จ the algorithm argument can bepriority, which specifies Chow's priority coloring, orCB, which specifies Chaitin-Briggs coloring. Chaitin-Briggs coloring is not implemented for all architectures, but for those targets that do support it, it's the default because it generates better code. icon behavior honestly. - *
-fira-region=region* โ use specified regions for the integrated register allocator ๐บ๏ธ the region argument should be one of the following:allโ use all loops as register allocation regions. This can give the best results for machines with a small and/or irregular register set.mixedโ use all loops except for loops with small register pressure as the regions. This value usually gives the best results in most cases and for most architectures, and is enabled by default when compiling with optimization for speed (-O,-O2, ...).oneโ use all functions as a single region. This typically results in the smallest code size, and is enabled by default for-Osor-O0.
-fira-hoist-pressureโ use IRA to evaluate register pressure in the code hoisting pass for decisions to hoist expressions ๐ซถ this option usually results in smaller code, but it can slow the compiler down. no free lunch fr fr.
This option is enabled at level -Os for all targets.
-fira-loop-pressureโ use IRA to evaluate register pressure in loops for decisions to move loop invariants ๐ this option usually results in generation of faster and smaller code on machines with large register files (>= 32 registers), but it can slow the compiler down. worth it though ngl.
This option is enabled at level -O3 for some targets.
-fno-ira-share-save-slotsโ disables sharing of stack slots used for saving call-used hard registers living through a call ๐ each hard register gets a separate stack slot, and as a result function stack frames are larger. yeah your frames are gonna be thicc, that's the trade.-fno-ira-share-spill-slotsโ disables sharing of stack slots allocated for pseudo-registers ๐ each pseudo-register that does not get a hard register gets a separate stack slot, and as a result function stack frames are larger. again: thicc frames, that's the vibe.-flra-rematโ enable CFG-sensitive rematerialization in LRA โจ instead of loading values of spilled pseudos, LRA tries to rematerialize (recalculate) values if it is profitable. recalculate not reload, iykyk.
Enabled at levels -O2, -O3, -Os.
-fdelayed-branchโ if supported for the target machine, attempt to reorder instructions to exploit instruction slots available after delayed branch instructions ๐ธ.
Enabled at levels -O1, -O2, -O3, -Os, but not at -Og.
-fschedule-insnsโ if supported for the target machine, attempt to reorder instructions to eliminate execution stalls due to required data being unavailable โณ this helps machines that have slow floating point or memory load instructions by allowing other instructions to be issued until the result of the load or floating-point instruction is required. very "keep busy while you wait" of it.
Enabled at levels -O2, -O3.
-fschedule-insns2โ similar to-fschedule-insns, but requests an additional pass of instruction scheduling after register allocation has been done ๐ฅ especially useful on machines with a relatively small number of registers and where memory load instructions take more than one cycle.
Enabled at levels -O2, -O3, -Os.
-fno-sched-interblockโ disable instruction scheduling across basic blocks, which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher ๐ซ.-fno-sched-specโ disable speculative motion of non-load instructions, which is normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher ๐ซ.-fsched-pressureโ enable register pressure sensitive insn scheduling before register allocation ๐ this only makes sense when scheduling before register allocation is enabled, i.e. with-fschedule-insnsor at-O2or higher. using this option can improve the generated code and decrease its size by preventing register pressure increase above the number of available hard registers and subsequent spills in register allocation. less spilling = more iconic, obviously.-fsched-spec-loadโ allow speculative motion of some load instructions ๐ this only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-spec-load-dangerousโ allow speculative motion of more load instructions ๐ณ note the word dangerous, bestie, it's right there in the name. this only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-stalled-insns-fsched-stalled-insns=n โ define how many insns (if any) can be moved prematurely from the queue of stalled insns into the ready list during the second scheduling pass ๐-fno-sched-stalled-insnsmeans that no insns are moved prematurely,-fsched-stalled-insns=0means there is **no limit on how many queued insns can be moved prematurely, and-fsched-stalled-insnswithout a value is equivalent to-fsched-stalled-insns=1. the way that zero means infinity hereโฆ not me double-checking that twice ๐ญ-fsched-stalled-insns-dep- *
-fsched-stalled-insns-dep=n* โ define how many insn groups (cycles) are examined for a dependency on a stalled insn that is a candidate for premature removal from the queue of stalled insns ๐ this has an effect only during the second scheduling pass, and only if-fsched-stalled-insnsis used.-fno-sched-stalled-insns-depis equivalent to-fsched-stalled-insns-dep=0.-fsched-stalled-insns-depwithout a value is equivalent to-fsched-stalled-insns-dep=1. -fsched2-use-superblocksโ when scheduling after register allocation, use superblock scheduling ๐ฆธ this allows motion across basic block boundaries, resulting in faster schedules. this option is experimental, as not all machine descriptions used by GCC model the CPU closely enough to avoid unreliable results from the algorithm. so like, it's giving mad scientist energy, proceed with awareness ๐งช.
This only makes sense when scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
-fsched-group-heuristicโ enable the group heuristic in the scheduler ๐ this heuristic favors the instruction that belongs to a schedule group. it's enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-critical-path-heuristicโ enable the critical-path heuristic in the scheduler ๐ฃ๏ธ this heuristic favors instructions on the critical path. enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-spec-insn-heuristicโ enable the speculative instruction heuristic in the scheduler โจ this heuristic favors speculative instructions with greater dependency weakness. enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-rank-heuristicโ enable the rank heuristic in the scheduler ๐ this heuristic favors the instruction belonging to a basic block with greater size or frequency. enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-last-insn-heuristicโ enable the last-instruction heuristic in the scheduler ๐ this heuristic favors the instruction that is less dependent on the last instruction scheduled. enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-dep-count-heuristicโ enable the dependent-count heuristic in the scheduler ๐งฎ this heuristic favors the instruction that has more instructions depending on it. enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-freschedule-modulo-scheduled-loopsโ modulo scheduling is performed before traditional scheduling ๐ if a loop is modulo scheduled, later scheduling passes may change its schedule. use this option to control that behavior.-fselective-schedulingโ schedule instructions using the selective scheduling algorithm ๐ฏ selective scheduling runs instead of the first scheduler pass.-fselective-scheduling2โ schedule instructions using the selective scheduling algorithm ๐ฏ selective scheduling runs instead of the second scheduler pass.-fsel-sched-pipeliningโ enable software pipelining of innermost loops during selective scheduling ๐ this option has no effect unless one of-fselective-schedulingor-fselective-scheduling2is turned on.-fsel-sched-pipelining-outer-loopsโ when pipelining loops during selective scheduling, also pipeline outer loops ๐ this option has no effect unless-fsel-sched-pipeliningis turned on.-fsemantic-interpositionโ okay so bestie, some object formats (hi, ELF ๐) let the dynamic linker interpose symbols, meaning for symbols exported from the DSO the compiler literally cannot do interprocedural propagation, inlining, and other optimizations, because the function or variable in question might change on it ๐ญ. It's a genuinely useful feature โ like when you want to rewrite memory allocation functions with a debugging implementation โ but it is expensive in terms of code quality. With-fno-semantic-interpositionthe compiler assumes that if interposition happens for functions, the overwriting function will have precisely the same semantics (and side effects). Same deal for variables: if interposition happens for variables, the constructor of the variable will be the same. This flag has no effect for functions explicitly declaredinline(where it is never allowed for interposition to change semantics) and for symbols explicitly declaredweak. Periodt.-fshrink-wrapโ emit function prologues only right before the parts of the function that actually need it, instead of dumping them at the top of the function like it's 1999 โจ. This flag is enabled by default at-Oand higher.-fshrink-wrap-separateโ shrink-wrap the separate parts of the prologue and epilogue separately, so those parts only get executed when needed ๐. This option is on by default, but it does literally nothing unless-fshrink-wrapis also turned on and the target supports this.-fcaller-savesโ enable allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls ๐ . Such allocation is done only when it seems to result in better code. This option is always enabled by default on certain machines, usually those which have no call-preserved registers to use instead. Enabled at levels-O2,-O3,-Os.-fcombine-stack-adjustmentsโ tracks stack adjustments (pushes and pops) and stack memory references and then tries to find ways to combine them ๐ง. Enabled by default at-O1and higher.-fipa-raโ use caller save registers for allocation if those registers are not used by any called function ๐. In that case it is not necessary to save and restore them around calls. This is only possible if called functions are part of same compilation unit as current function and they are compiled before it. Enabled at levels-O2,-O3,-Os, however the option is disabled if generated code will be instrumented for profiling (-p, or-pg) or if callee's register usage cannot be known exactly (this happens on targets that do not expose prologues and epilogues in RTL).-fconserve-stackโ attempt to minimize stack usage ๐ธ. The compiler attempts to use less stack space, even if that makes the program slower. This option implies setting thelarge-stack-frameparameter to100and thelarge-stack-frame-growthparameter to400.-ftree-reassocโ perform reassociation on trees ๐. This flag is enabled by default at-O1and higher.-fcode-hoistingโ perform code hoisting ๐. Code hoisting tries to move the evaluation of expressions executed on all paths to the function exit as early as possible. This is especially useful as a code size optimization, but it often helps for code speed as well. This flag is enabled by default at-O2and higher.-ftree-preโ perform partial redundancy elimination (PRE) on trees โจ. This flag is enabled by default at-O2and-O3.-ftree-partial-preโ make partial redundancy elimination (PRE) more aggressive ๐ฅ. This flag is enabled by default at-O3.-ftree-forwpropโ perform forward propagation on trees ๐ฆ. This flag is enabled by default at-O1and higher.-ftree-freโ perform full redundancy elimination (FRE) on trees ๐. The difference between FRE and PRE is that FRE only considers expressions that are computed on all paths leading to the redundant computation. This analysis is faster than PRE, though it exposes fewer redundancies. This flag is enabled by default at-O1and higher.-ftree-phipropโ perform hoisting of loads from conditional pointers on trees ๐. This pass is enabled by default at-O1and higher.-fhoist-adjacent-loadsโ speculatively hoist loads from both branches of anif-then-elseif the loads are from adjacent locations in the same structure and the target architecture has a conditional move instruction ๐. This flag is enabled by default at-O2and higher.-ftree-copy-propโ perform copy propagation on trees ๐ธ. This pass eliminates unnecessary copy operations. This flag is enabled by default at-O1and higher.-fipa-pure-constโ discover which functions are pure or constant ๐ง. Enabled by default at-O1and higher.-fipa-referenceโ discover which static variables do not escape the compilation unit ๐. Enabled by default at-O1and higher.-fipa-reference-addressableโ discover read-only, write-only and non-addressable static variables โจ. Enabled by default at-O1and higher.-fipa-stack-alignmentโ reduce stack alignment on call sites if possible ๐. Enabled by default.-fipa-ptaโ perform interprocedural pointer analysis and interprocedural modification and reference analysis ๐ . This option can cause excessive memory and compile-time usage on large compilation units. It is not enabled by default at any optimization level.-fipa-profileโ perform interprocedural profile propagation ๐. The functions called only from cold functions are marked as cold. Also functions executed once (such as"cold","noreturn", static constructors or destructors) are identified. Cold functions and loop less parts of functions executed once are then optimized for size. Enabled by default at-O1and higher.-fipa-modrefโ perform interprocedural mod/ref analysis ๐ฅ. This optimization analyzes the side effects of functions (memory locations that are modified or referenced) and enables better optimization across the function call boundary. This flag is enabled by default at-O1and higher.-fipa-cpโ perform interprocedural constant propagation ๐. This optimization analyzes the program to determine when values passed to functions are constants and then optimizes accordingly. This optimization can substantially increase performance if the application has constants passed to functions. This flag is enabled by default at-O2,-Osand-O3. It is also enabled by-fprofile-useand-fauto-profile.-fipa-cp-cloneโ perform function cloning to make interprocedural constant propagation stronger ๐ฆ. When enabled, interprocedural constant propagation performs function cloning when externally visible function can be called with constant arguments. Because this optimization can create multiple copies of functions, it may significantly increase code size (see--param ipa-cp-unit-growth=value). This flag is enabled by default at-O3. It is also enabled by-fprofile-useand-fauto-profile.-fipa-bit-cpโ when enabled, perform interprocedural bitwise constant propagation โจ. This flag is enabled by default at-O2and by-fprofile-useand-fauto-profile. It requires that-fipa-cpis enabled.-fipa-vrpโ when enabled, perform interprocedural propagation of value ranges ๐. This flag is enabled by default at-O2. It requires that-fipa-cpis enabled.-fipa-icfโ perform Identical Code Folding for functions and read-only variables ๐. The optimization reduces code size and may disturb unwind stacks by replacing a function by equivalent one with a different name. The optimization works more effectively with link-time optimization enabled.
Although the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels and thus the optimizations are not same โ there are equivalences that are found only by GCC and equivalences found only by Gold ๐ค.
This flag is enabled by default at -O2 and -Os.
-flive-patching=levelโ control GCC's optimizations to produce output suitable for live-patching ๐ .
If the compiler's optimization uses a function's body or information extracted from its body to optimize/change another function, the latter is called an impacted function of the former. If a function is patched, its impacted functions should be patched too ๐ญ.
The impacted functions are determined by the compiler's interprocedural optimizations. For example, a caller is impacted when inlining a function into its caller, cloning a function and changing its caller to call this new clone, or extracting a function's pureness/constness information to optimize its direct or indirect callers, etc.
Usually, the more IPA optimizations enabled, the larger the number of impacted functions for each function. In order to control the number of impacted functions and more easily compute the list of impacted function, IPA optimizations can be partially enabled at two different levels.
The level argument should be one of the following:
inline-cloneโ only enable inlining and cloning optimizations, which includes inlining, cloning, interprocedural scalar replacement of aggregates and partial inlining ๐ธ. As a result, when patching a function, all its callers and its clones' callers are impacted, therefore need to be patched as well.
-flive-patching=inline-clone disables the following optimization flags: -fwhole-program -fipa-pta -fipa-reference -fipa-ra -fipa-icf -fipa-icf-functions -fipa-icf-variables -fipa-bit-cp -fipa-vrp -fipa-pure-const -fipa-reference-addressable -fipa-stack-alignment -fipa-modref
inline-only-staticโ only enable inlining of static functions ๐ง. As a result, when patching a static function, all its callers are impacted and so need to be patched as well.
In addition to all the flags that -flive-patching=inline-clone disables, -flive-patching=inline-only-static disables the following additional optimization flags: -fipa-cp-clone -fipa-sra -fpartial-inlining -fipa-cp
When -flive-patching is specified without any value, the default value is inline-clone.
This flag is disabled by default.
Note that-flive-patchingis not supported with link-time optimization (-flto) ๐.
-fisolate-erroneous-paths-dereferenceโ bestie, this one sniffs out paths that would trigger erroneous or undefined behavior because somebody dereferenced a null pointer ๐ญ. It then isolates those paths away from the main control flow and turns that doomed statement into a trap ๐ชค. It's on by default at-O2and higher, and it also needs-fdelete-null-pointer-checksto be enabled at the same time, iykyk.-fisolate-erroneous-paths-attributeโ same energy as above but for a different crime: paths that trigger erroneous or undefined behavior because a null value got used in a way that areturns_nonnullornonnullattribute straight-up forbids ๐ . It isolates those paths from the main control flow and turns the offending statement into a trap too. Heads up tho โ this one is not currently enabled, but it may get enabled by-O2in the future ๐.-ftree-sinkโ does forward store motion on trees โจ. Enabled by default at-O1and higher.-ftree-bit-ccpโ performs sparse conditional bit constant propagation on trees and also propagates pointer alignment info ๐. This pass only messes with local scalar variables, and it's on by default at-O1and higher โ except for-Og. It needs-ftree-ccpto be enabled, no cap.-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees ๐ซ. Again, local scalar variables only, and it's enabled by default at-O1and higher.-fssa-backpropโ propagates info about uses of a value up the definition chain so the definitions can get simplified ๐ธ. Like, for example, this pass strips sign operations if the sign of a value literally never matters. Enabled by default at-O1and higher.-fssa-phioptโ does pattern matching on SSA PHI nodes to optimize conditional code ๐ฆ. Enabled by default at-O1and higher, except for-Og.-ftree-switch-conversionโ converts simple initializations in aswitchinto initializations from a scalar array โจ. On by default at-O2and higher.-ftree-tail-mergeโ hunts for identical code sequences ๐. When it finds some, it replaces one with a jump to the other. This optimization is known as tail merging or cross jumping. Enabled by default at-O2and higher. You can cap the compile time in this pass using themax-tail-merge-comparisonsparameter and themax-tail-merge-iterationsparameter.-ftree-dceโ performs dead code elimination (DCE) on trees ๐. Enabled by default at-O1and higher.-ftree-builtin-call-dceโ performs conditional dead code elimination (DCE) for calls to built-in functions that may seterrnobut are otherwise free of side effects ๐. Enabled by default at-O2and higher โ as long as-Osisn't also specified.-ffinite-loopsโ assumes that a loop with an exit will eventually take that exit and not loop forever โพ๏ธ. This lets the compiler remove loops that otherwise have no side-effects, because it doesn't count eventual endless looping as a side-effect. This option is enabled by default at-O2for C++ with-std=c++11or higher.-ftree-dominator-optsโ performs a whole lil' spa day of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal ๐ง. It also does jump threading (to reduce jumps to jumps). Enabled by default at-O1and higher.-ftree-dseโ performs dead store elimination (DSE) on trees ๐๏ธ. A dead store is a store into a memory location that later gets overwritten by another store without any loads in between. In that case the earlier store can just be deleted. Enabled by default at-O1and higher.-ftree-chโ performs loop header copying on trees ๐. This is a good thing because it boosts the effectiveness of code motion optimizations. It also saves one jump. Enabled by default at-O1and higher. It is not enabled for-Os, since it usually makes code size bigger.-ftree-loop-optimizeโ performs loop optimizations on trees ๐. Enabled by default at-O1and higher.-ftree-loop-linear,-floop-strip-mine,-floop-blockโ these three all perform loop nest optimizations ๐ . Same as-floop-nest-optimize. To use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure.-fgraphite-identityโ enables the identity transformation for graphite โจ. For every SCoP we generate the polyhedral representation and transform it back to gimple. Using-fgraphite-identitywe can check the costs or benefits of theGIMPLE -> GRAPHITE -> GIMPLEtransformation. Some minimal optimizations also get done by the code generator isl, like index splitting and dead code elimination in loops.-floop-nest-optimizeโ enables the isl based loop nest optimizer ๐. It's a generic loop nest optimizer built on the Pluto optimization algorithms. It calculates a loop structure optimized for data-locality and parallelism. Heads up: this option is experimental ๐งช.-floop-parallelize-allโ uses the Graphite data dependence analysis to find loops that can be parallelized ๐ฅ. It parallelizes all the loops that can be analyzed to not contain loop carried dependences โ and it does not check whether it's actually profitable to parallelize them, so yeah, it just goes for it ๐ค.-ftree-coalesce-varsโ while transforming the program out of the SSA representation, this tries to reduce copying by coalescing versions of different user-defined variables, instead of just compiler temporaries ๐. Warning tho: this may severely limit your ability to debug an optimized program compiled with-fno-var-tracking-assignments๐ญ. In the negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise.-ftree-loop-if-convertโ attempts to transform conditional jumps in the innermost loops into branch-less equivalents ๐. The whole intent is to remove control-flow from the innermost loops so the vectorization pass can handle those loops better. Enabled by default if vectorization is enabled.-ftree-loop-distributionโ performs loop distribution โจ. This flag can improve cache performance on big loop bodies and let further loop optimizations โ like parallelization or vectorization โ happen. For example, the loop
DO I = 1, N
A(I) = B(I) + C
D(I) = E(I) * F
ENDDO
gets transformed to
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
This flag is enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile.
-ftree-loop-distribute-patternsโ performs loop distribution of patterns that can be code generated with calls to a library ๐. This flag is enabled by default at-O2and higher, and by-fprofile-useand-fauto-profile.
This pass distributes the initialization loops and generates a call to memset zero ๐ซถ. For example, the loop
DO I = 1, N
A(I) = 0
B(I) = A(I) + I
ENDDO
gets transformed to
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and the initialization loop becomes a call to memset zero. This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.
-floop-interchangeโ performs loop interchange outside of graphite ๐. This flag can improve cache performance on loop nests and let further loop optimizations, like vectorization, take place. For example, the loop
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
for (int k = 0; k < N; k++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
gets transformed to
for (int i = 0; i < N; i++)
for (int k = 0; k < N; k++)
for (int j = 0; j < N; j++)
c[i][j] = c[i][j] + a[i][k]*b[k][j];
This flag is enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile.
-floop-unroll-and-jamโ applies unroll and jam transformations on feasible loops ๐. In a loop nest this unrolls the outer loop by some factor and fuses the resulting multiple inner loops together. Enabled by default at-O3. It's also enabled by-fprofile-useand-fauto-profile.-ftree-loop-imโ performs loop invariant motion on trees โจ. This pass only moves invariants that are hard to handle at RTL level (function calls, operations that expand to nontrivial sequences of insns). With-funswitch-loopsit also moves operands of conditions that are invariant out of the loop, so we can use just trivial invariantness analysis in loop unswitching. The pass also includes store motion.-ftree-loop-ivcanonโ creates a canonical counter for the number of iterations in loops where figuring out the iteration count requires complicated analysis ๐ข. Later optimizations can then determine the number easily. Super useful especially in connection with unrolling.-ftree-scev-cpropโ performs final value replacement ๐ซ. If a variable is modified in a loop in such a way that its value when exiting the loop can be determined using only its initial value and the number of loop iterations, then replace uses of the final value by such a computation โ provided it's sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at-O1and higher.-fivoptsโ performs induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees ๐.-ftree-parallelize-loops=nโ parallelizes loops, i.e. splits their iteration space to run in n threads ๐งต. This is only possible for loops whose iterations are independent and can be arbitrarily reordered. The optimization is only profitable on multiprocessor machines, for loops that are CPU-intensive rather than constrained by, like, memory bandwidth. This option implies-pthread, and so it's only supported on targets that have support for-pthread.-ftree-ptaโ bestie we're doing function-local points-to analysis on trees ๐ณ it's on by default at-O1and up, except for-Og(she's built different, leave her alone).-ftree-sraโ scalar replacement of aggregates, and no I will not be taking questions ๐ what it does is swap structure references out for scalars so we don't commit structures to memory too early. default at-O1and higher, except for-Og.-fstore-mergingโ merging narrow stores to consecutive memory addresses ๐ซถ it takes contiguous stores of immediate values narrower than a word and merges them into fewer wider stores so the instruction count goes down. on by default at-O2and higher, and also at-Os.-ftree-terโ temporary expression replacement during theSSA->normalphase โจ single use/single def temporaries get replaced at their use location with their defining expression. the result is non-GIMPLE code, which sounds bad but actually gives the expanders way more complex trees to work on, which means better RTL generation. default at-O1and higher.-ftree-slsrโ straight-line strength reduction on trees ๐ธ it spots related expressions involving multiplications and replaces them with cheaper calculations when it can. default at-O1and higher.-ftree-vectorizeโ vectorization on trees ๐ฆ this flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif they're not explicitly specified.-ftree-loop-vectorizeโ loop vectorization on trees ๐ enabled by default at-O2, and also by-ftree-vectorize,-fprofile-use, and-fauto-profile.-ftree-slp-vectorizeโ basic block vectorization on trees โญ enabled by default at-O2, and also by-ftree-vectorize,-fprofile-use, and-fauto-profile.
-ftrivial-auto-var-init=choiceโ ok this one is a whole thing, bestie, let me lock in ๐ฅ it initializes automatic variables with either a pattern or with zeroes, which boosts security and predictability by preventing uninitialized memory disclosure and use. GCC still considers an automatic variable with no explicit initializer as uninitialized, and-Wuninitializedand-Wanalyzer-use-of-uninitialized-valuewill still report warning messages on those. with this option GCC will also initialize any padding of automatic variables that have structure or union types to zeroes. however โ the current implementation cannot initialize automatic variables declared between the controlling expression and the firstcaseof aswitchstatement. use-Wtrivial-auto-var-initto report all such cases.
the three values of choice are:
uninitializedโ doesn't initialize any automatic variables. this is C and C++'s default.patternโ initializes automatic variables with values that will likely transform logic bugs into crashes down the line, are easily recognized in a crash dump, and aren't values programmers can rely on for useful program semantics. the current value is a byte-repeatable pattern with byte"0xFE". the values used for pattern initialization might be changed in the future.zeroโ initializes automatic variables with zeroes.
the default is uninitialized.
you can control this behavior for a specific variable by using the variable attribute uninitialized.
-fvect-cost-model=modelโ changing up the cost model used for vectorization ๐ซ model should be one ofunlimited,dynamic,cheaporvery-cheap. with theunlimitedmodel the vectorized code-path is assumed to be profitable. withdynamic, a runtime check guards the vectorized code-path so it only turns on for iteration counts that will likely run faster than the original scalar loop. thecheapmodel disables vectorization of loops where doing so would be cost prohibitive โ for example because of required runtime checks for data dependence or alignment โ but otherwise it's equal todynamic. thevery-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code being vectorized. like, for example: if each iteration of a vectorized loop could only handle exactly four iterations of the scalar loop,very-cheapwould only allow vectorization if the scalar iteration count is known to be a multiple of four.
the default cost model depends on other optimization flags and is either dynamic or cheap.
-fsimd-cost-model=modelโ same energy but for vectorization of loops marked with the OpenMPsimddirective ๐ model should be one ofunlimited,dynamic,cheap. all values of model mean the same thing as described in-fvect-cost-model, and by default a cost model defined with-fvect-cost-modelis used.-ftree-vrpโ Value Range Propagation on trees ๐ similar to the constant propagation pass, but instead of values, ranges of values get propagated. this lets the optimizers remove unnecessary range checks like array bound checks and null pointer checks. default at-O2and higher. null pointer check elimination only happens if-fdelete-null-pointer-checksis enabled.-fsplit-pathsโ splits paths leading to loop backedges โ๏ธ this can improve dead code elimination and common subexpression elimination. default at-O3and above.-fsplit-ivs-in-unrollerโ expresses values of induction variables in later iterations of the unrolled loop using the value from the first iteration ๐ this breaks long dependency chains, which improves the efficiency of the scheduling passes.
a combination of -fweb and CSE is often enough to get the same effect. however, that's not reliable when the loop body is more complicated than a single basic block. it also doesn't work at all on some architectures because of restrictions in the CSE pass.
this optimization is enabled by default.
-fvariable-expansion-in-unrollerโ with this one the compiler makes multiple copies of some local variables when unrolling a loop, which can result in superior code ๐ this optimization is enabled by default for PowerPC targets, but disabled by default otherwise.-fpartial-inliningโ inline parts of functions ๐ซถ this option has any effect only when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions.
enabled at levels -O2, -O3, -Os.
-fpredictive-commoningโ predictive commoning optimization, i.e. reusing computations (especially memory loads and stores) performed in previous iterations of loops ๐ enabled at level-O3. it's also enabled by-fprofile-useand-fauto-profile.-fprefetch-loop-arraysโ if the target machine supports it, generate instructions to prefetch memory to improve the performance of loops that access large arrays ๐ heads up though: this option may generate better or worse code; results are highly dependent on the structure of loops within the source code. disabled at level-Os.-fno-printf-return-valueโ do not substitute constants for the known return value of formatted output functions such assprintf,snprintf,vsprintf, andvsnprintf(but notprintforfprintf) ๐ this transformation lets GCC optimize or even eliminate branches based on the known return value of these functions when called with arguments that are either constant, or whose values are known to be in a range that makes determining the exact return value possible. for example, when-fprintf-return-valueis in effect, both the branch and the body of theifstatement (but not the call tosnprint) can be optimized away wheniis a 32-bit or smaller integer because the return value is guaranteed to be at most 8.
char buf[9];
if (snprintf (buf, "%08x", i) >= sizeof buf)
...
the -fprintf-return-value option relies on other optimizations and yields best results with -O2 and above. it works in tandem with the -Wformat-overflow and -Wformat-truncation options. the -fprintf-return-value option is enabled by default.
-fno-peephole-fno-peephole2โ disable any machine-specific peephole optimizations ๐ the difference between-fno-peepholeand-fno-peephole2is in how they're implemented in the compiler; some targets use one, some use the other, and a few use both.
-fpeephole is enabled by default. -fpeephole2 enabled at levels -O2, -O3, -Os.
-fno-guess-branch-probabilityโ do not guess branch probabilities using heuristics ๐ซ GCC uses heuristics to guess branch probabilities when they aren't provided by profiling feedback (-fprofile-arcs). these heuristics are based on the control flow graph. if some branch probabilities are specified by__builtin_expect, then the heuristics are used to guess branch probabilities for the rest of the control flow graph, taking the__builtin_expectinfo into account. the interactions between the heuristics and__builtin_expectcan be complex, and in some cases it may be useful to disable the heuristics so that the effects of__builtin_expectare easier to understand.
it's also possible to specify expected probability of the expression with the __builtin_expect_with_probability built-in function.
the default is -fguess-branch-probability at levels -O, -O2, -O3, -Os.
-freorder-blocksโ reorder basic blocks in the compiled function to reduce the number of taken branches and improve code locality ๐ enabled at levels-O1,-O2,-O3,-Os.-freorder-blocks-algorithm=algorithmโ use the specified algorithm for basic block reordering ๐ง algorithm can besimple, which does not increase code size (except sometimes due to secondary effects like alignment), orstc, the "software trace cache" algorithm, which tries to put all often executed code together, minimizing the number of branches executed by making extra copies of code.
the default is simple at levels -O1, -Os, and stc at levels -O2, -O3.
-freorder-blocks-and-partitionโ okay so this one is not just reordering basic blocks inside your compiled function to cut down on taken branches (which it also does ๐ ), it ALSO partitions the hot ๐ฅ and cold ๐ฅถ basic blocks into separate sections of the assembly and.ofiles, so paging and cache locality get a glow-up. main character optimization fr.
It gets automatically turned off when:
- there's exception handling or unwind tables happening (on targets using
setjump/longjumpor a target specific scheme) - you're in linkonce sections
- you've got functions with a user-defined section attribute
- you're on any architecture that does not support named sections
When -fsplit-stack is used, this option is not enabled by default (gotta dodge those linker errors ๐), but you can enable it explicitly โ if you're using a working linker, bestie.
Enabled for x86 at levels -O2, -O3, -Os. slay.
-freorder-functionsโ this reorders functions in the object file to improve code locality. It does this with special subsections:.text.hotfor the most frequently executed functions and.text.unlikelyfor the ones that probably won't run. The reordering is done by the linker, so your object file format has to support named sections and the linker has to place them in a reasonable way. no cap.
Heads up tho: this option isn't effective unless you either provide profile feedback (peep -fprofile-arcs for the deets) or manually annotate functions with hot or cold attributes.
Enabled at levels -O2, -O3, -Os. โจ
-fstrict-aliasingโ lets the compiler assume the strictest aliasing rules applicable to the language you're compiling. For C (and C++), this activates optimizations based on the type of expressions. Specifically: an object of one type is assumed to never live at the same address as an object of a different type, unless the types are almost the same. For example, anunsigned intcan alias anint, but not avoid*or adouble. A character type may alias any other type.
Pay special attention to code like this, bestie:
union a_union {
int i;
double d;
};
int f() {
union a_union t;
t.d = 3.0;
return t.i;
}
The practice of reading from a different union member than the one most recently written to (this is called "type-punning") is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So the code above works as expected. ๐ซถ HOWEVER โ this code might not:
int f() {
union a_union t;
int* ip;
t.d = 3.0;
ip = &t.i;
return *ip;
}
Similarly, access by taking the address, casting the resulting pointer and dereferencing the result has undefined behavior, even if the cast uses a union type, e.g.:
int f() {
double d = 3.0;
return ((union a_union *) &d)->i;
}
bestie this is literally undefined behavior territory ๐ don't do it.
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-fipa-strict-aliasingโ controls whether the rules of-fstrict-aliasingget applied across function boundaries. Note that if multiple functions get inlined into a single function, the memory accesses are no longer considered to be crossing a function boundary. ๐ฆ
The -fipa-strict-aliasing option is enabled by default and is effective only in combination with -fstrict-aliasing.
-falign-functions-falign-functions=n-falign-functions=n:m-falign-functions=n:m:n2-falign-functions=n:m:n2:m2โ aligns the start of functions to the next power-of-two greater than or equal to n, skipping up to m-1 bytes. This ensures that at least the first m bytes of the function can be fetched by the CPU without crossing an n-byte alignment boundary. ๐
If m is not specified, it defaults to n.
Examples, so it actually clicks:
-falign-functions=32aligns functions to the next 32-byte boundary-falign-functions=24aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less-falign-functions=32:7aligns to the next 32-byte boundary only if this can be done by skipping 6 bytes or less
The second pair of n2:m2 values lets you specify a secondary alignment: -falign-functions=64:7:32:3 aligns to the next 64-byte boundary if this can be done by skipping 6 bytes or less, otherwise aligns to the next 32-byte boundary if this can be done by skipping 2 bytes or less. If m2 is not specified, it defaults to n2.
Some assemblers only support this flag when n is a power of two; in that case, it is rounded up.
-fno-align-functions and -falign-functions=1 are equivalent and mean that functions are not aligned.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-flimit-function-alignmentโ if this is enabled, the compiler tries to avoid unnecessarily overaligning functions. It attempts to instruct the assembler to align by the amount specified by-falign-functions, but not to skip more bytes than the size of the function. ๐-falign-labels-falign-labels=n-falign-labels=n:m-falign-labels=n:m:n2-falign-labels=n:m:n2:m2โ aligns all branch targets to a power-of-two boundary. โจ
Parameters of this option are analogous to the -falign-functions option. -fno-align-labels and -falign-labels=1 are equivalent and mean that labels are not aligned.
If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead.
If n is not specified or is zero, use a machine-dependent default which is very likely to be 1, meaning no alignment. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-falign-loops-falign-loops=n-falign-loops=n:m-falign-loops=n:m:n2-falign-loops=n:m:n2:m2โ aligns loops to a power-of-two boundary. If the loops are executed many times, this makes up for any execution of the dummy padding instructions. it's giving worth-it. ๐
If -falign-labels is greater than this value, then its value is used instead.
Parameters of this option are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent and mean that loops are not aligned. The maximum allowed n option value is 65536.
If n is not specified or is zero, use a machine-dependent default.
Enabled at levels -O2, -O3.
-falign-jumps-falign-jumps=n-falign-jumps=n:m-falign-jumps=n:m:n2-falign-jumps=n:m:n2:m2โ aligns branch targets to a power-of-two boundary, for branch targets where the targets can only be reached by jumping. In this case, no dummy operations need be executed. ๐ฅ
If -falign-labels is greater than this value, then its value is used instead.
Parameters of this option are analogous to the -falign-functions option. -fno-align-jumps and -falign-jumps=1 are equivalent and mean that loops are not aligned.
If n is not specified or is zero, use a machine-dependent default. The maximum allowed n option value is 65536.
Enabled at levels -O2, -O3.
-fno-allocation-dceโ do not remove unused C++ allocations in dead code elimination. periodt.-fallow-store-data-racesโ allows the compiler to perform optimizations that may introduce new data races on stores, without proving that the variable cannot be concurrently accessed by other threads. Does not affect optimization of local data. It is safe to use this option if it is known that global data will not be accessed by multiple threads.
Examples of optimizations enabled by -fallow-store-data-races include hoisting or if-conversions that may cause a value that was already in memory to be re-written with that same value. Such re-writing is safe in a single threaded context but may be unsafe in a multi-threaded context. Note that on some processors, if-conversions may be required in order to enable vectorization. ๐ง
Enabled at level -Ofast.
-funit-at-a-timeโ this option is left for compatibility reasons.-funit-at-a-timehas no effect, while-fno-unit-at-a-timeimplies-fno-toplevel-reorderand-fno-section-anchors.
Enabled by default. ๐
-fno-toplevel-reorderโ do not reorder top-level functions, variables, andasmstatements. Output them in the same order that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.
-ftoplevel-reorder is the default at -O1 and higher, and also at -O0 if -fsection-anchors is explicitly requested. Additionally -fno-toplevel-reorder implies -fno-section-anchors. ๐ธ
-fwebโ constructs webs as commonly used for register allocation purposes and assigns each web an individual pseudo register. This lets the register allocation pass operate on pseudos directly, but it also strengthens several other optimization passes, such as CSE, loop optimizer and trivial dead code remover. It can, however, make debugging impossible, since variables no longer stay in a "home register". ๐ญ
Enabled by default with -funroll-loops.
-fwhole-programโ assume that the current compilation unit represents the whole program being compiled. All public functions and variables โ with the exception ofmainand those merged by attributeexternally_visibleโ become static functions and in effect are optimized more aggressively by interprocedural optimizers. ๐ฅ
This option should not be used in combination with -flto. Instead relying on a linker plugin should provide safer and more precise information.
fr fr, don't pair this with -flto. just don't.
-flto[=n]โ this option runs the standard link-time optimizer. When invoked with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. When the object files are linked together, all the function bodies are read from these ELF sections and instantiated as if they had been part of the same translation unit. ๐
To use the link-time optimizer, bestie, you gotta pass -flto plus your optimization options at compile time and during the final link. The vibe is: compile every file in the same link with the same options, and also specify those options at link time. Like this:
gcc -c -O2 -flto foo.c
gcc -c -O2 -flto bar.c
gcc -o myprog -flto -O2 foo.o bar.o
The first two invocations save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation reads the GIMPLE bytecode from foo.o and bar.o, merges the two files into one internal image, and compiles the result as usual. Because both foo.o and bar.o get merged into a single image, all the interprocedural analyses and optimizations in GCC work across the two files as if they were one. So for example, the inliner can inline functions in bar.o into functions in foo.o and vice-versa. Iconic. ๐
Another (simpler) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
That generates bytecode for foo.c and bar.c, merges them into a single GIMPLE representation, and optimizes them as usual to produce myprog.
The important thing to keep in mind: to enable LTO you need to use the GCC driver to perform the link step. GCC automatically does LTO if any of the objects involved were compiled with -flto. You can always override the automatic decision by passing -fno-lto to the link command. No cap. โจ
To make whole program optimization effective, you have to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside the link-time optimized unit. When supported by the linker, the linker plugin (see -fuse-linker-plugin) passes information to the compiler about used and externally visible symbols. When the linker plugin is not available, -fwhole-program should be used to let the compiler make these assumptions, which leads to more aggressive optimization decisions.
When a file is compiled with -flto without -fuse-linker-plugin, the generated object file is larger than a regular object file because it contains GIMPLE bytecodes and the usual final code (see -ffat-lto-objects). This means object files with LTO information can be linked as normal object files; if -fno-lto is passed to the linker, no interprocedural optimizations are applied. Note that when -fno-fat-lto-objects is enabled the compile stage is faster, but you cannot perform a regular, non-LTO link on them.
When producing the final binary, GCC only applies link-time optimizations to those files that contain bytecode. So you can mix and match object files and libraries with GIMPLE bytecodes and final object code. GCC automatically selects which files to optimize in LTO mode and which files to link without further processing. Slay. ๐ฆ
Generally, options specified at link time override those specified at compile time, although in some cases GCC attempts to infer link-time options from the settings used to compile the input files.
If you do not specify an optimization level option -O at link time, then GCC uses the highest optimization level used when compiling the object files. Note that it is generally ineffective to specify an optimization level option only at link time and not at compile time, for two reasons. First, compiling without optimization suppresses compiler passes that gather information needed for effective optimization at link time. Second, some early optimization passes can be performed only at compile time and not at link time. Periodt. ๐
There are some code generation flags preserved by GCC when generating bytecodes, as they need to be used during the final link. Currently, the following options and their settings are taken from the first object file that explicitly specifies them: -fcommon, -fexceptions, -fnon-call-exceptions, -fgnu-tm and all the -m target flags.
The following options -fPIC, -fpic, -fpie and -fPIE are combined based on the following scheme:
-fPIC + -fpic = -fpic
-fPIC + -fno-pic = -fno-pic
-fpic/-fPIC + (no option) = (no option)
-fPIC + -fPIE = -fPIE
-fpic + -fPIE = -fpie
-fPIC/-fpic + -fpie = -fpie
Certain ABI-changing flags are required to match in all compilation units, and trying to override this at link time with a conflicting value is ignored. This includes options such as -freg-struct-return and -fpcc-struct-return.
Other options such as -ffp-contract, -fno-strict-overflow, -fwrapv, -fno-trapv or -fno-strict-aliasing are passed through to the link stage and merged conservatively for conflicting translation units. Specifically -fno-strict-overflow, -fwrapv and -fno-trapv take precedence; and for example -ffp-contract=off takes precedence over -ffp-contract=fast. You can override them at link time.
Diagnostic options such as -Wstringop-overflow are passed through to the link stage and their setting matches that of the compile-step at function granularity. Note that this matters only for diagnostics emitted during optimization. Note that code transforms such as inlining can lead to warnings being enabled or disabled for regions if code not consistent with the setting at compile time.
When you need to pass options to the assembler via -Wa or -Xassembler, make sure to either compile such translation units with -fno-lto or consistently use the same assembler options on all translation units. You can alternatively also specify assembler options at LTO link time.
To enable debug info generation you need to supply -g at compile time. If any of the input files at link time were built with debug info generation enabled, the link will enable debug info generation as well. Any elaborate debug info settings like the dwarf level -gdwarf-5 need to be explicitly repeated at the linker command line, and mixing different settings in different translation units is discouraged. Don't do that, bestie. ๐ญ
If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time. Similar diagnostics may be raised for other languages.
Another feature of LTO is that it is possible to apply interprocedural optimizations on files written in different languages:
gcc -c -flto foo.c
g++ -c -flto bar.cc
gfortran -c -flto baz.f90
g++ -o myprog -flto -O3 foo.o bar.o baz.o -lgfortran
Notice that the final link is done with g++ to get the C++ runtime libraries and -lgfortran is added to get the Fortran runtime libraries. In general, when mixing languages in LTO mode, you should use the same link command options as when mixing languages in a regular (non-LTO) compilation.
If object files containing GIMPLE bytecode are stored in a library archive, say libfoo.a, it is possible to extract and use them in an LTO link if you are using a linker with plugin support. To create static libraries suitable for LTO, use gcc-ar and gcc-ranlib instead of ar and ranlib; to show the symbols of object files with GIMPLE bytecode, use gcc-nm. Those commands require that ar, ranlib and nm have been compiled with plugin support. At link time, use the flag -fuse-linker-plugin to ensure that the library participates in the LTO optimization process:
gcc -o myprog -O2 -flto -fuse-linker-plugin a.o b.o -lfoo
With the linker plugin enabled, the linker extracts the needed GIMPLE files from libfoo.a and passes them on to the running GCC to make them part of the aggregated GIMPLE image to be optimized.
If you are not using a linker with plugin support and/or do not enable the linker plugin, then the objects inside libfoo.a are extracted and linked as usual, but they do not participate in the LTO optimization process. In order to make a static library suitable for both LTO optimization and usual linkage, compile its object files with -flto -ffat-lto-objects.
Link-time optimizations do not require the presence of the whole program to operate. If the program does not require any symbols to be exported, it is possible to combine -flto and -fwhole-program to allow the interprocedural optimizers to use more aggressive assumptions which may lead to improved optimization opportunities. Use of -fwhole-program is not needed when linker plugin is active (see -fuse-linker-plugin).
The current implementation of LTO makes no attempt to generate bytecode that is portable between different types of hosts. The bytecode files are versioned and there is a strict version check, so bytecode files generated in one version of GCC do not work with an older or newer version of GCC.
Link-time optimization does not work well with generation of debugging information on systems other than those using a combination of ELF and DWARF.
If you specify the optional n, the optimization and code generation done at link time is executed in parallel using n parallel jobs by utilizing an installed make program. The environment variable MAKE may be used to override the program used. Parallel vibes. ๐
You can also specify -flto=jobserver to use GNU make's job server mode to determine the number of parallel jobs. This is useful when the Makefile calling GCC is already executing in parallel. You must prepend a + to the command recipe in the parent Makefile for this to work. This option likely only works if MAKE is GNU make. Even without the option value, GCC tries to automatically detect a running GNU make's job server.
Use -flto=auto to use GNU make's job server, if available, or otherwise fall back to autodetection of the number of CPU threads present in your system. Auto-detect ate and left no crumbs. ๐
-flto-partition=algโ this is you picking the partitioning algorithm the link-time optimizer is gonna use, bestie. The value is either1to1(partitioning that mirrors the original source files, one-for-one, cute) orbalanced(chunking things into equally sized partitions whenever possible) ormax(making a brand new partition for every symbol where possible). If you passnoneas the algorithm it disables partitioning and streaming completely. Default value isbalanced. Now:1to1can be used as a workaround for various code ordering issues, butmaxpartitioning is intended for internal testing only โ do not make that your whole personality. The valueonespecifies that exactly one partition should be used, while the valuenonebypasses partitioning and executes the link-time optimization step directly from the WPA phase.-flto-compression-level=nโ sets the level of compression used for the intermediate language written to LTO object files. Only meaningful in conjunction with LTO mode (-flto), so don't bother otherwise. GCC currently supports two LTO compression algorithms. Forzstd, valid values are0(no compression) to19(maximum compression), whilezlibsupports values from0to9. Values outside that range get clamped to either the minimum or maximum of the supported values (so it's not gonna yell at you, it just picks a side ๐ ). If the option isn't given, a default balanced compression setting is used.-fuse-linker-pluginโ enables the use of a linker plugin during link-time optimization. This relies on plugin support in the linker, which is available ingoldor in GNUld2.21 or newer.
This option enables the extraction of object files with GIMPLE bytecode out of library archives. This improves the quality of optimization by exposing more code to the link-time optimizer. This information specifies what symbols can be accessed externally (by non-LTO object or during dynamic linking). Resulting code quality improvements on binaries (and shared libraries that use hidden visibility) are similar to -fwhole-program. See -flto for a description of the effect of this flag and how to use it.
This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer, or gold).
-ffat-lto-objectsโ fat LTO objects are object files that contain both the intermediate language and the object code. That makes them usable for both LTO linking and normal linking. This option is effective only when compiling with-fltoand is ignored at link time.
-fno-fat-lto-objects improves compilation time over plain LTO, but it requires the complete toolchain to be aware of LTO. It requires a linker with linker plugin support for basic functionality. Additionally, nm, ar and ranlib need to support linker plugins to allow a full-featured build environment (capable of building static libraries etc). GCC provides the gcc-ar, gcc-nm, gcc-ranlib wrappers to pass the right options to these tools. With non fat LTO, makefiles need to be modified to use them.
Note that modern binutils provide plugin auto-load mechanism. Installing the linker plugin into $libdir/bfd-plugins has the same effect as usage of the command wrappers (gcc-ar, gcc-nm and gcc-ranlib).
The default is -fno-fat-lto-objects on targets with linker plugin support.
-fcompare-elimโ after register allocation and post-register allocation instruction splitting, identify arithmetic instructions that compute processor flags similar to a comparison operation based on that arithmetic. If possible, eliminate the explicit comparison operation. ๐
This pass only applies to certain targets that cannot explicitly represent the comparison operation before register allocation is complete.
Enabled at levels -O1, -O2, -O3, -Os.
-fcprop-registersโ after register allocation and post-register allocation instruction splitting, perform a copy-propagation pass to try to reduce scheduling dependencies and occasionally eliminate the copy. Honestly? iconic behaviour.
Enabled at levels -O1, -O2, -O3, -Os.
-fprofile-correctionโ profiles collected using an instrumented binary for multi-threaded programs may be inconsistent due to missed counter updates. When this option is specified, GCC uses heuristics to correct or smooth out such inconsistencies. By default, GCC emits an error message when an inconsistent profile is detected. ๐ญ
This option is enabled by -fauto-profile.
-fprofile-partial-trainingโ so with-fprofile-use, all portions of programs not executed during the train run are optimized aggressively for size rather than speed. In some cases it's not practical to train all possible hot paths in the program. (For example, the program may contain functions specific for a given hardware, and training may not cover all hardware configurations the program is run on.) With-fprofile-partial-training, profile feedback will be ignored for all functions not executed during the train run, leading them to be optimized as if they were compiled without profile feedback. This leads to better performance when the train run is not representative, but also leads to significantly bigger code. Tradeoffs, bestie, we love to see them.-fprofile-use-fprofile-use=path
Enable profile feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-reorder-functions
Before you can use this option, you must first generate profiling information. No shortcuts, babe.
By default, GCC emits an error message if the feedback profiles do not match the source code. This error can be turned into a warning by using -Wno-error=coverage-mismatch. Note this may result in poorly optimized code. Additionally, by default, GCC also emits a warning message if the feedback profiles do not exist (see -Wmissing-profile).
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
-fauto-profile-fauto-profile=path
Enable sampling-based feedback-directed optimizations, and the following optimizations, many of which are generally profitable only with profile feedback available:
-fbranch-probabilities -fprofile-values -funroll-loops
-fpeel-loops -ftracer -fvpt -finline-functions -fipa-cp
-fipa-cp-clone -fipa-bit-cp -fpredictive-commoning -fsplit-loops
-funswitch-loops -fgcse-after-reload -ftree-loop-vectorize
-ftree-slp-vectorize -fvect-cost-model=dynamic
-ftree-loop-distribute-patterns -fprofile-correction
path is the name of a file containing AutoFDO profile information. If omitted, it defaults to fbdata.afdo in the current directory.
Producing an AutoFDO profile data file requires running your program with the perf utility on a supported GNU/Linux target system. For more information, see https://perf.wiki.kernel.org/.
E.g.
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then use the create_gcov tool to convert the raw profile data to a format that can be used by GCC. You must also supply the unstripped binary for your program to this tool. See https://github.com/google/autofdo.
E.g.
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled. All of them. Every single one. No sneaking in for free.
-ffloat-storeโ do not store floating-point variables in registers, and inhibit other options that might change whether a floating-point value is taken from a register or memory.
This option prevents undesirable excess precision on machines such as the 68000 where the floating registers (of the 68881) keep more precision than a double is supposed to have. Similarly for the x86 architecture. For most programs, the excess precision does only good, but a few programs rely on the precise definition of IEEE floating point. Use -ffloat-store for such programs, after modifying them to store all pertinent intermediate computations into variables.
-fexcess-precision=styleโ this option allows further control over excess precision on machines where floating-point operations occur in a format with more precision or range than the IEEE standard and interchange floating-point types. By default,-fexcess-precision=fastis in effect; this means that operations may be carried out in a wider precision than the types specified in the source if that would result in faster code, and it is unpredictable when rounding to the types specified in the source code takes place. When compiling C, if-fexcess-precision=standardis specified then excess precision follows the rules specified in ISO C99; in particular, both casts and assignments cause values to be rounded to their semantic types (whereas-ffloat-storeonly affects assignments). This option is enabled by default for C if a strict conformance option such as-std=c99is used.-ffast-mathenables-fexcess-precision=fastby default regardless of whether a strict conformance option is used.
-fexcess-precision=standardis not implemented for languages other than C. On the x86, it has no effect if-mfpmath=sseor-mfpmath=sse+387is specified; in the former case, IEEE semantics apply without excess precision, and in the latter, rounding is unpredictable.
-ffast-mathโ sets the options-fno-math-errno,-funsafe-math-optimizations,-ffinite-math-only,-fno-rounding-math,-fno-signaling-nans,-fcx-limited-rangeand-fexcess-precision=fast.
This option causes the preprocessor macro __FAST_MATH__ to be defined.
This option is not turned on by any-Ooption besides-Ofast, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. ๐ฅ Choose wisely.
-fno-math-errnoโ okay so bestie, this one says do not seterrnoafter calling math functions that run in a single instruction, likesqrt. If your program handles math errors via IEEE exceptions instead, you might want this for the speed while still keeping IEEE arithmetic compatibility. ๐โ๏ธ
No -O option turns this on, because it can literally produce incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. But it may give you faster code if you don't need those guarantees.
The default is -fmath-errno.
Fun fact: on Darwin systems, the math library never sets errno, so there's literally no reason for the compiler to consider that it might โ -fno-math-errno is the default there. ๐
-funsafe-math-optimizationsโ allow optimizations for floating-point arithmetic that (a) assume arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link time, it may include libraries or startup files that change the default FPU control word or other similar optimizations. ๐ณ
Not turned on by any -O option, because, again, incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. But it may yield faster code for programs that don't require those guarantees. It enables -fno-signed-zeros, -fno-trapping-math, -fassociative-math and -freciprocal-math.
The default is -fno-unsafe-math-optimizations.
-fassociative-mathโ allow re-association of operands in series of floating-point operations. This violates the ISO C and C++ language standard by possibly changing the computation result. โ ๏ธ NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow โ so it cannot be used on code that relies on rounding behavior like(x + 2**52) - 2**52. It may also reorder floating-point comparisons, so it may not be used when ordered comparisons are required. This option requires that both-fno-signed-zerosand-fno-trapping-mathbe in effect. Also, it doesn't make much sense with-frounding-math. For Fortran, the option is automatically enabled when both-fno-signed-zerosand-fno-trapping-mathare in effect.
The default is -fno-associative-math.
-freciprocal-mathโ allow the reciprocal of a value to be used instead of dividing by the value if this enables optimizations. For examplex / ycan be replaced withx * (1/y), which is useful if(1/y)is subject to common subexpression elimination. Heads up though: this loses precision and increases the number of flops operating on the value. ๐ซ
The default is -fno-reciprocal-math.
-ffinite-math-onlyโ allow optimizations for floating-point arithmetic that assume arguments and results are not NaNs or +-Infs. ๐
Not turned on by any -O option, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that don't require the guarantees of these specifications.
The default is -fno-finite-math-only.
-fno-signed-zerosโ allow optimizations for floating-point arithmetic that ignore the signedness of zero. IEEE arithmetic specifies the behavior of distinct+0.0and-0.0values, which then prohibits simplification of expressions such asx+0.0or0.0*x(even with-ffinite-math-only). This option implies that the sign of a zero result isn't significant.
The default is -fsigned-zeros.
-fno-trapping-mathโ compile code assuming that floating-point operations cannot generate user-visible traps. These traps include division by zero, overflow, underflow, inexact result and invalid operation. This option requires that-fno-signaling-nansbe in effect. Setting this option may allow faster code if you rely on "non-stop" IEEE arithmetic, for example.
This option should never be turned on by any -O option, since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. ๐
The default is -ftrapping-math.
-frounding-mathโ disable transformations and optimizations that assume default floating-point rounding behavior. That's round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. Specify this for programs that change the FP rounding mode dynamically, or that may be executed with a non-default rounding mode. This option disables constant folding of floating-point expressions at compile time (which may be affected by rounding mode) and arithmetic transformations that are unsafe in the presence of sign-dependent rounding modes.
The default is -fno-rounding-math.
This option is experimental and does not currently guarantee to disable all GCC optimizations that are affected by rounding mode. Future versions of GCC may provide finer control of this setting using C99's FENV_ACCESS pragma. This command-line option will be used to specify the default state for FENV_ACCESS.
-fsignaling-nansโ compile code assuming that IEEE signaling NaNs may generate user-visible traps during floating-point operations. Setting this option disables optimizations that may change the number of exceptions visible with signaling NaNs. This option implies-ftrapping-math.
This option causes the preprocessor macro __SUPPORT_SNAN__ to be defined. โจ
The default is -fno-signaling-nans.
This option is experimental and does not currently guarantee to disable all GCC optimizations that affect signaling NaN behavior.
-fno-fp-int-builtin-inexactโ do not allow the built-in functionsceil,floor,roundandtrunc, and theirfloatandlong doublevariants, to generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 allow these functions to raise theinexactexception, but ISO/IEC TS 18661-1:2014, the C bindings to IEEE 754-2008, as integrated into ISO C2X, does not allow these functions to do so.
The default is -ffp-int-builtin-inexact, allowing the exception to be raised, unless C2X or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect.
Even if -fno-fp-int-builtin-inexact is used, if the functions generate a call to a library function then the inexact exception may be raised if the library implementation does not follow TS 18661. ๐ญ
-fsingle-precision-constantโ treat floating-point constants as single precision instead of implicitly converting them to double-precision constants. โจ-fcx-limited-rangeโ when enabled, this option states that a range reduction step is not needed when performing complex division. Also, there is no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. The default is-fno-cx-limited-range, but it's enabled by-ffast-math.
This option controls the default setting of the ISO C99 CX_LIMITED_RANGE pragma. Nevertheless, the option applies to all languages.
-fcx-fortran-rulesโ complex multiplication and division follow Fortran rules. Range reduction is done as part of complex division, but there is no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case.
The default is -fno-cx-fortran-rules.
The following options control optimizations that may improve performance, but are not enabled by any -O options. This section includes experimental options that may produce broken code. ๐ Proceed with main character caution.
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilities, to improve optimizations based on the number of times each branch was taken. When a program compiled with-fprofile-arcsexits, it saves arc execution counts to a file calledsourcename.gcdafor each source file. The information in this data file is very dependent on the structure of the generated code, so you must use the same source code and the same optimization options for both compilations. See details about the file naming in-fprofile-arcs.
With -fbranch-probabilities, GCC puts a REG_BR_PROB note on each JUMP_INSN and CALL_INSN. These can be used to improve optimization. Currently, they are only used in one place: in reorg.cc, instead of guessing which path a branch is most likely to take, the REG_BR_PROB values are used to exactly determine which path is taken more often.
Enabled by -fprofile-use and -fauto-profile.
-fprofile-valuesโ if combined with-fprofile-arcs, it adds code so that some data about values of expressions in the program is gathered.
With -fbranch-probabilities, it reads back the data gathered from profiling values of expressions for usage in optimizations.
Enabled by -fprofile-generate, -fprofile-use, and -fauto-profile.
-fprofile-reorder-functionsโ function reordering based on profile instrumentation collects first time of execution of a function and orders these functions in ascending order.
Enabled with -fprofile-use.
-fvptโ if combined with-fprofile-arcs, this option instructs the compiler to add code to gather information about values of expressions.
With -fbranch-probabilities, it reads back the data gathered and actually performs the optimizations based on them. Currently the optimizations include specialization of division operations using the knowledge about the value of the denominator.
Enabled with -fprofile-use and -fauto-profile.
-frename-registersโ attempt to avoid false dependencies in scheduled code by making use of registers left over after register allocation. This optimization most benefits processors with lots of registers. Depending on the debug information format adopted by the target, however, it can make debugging impossible, since variables no longer stay in a "home register". ๐ซถ
Enabled by default with -funroll-loops.
-fschedule-fusionโ runs a target-dependent pass over the instruction stream that schedules instructions of the same type right next to each other, because the target machine can execute them more efficiently when they're adjacent in the instruction flow. โจ
Enabled at levels -O2, -O3, -Os. periodt.
-ftracerโ does tail duplication to enlarge superblock size. this transformation simplifies the control flow of the function, which lets other optimizations do a better job. it's giving "let the other girls eat" ๐
Enabled by -fprofile-use and -fauto-profile.
-funroll-loopsโ unrolls loops whose number of iterations can be determined at compile time or upon entry to the loop.-funroll-loopsimplies-frerun-cse-after-loop,-fweband-frename-registers. It also turns on complete loop peeling (i.e. complete removal of loops with a small constant number of iterations). This option makes code larger, and may or may not make it run faster. ๐ญ
Enabled by -fprofile-use and -fauto-profile.
-funroll-all-loopsโ unrolls all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. ๐-funroll-all-loopsimplies the same options as-funroll-loops.-fpeel-loopsโ peels loops for which there's enough info that they don't roll much (from profile feedback or static analysis). It also turns on complete loop peeling (i.e. complete removal of loops with small constant number of iterations).
Enabled by -O3, -fprofile-use, and -fauto-profile.
-fmove-loop-invariantsโ enables the loop invariant motion pass in the RTL loop optimizer. Enabled at level-O1and higher, except for-Og.-fmove-loop-storesโ enables the loop store motion pass in the GIMPLE loop optimizer. This moves invariant stores to after the end of the loop in exchange for carrying the stored value in a register across the iteration. Heads up bestie: for this option to have an effect,-ftree-loop-imhas to be enabled as well. Enabled at level-O1and higher, except for-Og.-fsplit-loopsโ splits a loop into two if it contains a condition that's always true for one side of the iteration space and false for the other. ๐ฆ
Enabled by -fprofile-use and -fauto-profile.
-funswitch-loopsโ moves branches with loop invariant conditions out of the loop, with duplicates of the loop on both branches (modified according to result of the condition).
Enabled by -fprofile-use and -fauto-profile.
-fversion-loops-for-stridesโ if a loop iterates over an array with a variable stride, it creates another version of the loop that assumes the stride is always one. For example:
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
becomes:
if (stride == 1)
for (int i = 0; i < n; ++i)
x[i] = ...;
else
for (int i = 0; i < n; ++i)
x[i * stride] = ...;
This is particularly useful for assumed-shape arrays in Fortran where (for example) it allows better vectorization assuming contiguous accesses. This flag is enabled by default at -O3. It is also enabled by -fprofile-use and -fauto-profile.
-ffunction-sections-fdata-sections
Place each function or data item into its own section in the output file if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file. ๐
Use these options on systems where the linker can perform optimizations to improve locality of reference in the instruction space. Most systems using the ELF object format have linkers with such optimizations. On AIX, the linker rearranges sections (CSECTs) based on the call graph. The performance impact varies.
Together with a linker garbage collection (linker --gc-sections option) these options may lead to smaller statically-linked executables (after stripping).
On ELF/DWARF systems these options do not degenerate the quality of the debug information. There could be issues with other object files/debug info formats.
Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker create larger object and executable files and are also slower. These options affect code generation. They prevent optimizations by the compiler and assembler using relative locations inside a translation unit since the locations are unknown until link time. An example of such an optimization is relaxing calls to short call instructions.
-fstdarg-optโ optimizes the prologue of variadic argument functions with respect to usage of those arguments.
NOTE: In Ubuntu 14.10 and later versions,-fstack-protector-strongis enabled by default for C, C++, ObjC, ObjC++, if none of-fno-stack-protector,-nostdlib, nor-ffreestandingare found.
-fsection-anchorsโ tries to reduce the number of symbolic address calculations by using shared "anchor" symbols to address nearby objects. This transformation can help to reduce the number of GOT entries and GOT accesses on some targets. ๐ธ
For example, the implementation of the following function foo:
static int a, b, c;
int foo (void) { return a + b + c; }
usually calculates the addresses of all three variables, but if you compile it with -fsection-anchors, it accesses the variables from a common anchor point instead. The effect is similar to the following pseudocode (which isn't valid C):
int foo (void)
{
register int *xr = &x;
return xr[&a - &x] + xr[&b - &x] + xr[&c - &x];
}
Not all targets support this option. ๐
-fzero-call-used-regs=choiceโ zeroes call-used registers at function return to increase program security by either mitigating Return-Oriented Programming (ROP) attacks or preventing information leakage through registers. ๐ฅ
The possible values of choice are the same as for the zero_call_used_regs attribute. The default is skip.
You can control this behavior for a specific function by using the function attribute zero_call_used_regs.
--param name=valueโ okay so in some places, GCC uses various constants to control the amount of optimization that's done. For example, GCC does not inline functions that contain more than a certain number of instructions. You can control some of these constants on the command line using the--paramoption. โจ
The names of specific parameters, and the meaning of the values, are tied to the internals of the compiler, and are subject to change without notice in future releases.
In order to get minimal, maximal and default value of a parameter, one can use --help=param -Q options.
In each case, the value is an integer. The following choices of name are recognized for all targets:
predictable-branch-outcomeโ when branch is predicted to be taken with probability lower than this threshold (in percent), then it is considered well predictable.max-rtl-if-conversion-insnsโ RTL if-conversion tries to remove conditional branches around a block and replace them with conditionally executed instructions. This parameter gives the maximum number of instructions in a block which should be considered for if-conversion. The compiler will also use other heuristics to decide whether if-conversion is likely to be profitable.max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove conditional branches around a block and replace them with conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that would be generated by if-conversion depending on whether the branch is statically determined to be predictable or not. The units for this parameter are the same as those for the GCC internal seq_cost metric. The compiler will try to provide a reasonable default for this parameter using theBRANCH_COSTtarget macro.max-crossjump-edgesโ the maximum number of incoming edges to consider for cross-jumping. The algorithm used by-fcrossjumpingis O(N^2) in the number of edges incoming to each block. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in executable size.min-crossjump-insnsโ the minimum number of instructions that must be matched at the end of two blocks before cross-jumping is performed on them. This value is ignored in the case where all instructions in the block being cross-jumped from are matched.max-grow-copy-bb-insnsโ the maximum code size expansion factor when copying basic blocks instead of jumping. The expansion is relative to a jump instruction.max-goto-duplication-insnsโ the maximum number of instructions to duplicate to a block that jumps to a computed goto. To avoid O(N^2) behavior in a number of passes, GCC factors computed gotos early in the compilation process, and unfactors them as late as possible. Only computed jumps at the end of a basic blocks with no more than max-goto-duplication-insns are unfactored.max-delay-slot-insn-searchโ the maximum number of instructions to consider when looking for an instruction to fill a delay slot. If more than this arbitrary number of instructions are searched, the time savings from filling the delay slot are minimal, so stop searching. Increasing values mean more aggressive optimization, making the compilation time increase with probably small improvement in execution time.max-delay-slot-live-searchโ when trying to fill delay slots, the maximum number of instructions to consider when searching for a block with valid live register information. Increasing this arbitrarily chosen value means more aggressive optimization, increasing the compilation time. This parameter should be removed when the delay slot code is rewritten to maintain the control-flow graph.
--param max-gcse-memoryโ the approximate max amount of memory, in kB, that can be allocated to do the global common subexpression elimination optimization. If it needs more memory than you specified, bestie, the optimization simply doesn't happen. No cap. ๐ซถ--param max-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is bigger than this value for any expression, then RTL PRE inserts or removes the expression, which means it leaves partially redundant computations sitting in the instruction stream. ๐--param max-pending-list-lengthโ the maximum number of pending dependencies that scheduling allows before it flushes the current state and starts all over. Large functions with only a few branches or calls can create absolutely massive lists that just needlessly eat memory and resources. ๐ญ--param max-modulo-backtrack-attemptsโ the maximum number of backtrack attempts the scheduler should make when it's modulo scheduling a loop. Bigger values can make compilation time grow exponentially, so likeโฆ choose wisely. ๐--param max-inline-functions-called-once-loop-depthโ the maximal loop depth of a call considered by the inline heuristics that try to inline every function called once. โจ--param max-inline-functions-called-once-insnsโ the maximal estimated size of functions produced while inlining functions called once. ๐--param max-inline-insns-singleโ several parameters control the tree inliner used in GCC, and this number sets the maximum number of instructions (counted in GCC's internal representation) in a single function that the tree inliner will even consider for inlining. This one only affects functions declaredinlineand methods implemented in a class declaration (C++). ๐--param max-inline-insns-autoโ when you use-finline-functions(which is included in-O3), a whole lot of functions that wouldn't otherwise be considered for inlining by the compiler get investigated. For those functions, a different โ and more restrictive โ limit compared to functions declared inline can be applied (--param max-inline-insns-auto). ๐ฆ--param max-inline-insns-smallโ this is the bound applied to calls that are considered relevant with-finline-small-functions. ๐ธ--param max-inline-insns-sizeโ this is the bound applied to calls that are optimized for size. A little bit of growth may be desirable to anticipate optimization opportunities exposed by inlining. โจ--param uninlined-function-insnsโ the number of instructions the inliner accounts for function overhead, like the function prologue and epilogue. ๐ง--param uninlined-function-timeโ the extra time the inliner accounts for function overhead, like the time needed to execute the function prologue and epilogue. โญ--param inline-heuristics-hint-percentโ the scale, in percents, applied toinline-insns-single,inline-insns-single-O2, andinline-insns-autowhen the inline heuristics hint that inlining is very profitable (like, it'll enable later optimizations). ๐ฅ--param uninlined-thunk-insns,--param uninlined-thunk-timeโ same as--param uninlined-function-insnsand--param uninlined-function-time, but applied to function thunks. ๐ซถ--param inline-min-speedupโ when the estimated performance improvement of caller + callee runtime exceeds this threshold (in percent), the function can be inlined regardless of the limit on--param max-inline-insns-singleand--param max-inline-insns-auto. ๐--param large-function-insnsโ the limit that specifies really large functions. For functions larger than this limit after inlining, inlining gets constrained by--param large-function-growth. This parameter is useful primarily to avoid extreme compilation time caused by the non-linear algorithms the back end uses. ๐ญ--param large-function-growthโ specifies the maximal growth of a large function caused by inlining, in percents. For example, a parameter value of100limits large function growth to 2.0 times the original size. ๐--param large-unit-insnsโ the limit that specifies a large translation unit. Growth caused by inlining of units larger than this limit is limited by--param inline-unit-growth. For small units this might be too tight. For example, consider a unit consisting of functionAthat is inline andBthat just callsAthree times. IfBis small relative toA, the growth of the unit is 300% and yet such inlining is very sane. For very large units consisting of small inlineable functions, though, the overall unit growth limit is needed to avoid an exponential explosion of code size. So for smaller units, the size is increased to--param large-unit-insnsbefore applying--param inline-unit-growth. ๐--param lazy-modulesโ the maximum number of concurrently open C++ module files when lazy loading. ๐--param inline-unit-growthโ specifies the maximal overall growth of the compilation unit caused by inlining. For example, a parameter value of20limits unit growth to 1.2 times the original size. Cold functions (either marked cold via an attribute or by profile feedback) are not accounted into the unit size. ๐ง--param ipa-cp-unit-growthโ specifies the maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, a parameter value of10limits unit growth to 1.1 times the original size. โจ--param ipa-cp-large-unit-insnsโ the size of translation unit that the IPA-CP pass considers large. ๐--param large-stack-frameโ the limit that specifies large stack frames. While inlining, the algorithm tries not to grow past this limit too much. ๐ธ--param large-stack-frame-growthโ specifies the maximal growth of large stack frames caused by inlining, in percents. For example, a parameter value of1000limits large stack frame growth to 11 times the original size. ๐--param max-inline-insns-recursive,--param max-inline-insns-recursive-autoโ specify the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by performing recursive inlining.
--param max-inline-insns-recursive applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead. ๐ฆ
--param max-inline-recursive-depth,--param max-inline-recursive-depth-autoโ specify the maximum recursion depth used for recursive inlining.
--param max-inline-recursive-depth applies to functions declared inline. For functions not declared inline, recursive inlining happens only when -finline-functions (included in -O3) is enabled; --param max-inline-recursive-depth-auto applies instead. ๐
--param min-inline-recursive-probabilityโ recursive inlining is only profitable for functions that have deep recursion on average, and it can actually hurt functions that have little recursion depth, by increasing the prologue size or the complexity of the function body for other optimizers. ๐ฌ
When profile feedback is available (see -fprofile-generate), the actual recursion depth can be guessed from the probability that the function recurses via a given call expression. This parameter limits inlining only to call expressions whose probability exceeds the given threshold (in percents). ๐
--param early-inlining-insnsโ specify the growth that the early inliner can make. In effect, it increases the amount of inlining for code that has a large abstraction penalty. ๐--param max-early-inliner-iterationsโ the limit on iterations of the early inliner. This basically bounds the number of nested indirect calls the early inliner can resolve. Deeper chains are still handled by late inlining. ๐--param comdat-sharing-probabilityโ the probability (in percent) that C++ inline functions with comdat visibility are shared across multiple compilation units. ๐ซถ--param modref-max-bases,--param modref-max-refs,--param modref-max-accessesโ specify the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. ๐--param modref-max-testsโ specifies the maximal number of tests the alias oracle can perform to disambiguate memory locations using the mod/ref information. This parameter ought to be bigger than--param modref-max-basesand--param modref-max-refs. โญ--param modref-max-depthโ specifies the maximum depth of the DFS walk used by modref escape analysis. Setting it to0disables the analysis completely. ๐--param modref-max-escape-pointsโ specifies the maximum number of escape points tracked by modref per SSA-name. ๐ง--param modref-max-adjustmentsโ specifies the maximum number the access range is enlarged during modref dataflow analysis. ๐ธ--param profile-func-internal-idโ a parameter to control whether to use the function internal id in profile database lookup. If the value is0, the compiler uses an id that is based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. ๐ฅ--param min-vect-loop-boundโ the minimum number of iterations under which loops are not vectorized when-ftree-vectorizeis used. The number of iterations after vectorization needs to be greater than the value specified by this option to allow vectorization. ๐--param gcse-cost-distance-ratioโ the scaling factor in the calculation of the maximum distance an expression can be moved by GCSE optimizations. This is currently supported only in the code hoisting pass. The bigger the ratio, the more aggressive code hoisting is with simple expressions โ i.e., the expressions that have a cost less thangcse-unrestricted-cost. Specifying0disables hoisting of simple expressions. ๐gcse-unrestricted-costโ the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations stop constraining how far an expression can travel. This is currently supported only in the code hoisting pass, fyi. The lesser the cost, the more aggressive code hoisting gets. Specify0and literally every expression gets to travel unrestricted distances. no cap ๐max-hoist-depthโ how deep the search in the dominator tree goes looking for expressions to hoist. It exists to dodge quadratic behavior in the hoisting algorithm (because quadratic is giving ๐). A value of0does not limit the search, but heads up: it may slow down compilation of huge functions.max-tail-merge-comparisonsโ the max amount of similar bbs to compare a bb with. Again, this is here to avoid quadratic behavior in tree tail merging.max-tail-merge-iterationsโ the max amount of iterations of the pass over the function. Used to limit compilation time in tree tail merging.store-merging-allow-unalignedโ lets the store merging pass introduce unaligned stores, but only if it's legal to do so. โจmax-stores-to-mergeโ the max number of stores the store merging pass will attempt to merge into wider stores.max-store-chains-to-trackโ the max number of store chains to track at the same time while trying to merge them into wider stores in the store merging pass.max-stores-to-trackโ the max number of stores to track at the same time while attempting to merge them into wider stores in the store merging pass.max-unrolled-insnsโ the max number of instructions a loop may have and still get unrolled. And if a loop does get unrolled, this parameter also decides how many times the loop code is unrolled.max-average-unrolled-insnsโ same energy as above, but the instruction count is biased by the probabilities of their execution. It's the max number of instructions a loop may have to be unrolled, and if it's unrolled, this also determines how many times the loop code is unrolled. ๐max-unroll-timesโ the max number of unrollings of a single loop.max-peeled-insnsโ the max number of instructions a loop may have to be peeled. If a loop is peeled, this parameter also determines how many times the loop code is peeled.max-peel-timesโ the max number of peelings of a single loop.max-peel-branchesโ the max number of branches on the hot path through the peeled sequence.max-completely-peeled-insnsโ the max number of insns of a completely peeled loop.max-completely-peel-timesโ the max number of iterations of a loop for it to be suitable for complete peeling.max-completely-peel-loop-nest-depthโ the max depth of a loop nest that's suitable for complete peeling.max-unswitch-insnsโ the max number of insns of an unswitched loop.max-unswitch-levelโ the max number of branches unswitched in a single loop.lim-expensiveโ the minimum cost of an expensive expression in the loop invariant motion.min-loop-cond-split-probโ when FDO profile information is available, this specifies the minimum threshold for the probability of a semi-invariant condition statement to trigger a loop split. ๐iv-consider-all-candidates-boundโ the bound on the number of candidates for induction variables. Below this number, all candidates get considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered, so we don't hit quadratic time complexity.iv-max-considered-usesโ the induction variable optimizations give up on loops that contain more induction variable uses than this.iv-always-prune-cand-set-boundโ if the number of candidates in the set is smaller than this value, always try to remove unnecessary ivs from the set when adding a new one.avg-loop-niterโ average number of iterations of a loop.dse-max-object-sizeโ max size (in bytes) of objects tracked bytewise by dead store elimination. Heads up: larger values may result in larger compilation times.dse-max-alias-queries-per-storeโ max number of queries into the alias oracle per store. Larger values result in larger compilation times, and may result in more removed dead stores.scev-max-expr-sizeโ bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer down, bestie.scev-max-expr-complexityโ bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer.max-tree-if-conversion-phi-argsโ max number of arguments in a PHI that TREE if conversion supports โ unless the loop is marked with thesimdpragma, in which case this doesn't apply.vect-max-version-for-alignment-checksโ the max number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer.vect-max-version-for-alias-checksโ the max number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer.vect-max-peeling-for-alignmentโ the max number of loop peels to enhance access alignment for the vectorizer. A value of-1means no limit. ๐max-iterations-to-trackโ the max number of iterations of a loop that the brute-force algorithm for analyzing the number of iterations of the loop tries to evaluate.hot-bb-count-fractionโ the denominator n of the fraction1/nof the maximal execution count of a basic block in the entire program that a basic block needs to at least have to be considered hot. The default is10000, which means a basic block is hot if its execution count is greater than1/10000of the maximal execution count.0means it's never considered hot. Used in non-LTO mode. ๐ฅhot-bb-count-ws-permilleโ the number of most executed permilles, ranging from0to1000, of the profiled execution of the entire program that the execution count of a basic block must be part of to be considered hot. The default is990, which means a basic block is hot if its execution count contributes to the upper 990 permilles โ or 99.0% โ of the profiled execution of the entire program.0means it's never considered hot. Used in LTO mode.hot-bb-frequency-fractionโ the denominator n of the fraction1/nof the execution frequency of the entry block of a function that a basic block of this function needs to at least have to be considered hot. The default is1000, which means a basic block is hot in a function if it's executed more frequently than1/1000of the frequency of the entry block of the function.0means it's never considered hot.unlikely-bb-count-fractionโ the denominator n of the fraction1/nof the number of profiled runs of the entire program below which the execution count of a basic block must be in order for that basic block to be considered unlikely executed. The default is20, which means a basic block is considered unlikely executed if it's executed in fewer than1/20, or 5%, of the runs of the program.0means it's always considered unlikely executed.max-predicted-iterationsโ the max number of loop iterations we predict statically. This is useful when a function contains a single loop with a known bound and another loop with an unknown bound: the known number of iterations gets predicted correctly, while the unknown number of iterations averages to roughly10. Which means the loop without bounds appears artificially cold next to the other one. ๐ญbuiltin-expect-probabilityโ controls the probability of the expression having the specified value. This parameter takes a percentage (i.e.0 ... 100) as input.builtin-string-cmp-inline-lengthโ the max length of a constant string for a builtin string cmp call to be eligible for inlining.align-thresholdโ selects the fraction of the maximal frequency of executions of a basic block in a function to align the basic block.align-loop-iterationsโ a loop expected to iterate at least the selected number of iterations gets aligned.tracer-dynamic-coverage,tracer-dynamic-coverage-feedbackโ this value limits superblock formation once the given percentage of executed instructions is covered. It exists to limit unnecessary code size expansion.
The tracer-dynamic-coverage-feedback parameter is used only when profile feedback is available. The real profiles (as opposed to statically estimated ones) are much less balanced, which allows the threshold to be a larger value.
tracer-max-code-growthโ stop tail duplication once code growth has reached the given percentage. This is a rather artificial limit, since most of the duplicates get eliminated later in cross jumping โ so it may be set to much higher values than the code growth you actually want.tracer-min-branch-ratioโ stop reverse growth when the reverse probability of the best edge is less than this threshold (in percent).tracer-min-branch-probability,tracer-min-branch-probability-feedbackโ stop forward growth if the best edge has a probability lower than this threshold.
Just like with tracer-dynamic-coverage, two parameters are provided: tracer-min-branch-probability-feedback is used for compilation with profile feedback, and tracer-min-branch-probability for compilation without. The value for compilation with profile feedback needs to be more conservative (higher) in order to make the tracer effective. โจ
stack-clash-protection-guard-sizeโ sets how big the stack guard your OS gives you is, expressed as 2 raised to num bytes. Bigger values might mean fewer explicit probes, but bestie, listen: if you set this larger than the guard your operating system actually provides, your code is left wide open to stack clash style attacks. So don't do that. ๐ฉstack-clash-protection-probe-intervalโ stack clash protection works by probing the stack space as it gets allocated, and this param is the max distance between those probes, as 2 raised to num bytes. Higher values = possibly fewer explicit probes, but again, if it's bigger than the OS-provided guard, you're vulnerable to stack clash style attacks. Same energy as above, same warning. ๐max-cse-path-lengthโ the max number of basic blocks on a path that CSE will even look at.max-cse-insnsโ the max number of instructions CSE chews through before it flushes.ggc-min-expandโ okay so GCC runs its own little garbage collector to manage its own memory allocation, and this param is the minimum percentage its heap is allowed to expand between collections. Tuning it might speed up compilation; it does not touch code generation at all.
The default is 30% + 70% * (RAM/1GB), with an upper bound of 100% when RAM >= 1GB. If getrlimit is available, "RAM" means the smallest of actual RAM and RLIMIT_DATA or RLIMIT_AS. If GCC can't figure out the RAM on some platform, it just uses the lower bound of 30%. And if you set this param and ggc-min-heapsize to zero, a full collection happens at every single opportunity โ extremely slow, but genuinely useful for debugging. ๐
ggc-min-heapsizeโ the minimum size of the garbage collector's heap before it even bothers collecting. The first collection happens after the heap expands byggc-min-expand% beyondggc-min-heapsize. Again, tuning this may improve compilation speed and has no effect on code generation.
The default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to keep RLIMIT_DATA or RLIMIT_AS from being exceeded โ but with a lower bound of 4096 (four megabytes) and an upper bound of 131072 (128 megabytes). If GCC can't calculate RAM on a given platform, the lower bound is used. Set this very large and you effectively disable garbage collection. Set this and ggc-min-expand to zero and a full collection occurs at every opportunity. โจ
max-reload-search-insnsโ the max number of instructions reload should look backward for an equivalent register. Bigger values mean more aggressive optimization, so compile time goes up with probably slightly better performance. trade-off queen ๐max-cselib-memory-locationsโ the max number of memory locations cselib should take into account. Bigger = more aggressive optimization, longer compile time, probably slightly better performance.max-sched-ready-insnsโ the max number of instructions ready to be issued that the scheduler should consider at any given time during the first scheduling pass. Bigger values mean more thorough searches, longer compile time, and probably very little benefit. ๐max-sched-region-blocksโ the max number of blocks in a region considered for interblock scheduling.max-pipeline-region-blocksโ the max number of blocks in a region considered for pipelining in the selective scheduler.max-sched-region-insnsโ the max number of insns in a region considered for interblock scheduling.max-pipeline-region-insnsโ the max number of insns in a region considered for pipelining in the selective scheduler.min-spec-probโ the minimum probability (in percents) of reaching a source block for interblock speculative scheduling.max-sched-extend-regions-itersโ the max number of iterations through CFG to extend regions. A value of0disables region extensions. periodt.max-sched-insn-conflict-delayโ the max conflict delay for an insn to be considered for speculative motion.sched-spec-prob-cutoffโ the minimal probability of speculation success (in percents), so that speculative insns get scheduled.sched-state-edge-prob-cutoffโ the minimum probability an edge has to have for the scheduler to save its state across it.sched-mem-true-dep-costโ minimal distance (in CPU cycles) between a store and a load targeting the same memory locations.selsched-max-lookaheadโ the max size of the lookahead window of selective scheduling. Basically it's the depth of search for available instructions. ๐selsched-max-sched-timesโ the max number of times an instruction gets scheduled during selective scheduling. This is the limit on how many iterations the instruction may be pipelined through.selsched-insns-to-renameโ the max number of best instructions in the ready list that get considered for renaming in the selective scheduler.sms-min-scโ the minimum value of stage count that the swing modulo scheduler generates.max-last-value-rtlโ the max size, measured as number of RTLs, that can be recorded in an expression in combiner for a pseudo register as the last known value of that register.max-combine-insnsโ the max number of instructions the RTL combiner tries to combine.integer-share-limitโ small integer constants can share a data structure, which cuts the compiler's memory usage and speeds it up. This sets the max value of a shared integer constant.ssp-buffer-sizeโ the minimum size of buffers (i.e. arrays) that receive stack smashing protection when-fstack-protectoris used.
Fun history moment: this default before Ubuntu 10.10 was"8". Currently it is"4", to increase the number of functions protected by the stack protector. ๐ก๏ธ
min-size-for-stack-sharingโ the minimum size of variables that take part in stack slot sharing when not optimizing.max-jump-thread-duplication-stmtsโ the max number of statements allowed in a block that needs to be duplicated when threading jumps.max-fields-for-field-sensitiveโ the max number of fields in a structure treated in a field sensitive manner during pointer analysis.prefetch-latencyโ an estimate of the average number of instructions executed before a prefetch finishes. The distance prefetched ahead is proportional to this constant. Increasing this number may also lead to fewer streams being prefetched (seesimultaneous-prefetches). ๐simultaneous-prefetchesโ the max number of prefetches that can run at the same time.l1-cache-line-sizeโ the size of a cache line in the L1 data cache, in bytes.l1-cache-sizeโ the size of the L1 data cache, in kilobytes.l2-cache-sizeโ the size of the L2 data cache, in kilobytes.prefetch-dynamic-stridesโ whether the loop array prefetch pass should issue software prefetch hints for strides that are non-constant. In some cases this may be beneficial, though the fact that the stride is non-constant may make it hard to predict when there's a clear benefit to issuing these hints.
Set to 1 if the prefetch hints should be issued for non-constant strides. Set to 0 if prefetch hints should be issued only for strides that are known to be constant and below prefetch-minimum-stride.
prefetch-minimum-strideโ minimum constant stride, in bytes, to start using prefetch hints for. If the stride is less than this threshold, prefetch hints will not be issued.
This setting is useful for processors that have hardware prefetchers, because there can be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a maximum stride they can handle, that value should be used here to improve the use of software prefetchers.
A value of -1 means we don't have a threshold, and therefore prefetch hints can be issued for any constant stride.
This setting is only useful for strides that are known and constant. ๐
destructive-interference-size,constructive-interference-sizeโ the values for the C++17 variablesstd::hardware_destructive_interference_sizeandstd::hardware_constructive_interference_size. The destructive interference size is the minimum recommended offset between two independent concurrently-accessed objects; the constructive interference size is the maximum recommended size of contiguous memory accessed together. Typically both will be the size of an L1 cache line for the target, in bytes. For a generic target covering a range of L1 cache line sizes, typically the constructive interference size will be the small end of the range and the destructive size will be the large end.
The destructive interference size is intended to be used for layout, and thus has ABI impact. The default value is not expected to be stable, and on some targets it varies with -mtune, so using this variable in a context where ABI stability matters โ like the public interface of a library โ is strongly discouraged. If it is used in that context, users can stabilize the value using this option.
The constructive interference size is less sensitive, since it's typically only used in a static_assert to make sure a type fits within a cache line.
See also -Winterference-size. ๐ฆ
loop-interchange-max-num-stmtsโ the max number of stmts in a loop to be interchanged.loop-interchange-stride-ratioโ the minimum ratio between the stride of two loops before loop interchange is actually worth doing. Under that ratio? Not profitable, bestie, we're not doing it. ๐min-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches that lets prefetching turn on inside a loop. Basically: enough prefetches to be worth it or we're not bothering. โจprefetch-min-insn-to-mem-ratioโ the minimum ratio between the number of instructions and the number of memory references that enables prefetching in a loop. Same energy, different denominator, no cap. ๐ซถuse-canonical-typesโ whether the compiler uses the "canonical" type system. This one should always be 1, because that's the more efficient internal mechanism for comparing types in C++ and Objective-C++. But listen: if bugs in the canonical type system are causing compilation failures, set this to 0 to disable canonical types. Emergency escape hatch, iykyk. ๐จswitch-conversion-max-branch-ratioโ switch initialization conversion refuses to create arrays bigger thanswitch-conversion-max-branch-ratiotimes the number of branches in the switch. There's a line and this is it. ๐max-partial-antic-lengthโ maximum length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at-O3and above. Here's the tea: for some sorts of source code, the enhanced partial redundancy elimination optimization can run away, consuming all of the memory available on the host machine. This parameter caps the length of the sets being computed, which stops the runaway behavior. Setting this to 0 allows an unlimited set length. Unlimited! Greedy! ๐rpo-vn-max-loop-depthโ maximum loop depth that gets value-numbered optimistically. When the limit hits, the innermostrpo-vn-max-loop-depthloops and the outermost loop in the loop nest get value-numbered optimistically, and the remaining ones don't. Partial treatment, iconic behavior. ๐sccvn-max-alias-queries-per-accessโ the maximum number of alias-oracle queries performed when hunting for redundancies in loads and stores. Hit the limit and the search aborts and that load or store just isn't considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry. Math is math. ๐งฎira-max-loops-numโ IRA uses regional register allocation by default. If a function has more loops than the number given here, only at most that many of the most frequently-executed loops form regions for regional register allocation. The popular loops get picked, sorry to the rest. ๐ira-max-conflict-table-sizeโ ok so IRA uses a sophisticated algorithm to compress the conflict table, but the table can still need excessive amounts of memory for huge functions. If a function's conflict table could be bigger than the size in MB given by this parameter, the register allocator switches to a faster, simpler, lower-quality algorithm that doesn't require building a pseudo-register conflict table. Trade-off city. โ๏ธira-loop-reserved-regsโ IRA can be used to evaluate more accurate register pressure in loops so it can decide whether to move loop invariants (see-O3). The number of available registers reserved for some other purposes is given by this parameter. The default is the best value found from numerous experiments. Science! ๐ฌira-consider-dup-in-all-altsโ makes IRA consider a matching constraint (duplicated operand number) heavily in all available alternatives for the preferred register class. Set it to zero and IRA only respects the matching constraint when it's in the only available alternative with an appropriate register class. Otherwise, IRA checks all available alternatives for the preferred register class even if it already found some choice with an appropriate register class, and respects the found qualified matching constraint. Thorough queen. ๐lra-inheritance-ebb-probability-cutoffโ LRA tries to reuse values reloaded in registers in subsequent insns, and this optimization is called inheritance. EBB is used as the region for doing it. This parameter defines a minimal fall-through edge probability, in percentage, used to add a BB to the inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64. Proven in the field, fr fr. ๐loop-invariant-max-bbs-in-loopโ loop invariant motion can be very expensive, both in compilation time and in the amount of compile-time memory needed, when loops are very large. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them at all. Cut off. โ๏ธloop-max-datarefs-for-datadepsโ building data dependencies is expensive for very large loops, so this parameter limits the number of data references in loops that get considered for data dependence analysis. These large loops are not handled by the optimizations that use loop data dependencies. (Yes, the original says "are no handled" โ we love a typo, iconic.) ๐max-vartrack-sizeโ sets a maximum number of hash table slots to use during variable tracking dataflow analysis of any function. If this limit is exceeded with variable tracking at assignments enabled, analysis for that function is retried without it, after removing all debug insns from the function. If the limit is exceeded even without debug insns, var tracking analysis is completely disabled for that function. Setting this parameter to zero makes it unlimited. Zero = no rules. ๐max-vartrack-expr-depthโ sets a maximum number of recursion levels when trying to map variable names or debug temporaries to value expressions. This trades compilation time for more complete debug information. Set it too low and value expressions that are available and could be represented in debug info may end up unused; set it higher and the compiler may find more complex debug expressions, but compile time and memory use may grow. Balance, bestie. โ๏ธmax-debug-marker-countโ sets a threshold on the number of debug markers (e.g. begin stmt markers) to avoid complexity explosion at inlining or expanding to RTL. If a function has more such gimple stmts than the set limit, those stmts get dropped from the inlined copy of the function, and from its RTL expansion. Bye bye markers. ๐min-nondebug-insn-uidโ use uids starting at this parameter for nondebug insns. The range below the parameter is reserved exclusively for debug insns created by-fvar-tracking-assignments, but debug insns may get (non-overlapping) uids above it if the reserved range is exhausted. Overbooked, honestly. ๐๏ธipa-sra-ptr-growth-factorโ IPA-SRA replaces a pointer to an aggregate with one or more new parameters only when their cumulative size is less than or equal toipa-sra-ptr-growth-factortimes the size of the original pointer parameter. Size matters, lowkey. ๐ipa-sra-max-replacementsโ maximum pieces of an aggregate that IPA-SRA tracks. As a consequence, it's also the maximum number of replacements of a formal parameter. Two jobs, one number. ๐sra-max-scalarization-size-Ospeedsra-max-scalarization-size-Osizeโ the two Scalar Reduction of Aggregates passes (SRA and IPA-SRA) aim to replace scalar parts of aggregates with uses of independent scalar variables. These parameters control the maximum size, in storage units, of an aggregate considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or for size (sra-max-scalarization-size-Osize), respectively. Pick your fighter. ๐ฅsra-max-propagationsโ the maximum number of artificial accesses that Scalar Replacement of Aggregates (SRA) tracks, per one local variable, so that copy propagation is easier. Track queen. ๐tm-max-aggregate-sizeโ when making copies of thread-local variables in a transaction, this parameter specifies the size in bytes after which variables are saved with the logging functions instead of save/restore code sequence pairs. This option only applies when using-fgnu-tm. Only there! ๐งgraphite-max-nb-scop-paramsโ to avoid exponential effects in the Graphite loop transforms, the number of parameters in a Static Control Part (SCoP) is bounded. A value of zero can be used to lift the bound. And for the record: a variable whose value is unknown at compilation time and defined outside a SCoP is a parameter of the SCoP. ๐loop-block-tile-sizeโ loop blocking or strip mining transforms, enabled with-floop-blockor-floop-strip-mine, strip mine each loop in the loop nest by a given number of iterations. The strip length can be changed using theloop-block-tile-sizeparameter. Slice it up. ๐ฐipa-jump-function-lookupsโ specifies the number of statements visited during jump function offset discovery. Count 'em. ๐ขipa-cp-value-list-sizeโ IPA-CP tries to track all possible values and types passed to a function's parameter so it can propagate them and do devirtualization.ipa-cp-value-list-sizeis the maximum number of values and types it stores per one formal parameter of a function. ๐๏ธipa-cp-eval-thresholdโ IPA-CP calculates its own score of cloning profitability heuristics, and only performs cloning opportunities whose scores exceedipa-cp-eval-threshold. Score above the bar or it's not happening. ๐ipa-cp-max-recursive-depthโ maximum depth of recursive cloning for a self-recursive function. Go deep but not too deep. ๐ipa-cp-min-recursive-probabilityโ recursive cloning only happens when the probability of the call being executed exceeds this parameter. Otherwise? No clone for you. ๐ญipa-cp-profile-count-baseโ when using the-fprofile-useoption, IPA-CP considers the measured execution count of a call graph edge at this percentage position in their histogram as the basis for its heuristics calculation. Statistics girlie. ๐ipa-cp-recursive-freq-factorโ the number of times interprocedural copy propagation expects recursive functions to call themselves. Expectation setting. ๐ipa-cp-recursion-penaltyโ percentage penalty recursive functions receive when they're evaluated for cloning. Recursion tax, and it is not cheap. ๐ธipa-cp-single-call-penaltyโ the percentage penalty that functions containing a single call to another function get hit with when they're being evaluated for cloning. basically a lil tax for being a one-call wonder ๐ipa-max-agg-itemsโ IPA-CP can also propagate a bunch of scalar values that got passed in an aggregate, and this one caps the max number of those values per single parameter. one parameter, that many items, no more bestie.ipa-cp-loop-hint-bonusโ when IPA-CP figures out that a cloning candidate would make the number of iterations of a loop known, it adds a bonus ofipa-cp-loop-hint-bonusto the candidate's profitability score. it's giving "knowing the loop count = free clout" โจipa-max-loop-predicatesโ the maximum number of different predicates IPA will use to describe when loops in a function have known properties. keep it under this many, okay?ipa-max-aa-stepsโ during its analysis of function bodies, IPA-CP employs alias analysis to track values pointed to by function parameters. but it refuses to spend all day analyzing huge functions, so after examiningipa-max-aa-stepsstatements that modify memory, it gives up and considers all memory clobbered. it's literally the "i've seen enough" meme ๐ญipa-max-switch-predicate-boundsโ the maximal number of boundary endpoints of case ranges of a switch statement. for a switch that exceeds this limit, IPA-CP will not construct a cloning cost predicate (the thing used to estimate cloning benefit) for the default case of the switch statement.ipa-max-param-expr-opsโ IPA-CP will analyze a conditional statement that references some function parameter to estimate the benefit of cloning upon a certain constant value. but if the number of operations in a parameter expression exceedsipa-max-param-expr-ops, the expression gets treated as a complicated one and IPA analysis just... won't handle it. not her problem fr fr.lto-partitionsโ specify the desired number of partitions produced during WHOPR compilation. the number of partitions should exceed the number of CPUs used for compilation. more partitions than CPUs, periodt.lto-min-partitionโ the size of the minimal partition for WHOPR (in estimated instructions). this prevents the expense of splitting very small programs into way too many partitions. tiny program, tiny partition energy ๐lto-max-partitionโ the size of the max partition for WHOPR (in estimated instructions), to provide an upper bound for the individual size of a partition. meant to be used only with balanced partitioning, bestie.lto-max-streaming-parallelismโ the maximal number of parallel processes used for LTO streaming. maximum parallel chaos, controlled ๐ฆcxx-max-namespaces-for-diagnostic-helpโ the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. it's the "did you mean...?" feature and it only checks this many namespaces ๐sink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block, to allow statement sinking of a statement. larger numbers = more aggressive statement sinking. a small positive adjustment gets applied for statements with memory operands, because those are even more profitable to sink. so yes, memory operands get special treatment, and deservedly so โจmax-stores-to-sinkโ the maximum number of conditional store pairs that can be sunk. set it to0if either vectorization (-ftree-vectorize) or if-conversion (-ftree-loop-if-convert) is disabled. that's the rule, no cap. (jk there IS a cap, that's the whole point.)case-values-thresholdโ the smallest number of different values for which it is best to use a jump-table instead of a tree of conditional branches. if the value is0, use the default for the machine.jump-table-max-growth-ratio-for-sizeโ the maximum code size growth ratio when expanding into a jump table (in percent). this parameter is used when optimizing for size.jump-table-max-growth-ratio-for-speedโ the maximum code size growth ratio when expanding into a jump table (in percent). this parameter is used when optimizing for speed. same ratio, different agenda, iykyk ๐ฅtree-reassoc-widthโ sets the maximum number of instructions executed in parallel in a reassociated tree. this parameter overrides the target dependent heuristics used by default if it has a non zero value. zero = hands off, let the target decide.sched-pressure-algorithmโ choose between the two available implementations of-fsched-pressure.- Algorithm
1is the original implementation and is the more likely to prevent instructions from being reordered. - Algorithm
2was designed to be a compromise between the relatively conservative approach taken by algorithm1and the rather aggressive approach taken by the default scheduler. it relies more heavily on having a regular register file and accurate register pressure classes.
- Algorithm
see haifa-sched.cc in the GCC sources for more details. the default choice depends on the target. algorithm 2 is giving "i'm the middle child, i mediate" ๐ญ
max-slsr-cand-scanโ set the maximum number of existing candidates that are considered when seeking a basis for a new straight-line strength reduction candidate. scanning budget: capped ๐asan-globalsโ enable buffer overflow detection for global objects. this kind of protection is enabled by default if you are using the-fsanitize=addressoption. to disable global objects protection use--param asan-globals=0.asan-stackโ enable buffer overflow detection for stack objects. this kind of protection is enabled by default when using-fsanitize=address. to disable stack protection use--param asan-stack=0option.asan-instrument-readsโ enable buffer overflow detection for memory reads. this kind of protection is enabled by default when using-fsanitize=address. to disable memory reads protection use--param asan-instrument-reads=0.asan-instrument-writesโ enable buffer overflow detection for memory writes. this kind of protection is enabled by default when using-fsanitize=address. to disable memory writes protection use--param asan-instrument-writes=0option.asan-memintrinโ enable detection for built-in functions. this kind of protection is enabled by default when using-fsanitize=address. to disable built-in functions protection use--param asan-memintrin=0.asan-use-after-returnโ enable detection of use-after-return. this kind of protection is enabled by default when using the-fsanitize=addressoption. to disable it use--param asan-use-after-return=0.
Note: by default the check is disabled at run time. to enable it, add"detect_stack_use_after_return=1"to the environment variableASAN_OPTIONS. not me forgetting this and being confused for an hour ๐
asan-instrumentation-with-call-thresholdโ if the number of memory accesses in a function being instrumented is greater or equal to this number, use callbacks instead of inline checks. e.g. to disable inline code use--param asan-instrumentation-with-call-threshold=0.hwasan-instrument-stackโ enable hwasan instrumentation of statically sized stack-allocated variables. this kind of instrumentation is enabled by default when using-fsanitize=hwaddressand disabled by default when using-fsanitize=kernel-hwaddress. to disable stack instrumentation use--param hwasan-instrument-stack=0, and to enable it use--param hwasan-instrument-stack=1.hwasan-random-frame-tagโ when using stack instrumentation, decide tags for stack variables using a deterministic sequence beginning at a random tag for each frame. with this parameter unset, tags are chosen using the same sequence but beginning from1. this is enabled by default for-fsanitize=hwaddressand unavailable for-fsanitize=kernel-hwaddress. to disable it use--param hwasan-random-frame-tag=0.hwasan-instrument-allocasโ enable hwasan instrumentation of dynamically sized stack-allocated variables. this kind of instrumentation is enabled by default when using-fsanitize=hwaddressand disabled by default when using-fsanitize=kernel-hwaddress. to disable instrumentation of such variables use--param hwasan-instrument-allocas=0, and to enable it use--param hwasan-instrument-allocas=1.hwasan-instrument-readsโ enable hwasan checks on memory reads. instrumentation of reads is enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. to disable checking memory reads use--param hwasan-instrument-reads=0.hwasan-instrument-writesโ enable hwasan checks on memory writes. instrumentation of writes is enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. to disable checking memory writes use--param hwasan-instrument-writes=0.hwasan-instrument-mem-intrinsicsโ enable hwasan instrumentation of builtin functions. instrumentation of these builtin functions is enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. to disable instrumentation of builtin functions use--param hwasan-instrument-mem-intrinsics=0.use-after-scope-direct-emission-thresholdโ if the size of a local variable in bytes is smaller or equal to this number, directly poison (or unpoison) shadow memory instead of using run-time callbacks. small variable, direct action, no middleman ๐tsan-distinguish-volatileโ emit special instrumentation for accesses to volatiles. volatile stays getting special attention, as it should.tsan-instrument-func-entry-exitโ emit instrumentation calls to__tsan_func_entry()and__tsan_func_exit().max-fsm-thread-path-insnsโ the maximum number of instructions to copy when duplicating blocks on a finite state automaton jump thread path.max-fsm-thread-lengthโ the maximum number of basic blocks on a jump thread path.threader-debugโthreader-debug=[none|all]enables verbose dumping of the threader solver. yes the options are literallynoneandall, it's giving "no in-between, pick a lane" ๐ญparloops-chunk-sizeโ the chunk size of the omp schedule for loops parallelized by parloops.parloops-scheduleโ the schedule type of the omp schedule for loops parallelized by parloops (static,dynamic,guided,auto,runtime). pick your scheduling vibe ๐parloops-min-per-threadโ the smallest number of iterations per thread in an innermost parallelized loop where the parallelized version actually wins over the single-threaded one. Heads up tho: for a parallelized loop nest, the minimum iterations of the outermost loop per thread is two. โจmax-ssa-name-query-depthโ max recursion depth when we're querying properties of SSA names in stuff like fold routines. One level of recursion = following one use-def chain link. ๐ฆmax-speculative-devirt-maydefsโ the most may-defs we'll analyze while hunting for a must-def that specifies the dynamic type of an object invoking a virtual call we might be able to devirtualize speculatively. ๐max-vrp-switch-assertionsโ the most assertions we'll slap along the default edge of a switch statement during VRP.evrp-sparse-thresholdโ max number of basic blocks before EVRP switches to using a sparse cache.evrp-modeโ picks the mode Early VRP operates in.vrp1-modeโ picks the mode VRP pass 1 operates in.vrp2-modeโ picks the mode VRP pass 2 operates in.ranger-debugโ picks the type of debug output to emit for ranges.evrp-switch-limitโ the most switch cases allowed before EVRP just ignores a switch entirely.unroll-jam-min-percentโ the minimum percentage of memory references that gotta be optimized away for the unroll-and-jam transformation to count as profitable.unroll-jam-max-unrollโ the most times the outer loop should be unrolled by the unroll-and-jam transformation.max-rtl-if-conversion-unpredictable-costโ the max cost allowed for the sequence the RTL if-conversion pass would generate for a branch that's considered unpredictable.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris in play, the most times a single variable will get expanded during loop unrolling.partial-inlining-entry-probabilityโ max probability of the entry BB of a split region (as a percent relative to the entry BB of the function) for partial inlining to actually happen.max-tracked-strlensโ the most strings the strlen optimization pass will track string lengths for.gcse-after-reload-partial-fractionโ the threshold ratio for doing partial redundancy elimination after reload.gcse-after-reload-critical-fractionโ the threshold ratio of critical edges execution count that permits performing redundancy elimination after reload.max-loop-header-insnsโ the most insns in a loop header that get duplicated by the copy loop headers pass.vect-epilogues-nomaskโ turn on loop epilogue vectorization using a smaller vector size.vect-partial-vector-usageโ controls when the loop vectorizer considers partial vector loads and stores as an alternative to falling back to scalar code.0stops the vectorizer from ever using partial vector loads and stores.1allows partial vector loads and stores if vectorization removes the need for the code to iterate.2allows partial vector loads and stores in all loops. This parameter only does anything on targets that support partial vector loads and stores. ๐vect-inner-loop-cost-factorโ the max factor the loop vectorizer applies to the cost of statements in an inner loop relative to the loop being vectorized. The factor applied is the max of the estimated number of iterations of the inner loop and this parameter. The default value of this parameter is50. ๐ฅvect-induction-floatโ turn on loop vectorization of floating point inductions.avoid-fma-max-bitsโ max number of bits for which we avoid creating FMAs.sms-loop-average-count-thresholdโ a threshold on the average loop count considered by the swing modulo scheduler.sms-dfa-historyโ the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.graphite-allow-codegen-errorsโ whether codegen errors should be ICEs when-fcheckingis on.sms-max-ii-factorโ a factor for tuning the upper bound that the swing modulo scheduler uses for scheduling a loop.lra-max-considered-reload-pseudosโ the max number of reload pseudos considered while spilling a non-reload pseudo.max-pow-sqrt-depthโ max depth of sqrt chains to use when synthesizing exponentiation by a real constant.max-dse-active-local-storesโ max number of active local stores in RTL dead store elimination.asan-instrument-allocasโ turn on asan allocas/VLAs protection.max-iterations-computation-costโ a bound on the cost of an expression to compute the number of iterations.max-isl-operationsโ max number of isl operations;0means unlimited.graphite-max-arrays-per-scopโ max number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of loc list for which reverse ops should be added.fsm-scale-path-stmtsโ scale factor applied to the number of statements in a threading path when comparing to the number of (scaled) blocks.uninit-control-dep-attemptsโ max number of nested calls to search for control dependencies during uninitialized variable analysis.fsm-scale-path-blocksโ scale factor applied to the number of blocks in a threading path when comparing to the number of (scaled) statements.sched-autopref-queue-depthโ a hardware autoprefetcher scheduler model control flag. Number of lookahead cycles the model looks into; at' 'only enable the instruction sorting heuristic.loop-versioning-max-inner-insnsโ the most instructions an inner loop can have before the loop versioning pass decides it's too big to copy.loop-versioning-max-outer-insnsโ the most instructions an outer loop can have before the loop versioning pass decides it's too big to copy, not counting any instructions in inner loops that directly benefit from versioning.ssa-name-def-chain-limitโ the mostSSA_NAMEassignments to follow when determining a property of a variable, like its value. This caps the number of iterations or recursive calls GCC does when optimizing certain statements, or when checking their validity before issuing diagnostics.store-merging-max-sizeโ max size of a single store merging region, in bytes.hash-table-verification-limitโ the number of elements for which hash table verification is done, for each searched element.max-find-base-term-valuesโ max number ofVALUEs handled during a singlefind_base_termcall.analyzer-max-enodes-per-program-pointโ the max number of exploded nodes per program point within the analyzer, before analysis of that point gets terminated.analyzer-max-constraintsโ the max number of constraints per state.analyzer-min-snodes-for-call-summaryโ the minimum number of supernodes within a function for the analyzer to consider summarizing its effects at call sites.analyzer-max-enodes-for-full-dumpโ the max depth of exploded nodes that should show up in a dot dump before switching to a less verbose format.analyzer-max-recursion-depthโ the max number of times a callsite can appear in a call stack within the analyzer, before analysis of a call that would recurse deeper gets terminated.analyzer-max-svalue-depthโ the max depth of a symbolic value before the value gets approximated as unknown.analyzer-max-infeasible-edgesโ the max number of infeasible edges to reject before declaring a diagnostic as infeasible.gimple-fe-computed-hot-bb-thresholdโ the number of executions of a basic block that counts as hot. This parameter is used only in GIMPLE FE.analyzer-bb-explosion-factorโ the max number of 'after supernode' exploded nodes within the analyzer per supernode, before analysis gets terminated.ranger-logical-depthโ max depth of logical expression evaluation the ranger will look through when evaluating outgoing edge ranges.relation-block-limitโ max number of relations the oracle will register in a basic block.min-pagesizeโ minimum page size, for warning purposes.openacc-kernelsโ picks the mode for handling OpenACCkernelsconstructs. With--param=openacc-kernels=decompose, OpenACCkernelsconstructs get decomposed into parts โ a sequence of compute constructs, each then handled individually. This is work in progress, bestie. With--param=openacc-kernels=parloops, OpenACCkernelsconstructs are handled by the parloops pass, en bloc. This is the current default. ๐ธopenacc-privatizationโ picks the mode for OpenACC privatization diagnostics for-fopt-info-omp-noteand applicable-fdump-tree-*-details. With--param=openacc-privatization=quiet, don't diagnose. This is the current default. With--param=openacc-privatization=noisy, do diagnose.
The following choices of name are available on AArch64 targets: ๐
aarch64-sve-compare-costsโ when vectorizing for SVE, consider using "unpacked" vectors for smaller elements and use the cost model to pick the cheapest approach. Also use the cost model to choose between SVE and Advanced SIMD vectorization.
Using unpacked vectors includes storing smaller elements in larger containers and accessing elements with extending loads and truncating stores. โจ
aarch64-float-recp-precisionโ this one is literally just "how many Newton iterations do we do when we're working out a reciprocal forfloat?" โจ The precision of the division is proportional to this param whenever division approximation is switched on. The default value is1. ๐aarch64-double-recp-precisionโ same vibe, but fordouble. It's the number of Newton iterations used when calculating the reciprocal fordoubletype, and again the precision of the division is proportional to this param when division approximation is enabled. The default value is2.aarch64-autovec-preferenceโ forces a specific ISA selection strategy for auto-vectorization. It accepts values from0to4, inclusive. ๐0โ use the default heuristics. (the safe, no-thoughts choice, bestie)1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE, but prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE, but prefer SVE when the costs are deemed equal.
The default value is 0. ๐
aarch64-loop-vect-issue-rate-nitersโ so the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when it's deciding whether a loop should get vectorized with SVE, vectorized with Advanced SIMD, or not vectorized at all. If you set this parameter to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations. ๐งaarch64-vect-unroll-limitโ the vectorizer uses whatever tuning info it has to figure out whether unrolling the main vectorized loop would be worth it, and by how much. This parameter sets the upper bound of how much the vectorizer will unroll the main loop. The default value isfour. ๐ฅ
The following choices of name are available on i386 and x86_64 targets, jsyk:
x86-stlf-window-ninsnsโ instructions number above which the STFL stall penalty can be compensated. ๐
โจ Program Instrumentation Options โจ
GCC has a whole lil collection of command-line options that control adding run-time instrumentation to the code it normally generates. ๐ซถ Like, one reason you'd want instrumentation is to collect profiling statistics so you can find program hot spots, do code coverage analysis, or run profile-guided optimizations. Another class of program instrumentation is adding run-time checking to catch programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks like stack smashing or C++ vtable hijacking. ๐ญ And there's also a general hook you can use to implement other forms of tracing or function-level instrumentation for debug or program analysis purposes.
-p,-pgโ generate extra code to write profile information suitable for the analysis programprof(for-p) orgprof(for-pg). You must use this option when compiling the source files you want data about, and you must also use it when linking. โญ
You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.
-fprofile-arcsโ adds code so that program flow arcs get instrumented. While the program runs, it records how many times each branch and call is executed, and how many times it is taken or returns. On targets that support constructors with priority support, profiling properly handles constructors, destructors, and C++ constructors (and destructors) of classes which are used as a type of a global variable. ๐ฆ
When the compiled program exits, it saves this data to a file called auxname.gcda for each source file. That data may be used for profile-directed optimizations (-fbranch-probabilities), or for test coverage analysis (-ftest-coverage). Each object file's auxname is generated from the name of the output file, if explicitly specified and it is not the final executable, otherwise it is the basename of the source file. In both cases any suffix is removed (e.g. foo.gcda for input file dir/foo.c, or dir/foo.gcda for output file specified as -o dir/foo.o).
Note that if a command line directly links source files, the corresponding.gcdafiles will be prefixed with the unsuffixed name of the output file. E.g.gcc a.c b.c -o binarywould generatebinary-a.gcdaandbinary-b.gcdafiles. ๐
--coverageโ this option is used to compile and link code instrumented for coverage analysis. It's a synonym for-fprofile-arcs -ftest-coverage(when compiling) and-lgcov(when linking). See the documentation for those options for more details. ๐- Compile the source files with
-fprofile-arcsplus optimization and code generation options. For test coverage analysis, use the additional-ftest-coverageoption. You do not need to profile every source file in a program. - Compile the source files additionally with
-fprofile-abs-pathto create absolute path names in the.gcnofiles. This allowsgcovto find the correct sources in projects where compilations occur with different working directories. - Link your object files with
-lgcovor-fprofile-arcs(the latter implies the former). - Run the program on a representative workload to generate the arc profile information. This may be repeated any number of times. You can run concurrent instances of your program, and provided that the file system supports locking, the data files will be correctly updated. Unless a strict ISO C dialect option is in effect,
forkcalls are detected and correctly handled without double counting.
- Compile the source files with
Moreover, an object file can be recompiled multiple times and the corresponding .gcda file merges as long as the source file and the compiler options are unchanged.
- For profile-directed optimizations, compile the source files again with the same optimization and code generation options plus
-fbranch-probabilities. - For test coverage analysis, use
gcovto produce human readable information from the.gcnoand.gcdafiles. Refer to thegcovdocumentation for further information.
With -fprofile-arcs, for each function of your program GCC creates a program flow graph, then finds a spanning tree for the graph. Only arcs that are not on the spanning tree have to be instrumented: the compiler adds code to count the number of times that these arcs are executed. When an arc is the only exit or only entrance to a block, the instrumentation code can be added to the block; otherwise, a new basic block must be created to hold the instrumentation code. ๐
-ftest-coverageโ produces a notes file that thegcovcode-coverage utility can use to show program coverage. Each source file's note file is calledauxname.gcno. Refer to the-fprofile-arcsoption above for a description of auxname and instructions on how to generate test coverage data. Coverage data matches the source files more closely if you do not optimize. ๐ธ-fprofile-abs-pathโ automatically converts relative source file names to absolute path names in the.gcnofiles. This allowsgcovto find the correct sources in projects where compilations occur with different working directories. โจ-fprofile-dir=pathโ sets the directory to search for the profile data files in to path. This option affects only the profile data generated by-fprofile-generate,-ftest-coverage,-fprofile-arcsand used by-fprofile-useand-fbranch-probabilitiesand its related options. Both absolute and relative paths can be used. By default, GCC uses the current directory as path, so the profile data file appears in the same directory as the object file. In order to prevent the file name clashing, if the object file name is not an absolute path, we mangle the absolute path of thesourcename.gcdafile and use it as the file name of a.gcdafile. See details about the file naming in-fprofile-arcs. See similar option-fprofile-note. ๐
When an executable is run in a massive parallel environment, it is recommended to save profile to different folders. That can be done with variables in path that are exported during run-time:
%pโ process ID.%q{VAR}โ value of environment variableVAR.
-fprofile-generate,-fprofile-generate=pathโ enables options usually used for instrumenting an application to produce a profile useful for later recompilation with profile feedback based optimization. You must use-fprofile-generateboth when compiling and when linking your program. ๐ฅ
The following options are enabled: -fprofile-arcs, -fprofile-values, -finline-functions, and -fipa-bit-cp.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir.
To optimize the program based on the collected profile information, use -fprofile-use.
-fprofile-info-section,-fprofile-info-section=nameโ registers the profile information in the specified section instead of using a constructor/destructor. The section name is name if it is specified, otherwise the section name defaults to.gcov_info. A pointer to the profile information generated by-fprofile-arcsis placed in the specified section for each translation unit. This option disables the profile information registration through a constructor and it disables the profile information processing through a destructor. This option is not intended to be used in hosted environments such as GNU/Linux. It targets free-standing environments (for example embedded systems) with limited resources which do not support constructors/destructors or the C library file I/O. ๐ง
The linker could collect the input sections in a continuous memory block and define start and end symbols. A GNU linker script example which defines a linker output section follows:
.gcov_info :
{
PROVIDE (__gcov_info_start = .);
KEEP (*(.gcov_info))
PROVIDE (__gcov_info_end = .);
}
The program could dump the profiling information registered in this linker set for example like this:
#include <gcov.h>
#include <stdio.h>
#include <stdlib.h>
extern const struct gcov_info *__gcov_info_start[];
extern const struct gcov_info *__gcov_info_end[];
static void
filename (const char *f, void *arg)
{
puts (f);
}
static void
dump (const void *d, unsigned n, void *arg)
{
const unsigned char *c = d;
for (unsigned i = 0; i < n; ++i)
printf ("%02x", c[i]);
}
static void *
allocate (unsigned length, void *arg)
{
return malloc (length);
}
static void
dump_gcov_info (void)
{
const struct gcov_info **info = __gcov_info_start;
const struct gcov_info **end = __gcov_info_end;
/* Obfuscate variable to prevent compiler optimizations. */
__asm__ ("" : "+r" (info));
while (info != end)
{
void *arg = NULL;
__gcov_info_to_gcda (*info, filename, dump, allocate, arg);
putchar ('\n');
++info;
}
}
int
main()
{
dump_gcov_info();
return 0;
}
okay bestie we're back and we're still in the options pit but honestly? iconic behavior. let's go ๐
-fprofile-note=pathโ if you hand it a path, GCC drops the.gcnofile right there in that location. heads up though: if you pair this with multiple source files, the.gcnofile gets overwritten โ like, no cap, one file, gone. ๐-fprofile-prefix-path=pathโ you use this one withprofile-generate=profile_dirandprofile-use=profile_dirto tell GCC where the base directory of your built source tree actually lives. by defaultprofile_diris out here holding files with mangled absolute paths of every object file in the project, which is not it when the directory you built the instrumented binary in is different from the directory you build the profile-feedback-optimized binary in โ because then the profile data won't be found during the optimized build. ๐ญ so in those setups,-fprofile-prefix-path=pathwith path pointing at the base directory of the build strips off the irrelevant part of the path and keeps all the file names relative to the main build directory. slay. โจ-fprofile-prefix-map=old=newโ when you're compiling files sitting in directory old, this records profiling info (with--coverage) describing them as if they lived in directory new instead. also peep-ffile-prefix-mapfor the cousin option. ๐ฆ-fprofile-update=methodโ this one changes up the update method for an app that's been instrumented for profile-feedback-based optimization. method has to be one ofsingle,atomic, orprefer-atomic.singleis the move for single-threaded apps, andatomicstops profile corruption by emitting thread-safe code. ๐ฅ
warning bestie!! when an application doesn't properly join all its threads (or creates a detached thread), a profile file can still get corrupted. not a vibe.
using prefer-atomic gets transformed into either atomic (when the target supports it) or single otherwise. and the GCC driver will automatically pick prefer-atomic whenever -pthread shows up in the command line. ๐
-fprofile-filter-files=regexโ instruments only functions from files whose name matches any of the regular expressions (separated by semicolons). so like,-fprofile-filter-files=main\.c;module.*\.cwill instrument onlymain.cand every C file that starts withmodule. obsessed. ๐-fprofile-exclude-files=regexโ the mirror image: instruments only functions from files whose name does not match any of the regular expressions (also separated by semicolons). for example,-fprofile-exclude-files=/usr/.*blocks instrumentation of every file chillin' in the/usr/folder. ๐ซ-fprofile-reproducible=[multithreaded|parallel-runs|serial]โ this controls how reproducible the profile gathered by-fprofile-generateis, so you can rebuild a program with the same outcome. super useful for distribution packages, fr fr. ๐ฆ
with -fprofile-reproducible=serial, the profile gathered by -fprofile-generate is reproducible provided the trained program behaves the same at each invocation of the train run, it's not multi-threaded, and profile data streaming always happens in the same order. note that profile streaming happens at the end of the program run but also before the fork function gets invoked. ๐
also note it's pretty common for execution counts of some part of programs to depend on stuff like the length of temporary file names or memory space randomization (which can affect hash-table collision rate). those non-reproducible parts can be annotated with the no_instrument_function function attribute, and gcov-dump with -l can dump the gathered data so you can verify it's actually reproducible. โญ
with -fprofile-reproducible=parallel-runs, the collected profile stays reproducible regardless of the order data streams into the gcda files. this setting lets you run multiple instances of an instrumented program in parallel (like with make -j). but bestie โ it reduces the quality of the gathered data, especially indirect call profiling. trade-offs, always. ๐
-fsanitize=addressโ enables AddressSanitizer, a fast memory error detector. memory access instructions get instrumented to catch out-of-bounds and use-after-free bugs. this option also enables-fsanitize-address-use-after-scope. more deets athttps://github.com/google/sanitizers/wiki/AddressSanitizer. ๐
the run-time behavior can be influenced with the ASAN_OPTIONS environment variable โ set it to help=1 and the available options get shown at startup of the instrumented program. a full list of supported options lives at https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags. ๐
this option cannot be combined with-fsanitize=threador-fsanitize=hwaddress. also note the only target-fsanitize=hwaddressis currently supported on is AArch64.
-fsanitize=kernel-addressโ enables AddressSanitizer for the Linux kernel. seehttps://github.com/google/kasanfor more. ๐ง-fsanitize=hwaddressโ enables Hardware-assisted AddressSanitizer, which uses a hardware ability to ignore the top byte of a pointer so it can detect memory errors with low memory overhead. memory access instructions get instrumented to catch out-of-bounds and use-after-free bugs. this option enables-fsanitize-address-use-after-scope. deets athttps://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html. ๐ฆ
run-time behavior can be influenced with the HWASAN_OPTIONS environment variable โ set it to help=1 and the available options show at startup of the instrumented program.
cannot be combined with-fsanitize=threador-fsanitize=address, and it's currently only available on AArch64.
-fsanitize=kernel-hwaddressโ enables Hardware-assisted AddressSanitizer for compiling the Linux kernel. it's similar to-fsanitize=kernel-addressbut uses an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences needed for compiling the Linux kernel. those differences exist to avoid hwasan library initialization calls and to account for the stack pointer having a different value in its top byte. ๐งโจ
note: this option has different defaults from-fsanitize=hwaddress. instrumenting the stack andallocacalls are not on by default, but you can still get them by specifying the command-line options--param hwasan-instrument-stack=1and--param hwasan-instrument-allocas=1respectively. using a random frame tag is not implemented for kernel instrumentation.
-fsanitize=pointer-compareโ instruments comparison operations (<,<=,>,>=) with pointer operands. this option must be combined with either-fsanitize=kernel-addressor-fsanitize=address, and it cannot be combined with-fsanitize=thread. ๐
note: by default the check is disabled at run time. to turn it on, adddetect_invalid_pointer_pairs=2to theASAN_OPTIONSenvironment variable. usingdetect_invalid_pointer_pairs=1detects an invalid operation only when both pointers are non-null.
-fsanitize=pointer-subtractโ instruments subtraction with pointer operands. just like its sibling, this option must be combined with either-fsanitize=kernel-addressor-fsanitize=address, and it cannot be combined with-fsanitize=thread. ๐ซถ
note: by default the check is disabled at run time. to turn it on, adddetect_invalid_pointer_pairs=2to theASAN_OPTIONSenvironment variable. usingdetect_invalid_pointer_pairs=1detects an invalid operation only when both pointers are non-null.
-fsanitize=shadow-call-stackโ enables ShadowCallStack, a security enhancement mechanism used to protect programs against return address overwrites (e.g. stack buffer overflows). it works by saving a function's return address to a separately allocated shadow call stack in the function prologue, then restoring that return address from the shadow call stack in the function epilogue. instrumentation only happens in functions that actually need to save the return address to the stack. ๐๐
currently it only supports the aarch64 platform. it's specifically designed for linux kernels that enable the CONFIG_SHADOW_CALL_STACK option. for user space programs, runtime support is not currently provided in libc and libgcc. users who want this feature in user space need to provide their own runtime support. and it should be noted that this may cause the ABI rules to be broken. ๐
on aarch64, the instrumentation makes use of the platform register x18. this generally means any code that may run on the same thread as code compiled with ShadowCallStack must be compiled with the flag -ffixed-x18 โ otherwise functions compiled without -ffixed-x18 might clobber x18 and so corrupt the shadow stack pointer. ๐ญ
also, because there's no userspace runtime support, code compiled with ShadowCallStack cannot use exception handling. use -fno-exceptions to turn off exceptions. ๐
see https://clang.llvm.org/docs/ShadowCallStack.html for more details. ๐ธ
-fsanitize=threadโ bestie, this one turns on ThreadSanitizer, aka the fast data race detector ๐โ๏ธ๐จ Memory access instructions get instrumented so it can sniff out data race bugs. More deets live at <https://github.com/google/sanitizers/wiki#threadsanitizer>. You can influence how it behaves at run time with theTSAN_OPTIONSenvironment variable, and there's a whole list of supported options at <https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags>. โ ๏ธ This option cannot be combined with-fsanitize=addressor-fsanitize=leak.
Also note: sanitized atomic builtins can't throw exceptions when they're operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions). ๐
-fsanitize=leakโ enables LeakSanitizer, the memory leak detector ๐ต๏ธโ๏ธ This one only matters for linking of executables, and the executable gets linked against a library that overridesmallocand other allocator functions. More details at <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>. Run-time behavior is influenced by theLSAN_OPTIONSenvironment variable. โ ๏ธ Cannot be combined with-fsanitize=thread.-fsanitize=undefinedโ turns on UndefinedBehaviorSanitizer, the fast undefined behavior detector โจ Various computations get instrumented so UB can be caught at runtime. Details at <https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>. Run-time behavior is influenced by theUBSAN_OPTIONSenvironment variable. The current suboptions are, and yes we're listing every single one because we do not gatekeep ๐ :-fsanitize=shiftโ checks that the result of a shift operation isn't undefined. Heads up though: what exactly counts as undefined differs slightly between C and C++, and between ISO C90 and C99, etc. This one has two suboptions:-fsanitize=shift-baseand-fsanitize=shift-exponent.-fsanitize=shift-exponentโ checks that the second argument of a shift operation isn't negative and is smaller than the precision of the promoted first argument.-fsanitize=shift-baseโ if the second argument of a shift operation is within range, check that the result of the shift operation isn't undefined. And again, what exactly counts as undefined differs slightly between C and C++, and between ISO C90 and C99, etc.-fsanitize=integer-divide-by-zeroโ detects integer division by zero. ๐ซโ0๏ธโฃ-fsanitize=unreachableโ with this one, the compiler turns the__builtin_unreachablecall into a diagnostics message call instead. When you actually reach that__builtin_unreachablecall, the behavior is undefined. ๐ญ-fsanitize=vla-boundโ tells the compiler to check that the size of a variable length array is positive.-fsanitize=nullโ enables pointer checking ๐ Specifically, an application built with this turned on will throw an error message when it tries to dereference a NULL pointer, or if a reference (possibly an rvalue reference) is bound to a NULL pointer, or if a method is invoked on an object pointed to by a NULL pointer.-fsanitize=returnโ enables return statement checking. Programs built with this turned on will issue an error message when the end of a non-void function is reached without actually returning a value. C++ only, bestie.-fsanitize=signed-integer-overflowโ enables signed integer overflow checking. We check that the result of+,*, and both unary and binary-doesn't overflow in signed arithmetic. It also detectsINT_MIN / -1signed division. But note: integer promotion rules must be taken into account. Which means the following is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ enables instrumentation of array bounds. Various out of bounds accesses get detected. But flexible array members, flexible array member-like arrays, and initializers of variables with static storage are not instrumented.-fsanitize=bounds-strictโ enables strict instrumentation of array bounds ๐ฅ Most out of bounds accesses get detected, including flexible array members and flexible array member-like arrays. Initializers of variables with static storage are still not instrumented though.-fsanitize=alignmentโ enables checking of alignment of pointers when they're dereferenced, or when a reference is bound to an insufficiently aligned target, or when a method or constructor is invoked on an insufficiently aligned object.-fsanitize=object-sizeโ enables instrumentation of memory references using the__builtin_object_sizefunction. Various out of bounds pointer accesses get detected.-fsanitize=float-divide-by-zeroโ detects floating-point division by zero. Unlike other similar options,-fsanitize=float-divide-by-zerois not enabled by-fsanitize=undefined, because floating-point division by zero can be a totally legitimate way of obtaining infinities and NaNs ๐-fsanitize=float-cast-overflowโ enables floating-point type to integer conversion checking. We check that the result of the conversion doesn't overflow. Unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Also, this option doesn't work well withFE_INVALIDexceptions enabled.-fsanitize=nonnull-attributeโ enables instrumentation of calls, checking whether null values aren't passed to arguments marked as requiring a non-null value by thenonnullfunction attribute.-fsanitize=returns-nonnull-attributeโ enables instrumentation of return statements in functions marked with thereturns_nonnullfunction attribute, so it can detect returning of null values from such functions.-fsanitize=boolโ enables instrumentation of loads from bool. If a value other than 0/1 gets loaded, a run-time error is issued. ๐จ-fsanitize=enumโ enables instrumentation of loads from an enum type. If a value outside the range of values for the enum type gets loaded, a run-time error is issued.-fsanitize=vptrโ enables instrumentation of C++ member function calls, member accesses and some conversions between pointers to base and derived classes, to verify the referenced object has the correct dynamic type. ๐-fsanitize=pointer-overflowโ enables instrumentation of pointer arithmetics. If the pointer arithmetics overflows, a run-time error is issued.-fsanitize=builtinโ enables instrumentation of arguments to selected builtin functions. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing 0 as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and gets diagnosed by this option.
And for the record, while -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message instead. This currently works only for the C family of languages. ๐
-fno-sanitize=allโ disables all previously enabled sanitizers, like a full reset button ๐งผโจ Note that-fsanitize=allis not allowed, because some sanitizers just cannot be used together. It's giving irreconcilable differences, fr fr.- *
-fasan-shadow-offset=number* โ forces GCC to use a custom shadow offset in AddressSanitizer checks. It's useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer. - *
-fsanitize-sections=s1,s2,...* โ sanitize global variables in selected user-defined sections. Eachsimay contain wildcards. ๐ฏ - *
-fsanitize-recover[=opts*]** โ this one controls error recovery mode for the sanitizers mentioned in the comma-separated list of *opts*. Enabling it for a sanitizer component makes it attempt to keep running the program as if no error happened. That means multiple runtime errors can be reported in a single program run, and the exit code of the program may indicate success even when errors *have* been reported ๐ The-fno-sanitize-recover=` option can be used to alter this behavior: only the first detected error gets reported, and the program then exits with a non-zero exit code.
Currently this feature only works for -fsanitize=undefined (and its suboptions except for -fsanitize=unreachable and -fsanitize=return), -fsanitize=float-cast-overflow, -fsanitize=float-divide-by-zero, -fsanitize=bounds-strict, -fsanitize=kernel-address and -fsanitize=address. For these sanitizers error recovery is turned on by default, except -fsanitize=address, for which this feature is experimental. -fsanitize-recover=all and -fno-sanitize-recover=all are also accepted: the former enables recovery for all sanitizers that support it, the latter disables recovery for all sanitizers that support it.
Even if recovery mode is turned on the compiler side, it also needs to be enabled on the runtime library side, otherwise the failures are still fatal. The runtime library defaults tohalt_on_error=0for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer ishalt_on_error=1. You can override this by setting thehalt_on_errorflag in the corresponding environment variable.
Also, syntax without an explicit opts parameter is deprecated โ ๏ธ It's equivalent to specifying an opts list of:
undefined,float-cast-overflow,float-divide-by-zero,bounds-strict
-fsanitize-address-use-after-scopeโ enables sanitization of local variables to detect use-after-scope bugs. This option sets-fstack-reusetonone.-fsanitize-undefined-trap-on-errorโ instructs the compiler to report undefined behavior using__builtin_traprather than alibubsanlibrary routine. The advantage here is that thelibubsanlibrary isn't needed and isn't linked in, so this is usable even in freestanding environments. ๐๏ธโจ-fsanitize-coverage=trace-pcโ turns on coverage-guided fuzzing instrumentation ๐ it drops a call to__sanitizer_cov_trace_pcinto every basic block, so every single one. no skipping, bestie.-fsanitize-coverage=trace-cmpโ dataflow-guided fuzzing instrumentation, and the way it works is so specific: it inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8for integral comparisons where both operands are variables, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8when one operand is a constant ๐ซถ and for floats/doubles it's__sanitizer_cov_trace_cmpfor__sanitizer_cov_trace_cmpd, plus__sanitizer_cov_trace_switchforswitchstatements. the whole squad of trace functions, assembled. โจ-fcf-protection=[full|branch|return|none|check]โ ok this one is genuinely iconic for security ๐ it instruments control-flow transfers so the compiler can check that the target addresses of control-flow transfer instructions โ like indirect function calls, function returns, indirect jumps โ are actually valid. which stops anyone from diverting the flow of control to some unexpected target. it's built to protect you from Return-oriented Programming (ROP) and, same energy, call/jmp-oriented programming (COP/JOP). ๐branchโ check validity at the point of indirect branch instructions, i.e.call/jmp.returnโ check validity at the point of returning from a function.fullโ an alias for specifying bothbranchandreturn.noneโ turns the instrumentation off. ๐ซcheckโ this one's for the final link with link-time optimization (LTO). an error gets issued if LTO object files were compiled with different-fcf-protectionvalues. and heads up:checkis ignored at compile time. ๐
The macro __CET__ is defined whenever -fcf-protection is used. its first bit is set to 1 for the value branch, and its second bit is set to 1 for return. โจ
You can also use the nocf_check attribute to identify which functions and calls should be skipped from instrumentation. lowkey handy.
Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET), which works for i686 processor or newer. ๐ง
-fharden-comparesโ for every logical test that survives gimple optimizations and is not the condition in a conditional branch (think: conditions tested for conditional moves, or to store in boolean variables), it emits extra code to compute and verify the reversed condition, and to call__builtin_trapif the results don't match. ๐ชค pair it with-fharden-conditional-branchesto cover all conditionals.-fharden-conditional-branchesโ for every non-vectorized conditional branch that survives gimple optimizations, it emits extra code to compute and verify the reversed condition, and to call__builtin_trapif the result is unexpected. pair it with-fharden-comparesto cover all conditionals. ๐ฅ
NOTE: In Ubuntu 19.10 and later versions,-fcf-protectionis enabled by default for C, C++, ObjC, ObjC++, if none of-fno-cf-protectionnor-fcf-protection=*are found.
-fstack-protectorโ emits extra code to check for buffer overflows, like stack smashing attacks ๐ญ it does this by adding a guard variable to functions with vulnerable objects. this includes functions that callalloca, and functions with buffers larger than or equal to 8 bytes. the guards get initialized when a function is entered, then checked when the function exits. if a guard check fails, an error message is printed and the program exits. ๐ only variables that are actually allocated on the stack count, so optimized-away variables or variables allocated in registers don't count. periodt.-fstack-protector-allโ like-fstack-protectorexcept that all functions are protected. all of them. no exceptions. ๐ก๏ธ-fstack-protector-strongโ like-fstack-protectorbut it includes additional functions to be protected โ specifically those that have local array definitions, or have references to local frame addresses. and same as before: only variables actually allocated on the stack are considered, optimized away variables or variables allocated in registers don't count. ๐-fstack-protector-explicitโ like-fstack-protectorbut it only protects those functions which have thestack_protectattribute. exclusive, as the name says. ๐-fstack-checkโ generates code to verify that you don't go beyond the boundary of the stack. you should specify this flag if you're running in an environment with multiple threads ๐งต but you only rarely need to specify it in a single-threaded environment, since stack overflow is automatically detected on nearly all systems if there's only one stack.
Note that this switch does not actually cause checking to be done; the operating system or the language runtime must do that. the switch just causes generation of code to ensure that they see the stack being extended. ๐ซ
You can additionally specify a string parameter: no means no checking, generic means force the use of old-style checking, specific means use the best checking method and is equivalent to bare -fstack-check.
Old-style checking is a generic mechanism that requires no specific target support in the compiler, but bestie it comes with drawbacks:
- Modified allocation strategy for large objects: they are always allocated dynamically if their size exceeds a fixed threshold. note this may change the semantics of some code. ๐ฌ
- Fixed limit on the size of the static frame of functions: when it's topped by a particular function, stack checking is not reliable and a warning is issued by the compiler.
- Inefficiency: because of both the modified allocation strategy and the generic implementation, code performance is hampered. ๐
Note that old-style stack checking is also the fallback method for specific if no target support has been added in the compiler.
-fstack-check= is designed for Ada's needs to detect infinite recursion and stack overflows. specific is an excellent choice when compiling Ada code โจ It is not generally sufficient to protect against stack-clash attacks. to protect against those you want -fstack-clash-protection.
-fstack-clash-protectionโ generates code to prevent stack clash style attacks ๐ฅ when this option is enabled, the compiler will only allocate one page of stack space at a time, and each page is accessed immediately after allocation. that way it prevents allocations from jumping over any stack guard page provided by the operating system. it's giving careful. ๐
Most targets do not fully support stack clash protection. however, on those targets -fstack-clash-protection will protect dynamic stack allocations. -fstack-clash-protection may also provide limited protection for static stack allocations if the target supports -fstack-check=specific.
NOTE: In Ubuntu 19.10 and later versions,-fstack-clash-protectionis enabled by default for C, C++, ObjC, ObjC++, unless-fno-stack-clash-protectionis found.
-fstack-limit-register=reg,-fstack-limit-symbol=sym,-fno-stack-limitโ these generate code to ensure that the stack doesn't grow beyond a certain value, either the value of a register or the address of a symbol. if a larger stack is required, a signal is raised at run time โก for most targets the signal is raised before the stack overruns the boundary, so it's possible to catch the signal without taking special precautions.
For instance, if the stack starts at absolute address 0x80000000 and grows downwards, you can use the flags -fstack-limit-symbol=__stack_limit and -Wl,--defsym,__stack_limit=0x7ffe0000 to enforce a stack limit of 128KB. note that this may only work with the GNU linker. ๐ง
You can locally override stack limit checking by using the no_stack_limit function attribute.
-fsplit-stackโ generates code to automatically split the stack before it overflows ๐ the resulting program has a discontiguous stack which can only overflow if the program is unable to allocate any more memory. this is most useful when running threaded programs, since it's no longer necessary to calculate a good stack size to use for each thread. currently this is only implemented for the x86 targets running GNU/Linux.
When code compiled with -fsplit-stack calls code compiled without -fsplit-stack, there may not be much stack space available for the latter code to run ๐ญ if compiling all code, including library code, with -fsplit-stack is not an option, then the linker can fix up these calls so that the code compiled without -fsplit-stack always has a large stack. support for this is implemented in the gold linker in GNU binutils release 2.21 and later. ๐
-fvtable-verify=[std|preinit|none]โ this option is only available when compiling C++ code, fyi ๐ it turns on (or off, if you use-fvtable-verify=none) the security feature that verifies at run time, for every virtual call, that the vtable pointer through which the call is made is valid for the type of the object, and hasn't been corrupted or overwritten. if an invalid vtable pointer is detected at run time, an error is reported and execution of the program is immediately halted. ๐ no cap.
This option causes run-time data structures to be built at program startup, which are used for verifying the vtable pointers. the options std and preinit control the timing of when these data structures are built. in both cases the data structures are built before execution reaches main. using -fvtable-verify=std causes the data structures to be built after shared libraries have been loaded and initialized. -fvtable-verify=preinit causes them to be built before shared libraries have been loaded and initialized. โจ
If this option appears multiple times in the command line with different values specified, none takes highest priority over both std and preinit; preinit takes priority over std. ๐
-fvtv-debugโ okay so when you pair this with-fvtable-verify=stdor-fvtable-verify=preinit, it makes the compiler call the debug versions of the runtime functions for the vtable verification feature. Bestie, it also makes the compiler log which vtable pointers it found for each class. That info gets written to a file calledvtv_set_ptr_data.log, and it goes in the directory named by the environment variableVTV_LOGS_DIRif that's defined โ otherwise it just lands in the current working directory.
Note: this feature appends data to the log file. So if you want a fresh log file, be sure to delete any existing one first. ๐
-fvtv-countsโ this one is a debugging flag, no cap. When you use it with-fvtable-verify=stdor-fvtable-verify=preinit, it makes the compiler keep track of the total number of virtual calls it encounters and the number of verifications it inserts. It also counts the number of calls to certain run-time library functions that it inserts, and logs that info for each compilation unit. All of this goes into a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif that's defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class and writes that intovtv_class_set_sizes.login the same directory.
Note: this feature appends data to the log files. To get fresh log files, be sure to delete any existing ones. ๐ซถ
-finstrument-functionsโ generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, these profiling functions get called with the address of the current function and its call site. (On some platforms,"__builtin_return_address"doesn't work beyond the current function, so the call site info may not be available to the profiling functions otherwise.)
void __cyg_profile_func_enter (void *this_fn,
void *call_site);
void __cyg_profile_func_exit (void *this_fn,
void *call_site);
The first argument is the address of the start of the current function, which you can look up exactly in the symbol table.
This instrumentation is also done for functions expanded inline in other functions. The profiling calls indicate where, conceptually, the inline function is entered and exited. Which means addressable versions of such functions must be available. If all your uses of a function are expanded inline, this may mean an additional expansion of code size. And if you use "extern inline" in your C code, an addressable version of such functions must be provided. (This is normally the case anyway, but if you get lucky and the optimizer always expands the functions inline, you might have gotten away without providing static copies.)
A function can be given the attribute "no_instrument_function", and then this instrumentation isn't done at all. This is useful for, like, the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions can't safely be called โ maybe signal handlers, if the profiling routines generate output or allocate memory. ๐ญ
-finstrument-functions-exclude-file-list=file,file,...โ sets the list of functions that are excluded from instrumentation (peep the description of-finstrument-functions). If the file that contains a function definition matches with one of file, then that function is not instrumented. The match is done on substrings: if the file parameter is a substring of the file name, it's considered a match.
For example:
-finstrument-functions-exclude-file-list=/bits/stl,include/sys
excludes any inline function defined in files whose pathnames contain /bits/stl or include/sys.
If, for some reason, you want to include letter , in one of sym, write ,. For example, -finstrument-functions-exclude-file-list=',,tmp' (note the single quote surrounding the option).
-finstrument-functions-exclude-function-list=sym,sym,...โ this is similar to-finstrument-functions-exclude-file-list, but this option sets the list of function names to be excluded from instrumentation. The function name to be matched is its user-visible name, like"vector<int> blah(const vector<int> &)", not the internal mangled name (e.g.,"_Z4blahRSt6vectorIiSaIiEE"). The match is done on substrings: if the sym parameter is a substring of the function name, it's considered a match. For C99 and C++ extended identifiers, the function name must be given in UTF-8, not using universal character names. โจ-fpatchable-function-entry=N[,M]โ generate N NOPs right at the beginning of each function, with the function entry point before the Mth NOP. If M is omitted, it defaults to0, so the function entry points to the address just at the first NOP. The NOP instructions reserve extra space which can be used to patch in any desired instrumentation at run time, provided that the code segment is writable. The amount of space is controllable indirectly via the number of NOPs; the NOP instruction used corresponds to the instruction emitted by the internal GCC back-end interface"gen_nop". This behavior is target-specific and may also depend on the architecture variant and/or other compilation options.
For run-time identification, the starting addresses of these areas โ which correspond to their respective function entries minus M โ are additionally collected in the "__patchable_function_entries" section of the resulting binary.
Note that the value of "__attribute__ ((patchable_function_entry (N,M)))" takes precedence over the command-line option -fpatchable-function-entry=N,M. This can be used to increase the area size or to remove it completely on a single function. If "N=0", no pad location is recorded.
The NOP instructions are inserted at โ and maybe before, depending on M โ the function entry address, even before the prologue.
The maximum value of N and M is 65535. ๐
โจ Options Controlling the Preprocessor โจ
These options control the C preprocessor, which gets run on each C source file before actual compilation. It's giving pre-game warmup, honestly.
If you use the -E option, nothing is done except preprocessing. Some of these options only make sense together with -E, because they cause the preprocessor output to be unsuitable for actual compilation.
In addition to the options listed here, there are a number of options to control search paths for include files documented in Directory Options. Options to control preprocessor diagnostics are listed in Warning Options.
-Dname โ predefine name as a macro, with definition1. Simple as that. ๐-Dname=definition โ the contents of definition are tokenized and processed as if they appeared during translation phase three in a#definedirective. In particular, the definition is truncated by embedded newline characters.
If you're invoking the preprocessor from a shell or shell-like program, you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax. iykyk
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you should quote the option. With sh and csh, -D'name(args...)=definition' works.
-D and -U options are processed in the order they are given on the command line. All -imacros file and -include file options are processed after all -D and -U options. Order matters, bestie, don't forget it. ๐
-Uname โ cancel any previous definition of name, either built in or provided with a-Doption. Gone. Deleted. Not me undefining your fave macro. ๐-includefile โ process file as if"#include "file""appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If it's not found there, it's searched for in the remainder of the"#include "...""search chain as normal.
If multiple -include options are given, the files are included in the order they appear on the command line.
-imacrosfile โ exactly like-include, except that any output produced by scanning file is thrown away. Macros it defines remain defined. This lets you acquire all the macros from a header without also processing its declarations. It's giving macro theft, but legal. โจ
All files specified by -imacros are processed before all files specified by -include.
-undefโ do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined. So it's a partial wipe, not a full reset. ๐ง-pthreadโ define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. This option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets.-Mโ instead of outputting the result of preprocessing, output a rule suitable formakedescribing the dependencies of the main source file. The preprocessor outputs onemakerule containing the object file name for that source file, a colon, and the names of all the included files, including those coming from-includeor-imacroscommand-line options.
Unless specified explicitly (with -MT or -MQ), the object file name consists of the name of the source file with any suffix replaced with object file suffix and with any leading directory parts removed. If there are many included files then the rule is split into several lines using \-newline. The rule has no commands.
This option does not suppress the preprocessor's debug output, such as -dM. To avoid mixing such debug output with the dependency rules you should explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal.
Passing -M to the driver implies -E, and suppresses warnings with an implicit -w.
-MMโ like-Mbut do not mention header files that are found in system header directories, nor header files that are included, directly or indirectly, from such a header.-MF fileโ when you're rolling with-Mor-MM, this is how you tell the preprocessor where to drop the dependency rules. No-MF? Then it just sends them wherever it would've sent the preprocessed output, nbd. When you're using the driver options-MDor-MMD,-MFoverrides the default dependency output file. And bestie, iffileis literally-, the deps go straight to stdout. ๐-MGโ teaming up with something like-Mthat generates dependencies,-MGjust assumes missing headers are generated files and adds them to the dependency list without throwing an error. The dependency filename comes straight from the#includedirective, no path prepended, no questions asked. It also suppresses preprocessed output, since a missing header makes that whole thing useless. This feature gets used for automatic makefile updating. โจ-Mno-modulesโ turns off dependency generation for compiled module interfaces. that's it, that's the vibe. ๐-MPโ tells CPP to add a phony target for each dependency other than the main file, so each one depends on nothing. These dummy rules are the fix for the errorsmakethrows at you when you delete header files without updating the Makefile to match. typical output looks like:
test.o: test.c test.h
test.h:
-MT targetโ changes the target of the rule that dependency generation emits. By default CPP takes the name of the main input file, deletes any directory components and any file suffix like.c, and appends the platform's usual object suffix โ boom, that's your target. An-MToption sets the target to be exactly the string you give it. Want multiple targets? Pass them as a single argument to-MT, or just use multiple-MToptions. For example,-MT '$(objpfx)foo.o'might give you:
$(objpfx)foo.o: foo.c
-MQ targetโ same as-MT, but it quotes any characters that are special to Make. So-MQ '$(objpfx)foo.o'gives:
$$(objpfx)foo.o: foo.c
The default target gets automatically quoted too, as if you'd passed it with -MQ. iconic. ๐
-MDโ-MDis equivalent to-M -MF file, except that-Eis not implied. The driver figures outfilebased on whether you gave it an-ooption. If you did, it uses that argument but with a.dsuffix; if you didn't, it takes the input file's name, strips directory components and suffix, and slaps a.don the end. If-MDis used with-E, any-oswitch is understood to specify the dependency output file โ but without-E, each-ospecifies a target object file. And since-Eisn't implied,-MDcan generate a dependency output file as a lil side effect of the compilation process. multitasking queen. ๐-MMDโ like-MDexcept it only mentions user header files, not system header files. ๐-fpreprocessedโ tells the preprocessor that the input file has already been preprocessed. This suppresses macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives. It still recognizes and removes comments though, so you can pass a file that was preprocessed with-Cto the compiler without any drama. In this mode the integrated preprocessor is barely more than a tokenizer for the front ends. ngl, it's giving minimal effort (affectionate).-fpreprocessedis implicit if the input file has one of the extensions.i,.iior.miโ those are the extensions GCC uses for preprocessed files created by-save-temps.-fdirectives-onlyโ when preprocessing, handle directives, but do not expand macros. The behavior depends on the-Eand-fpreprocessedoptions:- With
-E, preprocessing is limited to handling directives like#define,#ifdef, and#error. Other preprocessor operations, like macro expansion and trigraph conversion, are not performed. Bonus: the-dDoption is implicitly enabled. - With
-fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros like__LINE__, which are contextually dependent, are handled normally. This enables compilation of files previously preprocessed with"-E -fdirectives-only". - With both
-Eand-fpreprocessed, the rules for-fpreprocessedtake precedence. This enables full preprocessing of files previously preprocessed with"-E -fdirectives-only".
- With
-fdollars-in-identifiersโ accept$in identifiers. yes really. ๐-fextended-identifiersโ accept universal character names and extended characters in identifiers. This one's enabled by default for C99 (and later C standard versions) and C++. โจ-fno-canonical-system-headersโ when preprocessing, don't shorten system header paths with canonicalization. ๐ธ-fmax-include-depth=depthโ sets the max depth of nested#include. The default is200. don't go deeper than that bestie, it gets scary down there. ๐ฆ-ftabstop=widthโ sets the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even when tabs show up on the line. If the value is less than 1 or greater than 100, the option is just ignored. The default is8.-ftrack-macro-expansion[=level]โ tracks locations of tokens across macro expansions. This lets the compiler emit diagnostics about the current macro expansion stack when a compilation error happens inside a macro expansion. Heads up though: using this option makes the preprocessor and compiler consume more memory. Thelevelparameter chooses how precise the token location tracking is, so you can dial down the memory consumption if you need to:- Value
0oflevelde-activates this option. - Value
1tracks token locations in a degraded mode for minimal memory overhead. In this mode all tokens resulting from the expansion of an argument of a function-like macro have the same location. - Value
2tracks token locations completely. This value is the most memory hungry.
- Value
When this option is given with no argument, the default parameter value is 2. Also, note that "-ftrack-macro-expansion=2" is activated by default.
-fmacro-prefix-map=old=newโ when preprocessing files living in directoryold, expand the__FILE__and__BASE_FILE__macros as if the files lived in directorynewinstead. You can use this to turn an absolute path into a relative one by settingnewto., which can give you more reproducible builds that are location independent. This option also affects__builtin_FILE()during compilation. See also-ffile-prefix-map. ๐ซถ-fexec-charset=charsetโ set the execution character set, used for string and character constants. The default isUTF-8.charsetcan be any encoding supported by the system'siconvlibrary routine.-fwide-exec-charset=charsetโ set the wide execution character set, used for wide string and character constants. The default is one ofUTF-32BE,UTF-32LE,UTF-16BE, orUTF-16LE, whichever matches the width ofwchar_tand the big-endian or little-endian byte order being used for code generation. Just like-fexec-charset,charsetcan be any encoding supported by the system'siconvlibrary routine โ but you'll run into problems with encodings that don't fit exactly inwchar_t. consider yourself warned bestie. ๐ญ-finput-charset=charsetโ set the input character set, used for translating from the input file's character set to the source character set GCC uses. If the locale doesn't specify it, or GCC can't get that info from the locale, the default isUTF-8. Either the locale or this command-line option can override it. Currently the command-line option wins if there's a conflict.charsetcan be any encoding supported by the system'siconvlibrary routine.-fpch-depsโ when using precompiled headers, this flag makes the dependency-output flags also list the files from the precompiled header's dependencies. If you don't specify it, only the precompiled header gets listed, not the files used to create it โ because those files aren't consulted when a precompiled header is used. ๐ง-fpch-preprocessโ this option lets you use a precompiled header together with-E. It inserts a special#pragma,#pragma GCC pch_preprocess "filename", into the output to mark where the precompiled header was found, plus its filename. When-fpreprocessedis in use, GCC recognizes this#pragmaand loads the PCH. This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It's switched on by-save-temps. You should not write this#pragmain your own code, but it's safe to edit the filename if the PCH file is available somewhere else. The filename may be absolute, or relative to GCC's current directory. โจ-fworking-directoryโ enables generation of linemarkers in the preprocessor output that let the compiler know the current working directory at the time of preprocessing. When it's enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. When that directory is present in the preprocessed input, GCC uses it as the directory emitted as the current working directory in some debugging information formats. This option is implicitly enabled if debugging information is enabled, but you can inhibit it with the negated form-fno-working-directory. If the-Pflag is present on the command line, this option has no effect, since no#linedirectives get emitted whatsoever. ๐-A predicate=answerโ make an assertion with the predicatepredicateand answeranswer. This form is preferred over the older form-A predicate(answer), which is still supported, because it doesn't use shell special characters. slay, no escaping needed. ๐-A -predicate=answerโ cancel an assertion with the predicatepredicateand answeranswer.-Cโ do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which get deleted along with the directive. ๐
heads up bestie ๐ซถ be ready for side effects when you use -C โ it makes the preprocessor treat comments as tokens in their own right. So like, a comment chilling at the start of what would've been a directive line? That line becomes an ordinary source line instead, because the first token on the line is no longer a #. ikr ๐
-CCโ do not discard comments, including during macro expansion. It's like-C, except comments contained within macros also get passed through to the output file where the macro is expanded. โจ
On top of all the side effects of -C, -CC also converts every C++-style comment inside a macro into a C-style comment. Why? So that later use of that macro doesn't inadvertently comment out the rest of the source line. ๐ญ The -CC option is generally used to support lint comments.
-Pโ inhibit generation of linemarkers in the output from the preprocessor. Lowkey useful when you're running the preprocessor on something that is not C code and it's getting sent to a program that might be confused by the linemarkers. ๐ฆ-traditional-traditional-cppโ try to imitate the behavior of pre-standard C preprocessors, as opposed to ISO C preprocessors. See the GNU CPP manual for the deets. ๐
ngl GCC does not otherwise attempt to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly.
-trigraphsโ support ISO C trigraphs. These are three-character sequences, all starting with??, that ISO C defines to stand for single characters. For example,??/stands for\, so'??/n'is a character constant for a newline. ๐
The nine trigraphs and their replacements are:
Trigraph: ??( ??) ??< ??> ??= ??/ ??' ??! ??-
Replacement: [ ] { } # \ ^ | ~
By default, GCC ignores trigraphs, but in standard-conforming modes it converts them. Peep the -std and -ansi options. ๐
-remapโ enable special code to work around file systems which only permit very short file names, such as MS-DOS. ๐-Hโ print the name of each header file used, in addition to other normal activities. Each name is indented to show how deep in the#includestack it is. Precompiled header files are also printed, even if they're found to be invalid; an invalid precompiled header file is printed with...xand a valid one with...!. ๐-dlettersโ says to make debugging dumps during compilation as specified by letters. The flags documented here are the ones relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and so are silently ignored. If you specify letters whose behavior conflicts, the result is undefined. ๐-dMโ instead of the normal output, generate a list of#definedirectives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no filefoo.h, the command
touch foo.h; cpp -dM foo.h
shows all the predefined macros. โจ
If you use -dM without the -E option, -dM is interpreted as a synonym for -fdump-rtl-mach.
-dDโ like-dMexcept in two respects: it does not include the predefined macros, and it outputs both the#definedirectives and the result of preprocessing. Both kinds of output go to the standard output file. ๐-dNโ like-dD, but emit only the macro names, not their expansions. ๐ฆ-dIโ output#includedirectives in addition to the result of preprocessing. ๐ธ-dUโ like-dDexcept that only macros that are expanded, or whose definedness is tested in preprocessor directives, are output; the output is delayed until the use or test of the macro; and#undefdirectives are also output for macros tested but undefined at the time. ๐
-fdebug-cppโ this option is only useful for debugging GCC. When used from CPP or with-E, it dumps debugging information about location maps. Every token in the output is preceded by the dump of the map its location belongs to. ๐
When used from GCC without -E, this option has no effect.
-Wp,optionโ you can use-Wp,optionto bypass the compiler driver and pass option directly through to the preprocessor. If option contains commas, it is split into multiple options at the commas. However, many options are modified, translated or interpreted by the compiler driver before being passed to the preprocessor, and-Wpforcibly bypasses this phase. The preprocessor's direct interface is undocumented and subject to change, so whenever possible you should avoid using-Wpand let the driver handle the options instead. ๐ฌ-Xpreprocessor optionโ pass option as an option to the preprocessor. You can use this to supply system-specific preprocessor options that GCC does not recognize. ๐ซถ
If you want to pass an option that takes an argument, you must use -Xpreprocessor twice, once for the option and once for the argument.
-no-integrated-cppโ perform preprocessing as a separate pass before compilation. By default, GCC performs preprocessing as an integrated part of input tokenization and parsing. If this option is provided, the appropriate language front end (cc1,cc1plus, orcc1objfor C, C++, and Objective-C, respectively) is instead invoked twice, once for preprocessing only and once for actual compilation of the preprocessed input. This option may be useful in conjunction with the-Bor-wrapperoptions to specify an alternate preprocessor or perform additional processing of the program source between normal preprocessing and compilation. ๐ง-flarge-source-filesโ adjust GCC to expect large source files, at the expense of slower compilation and higher memory usage. ๐
Specifically, GCC normally tracks both column numbers and line numbers within source files and it normally prints both of these numbers in diagnostics. However, once it has processed a certain number of source lines, it stops tracking column numbers and only tracks line numbers. This means that diagnostics for later lines do not include column numbers. It also means that options like -Wmisleading-indentation cease to work at that point, although the compiler prints a note if this happens. Passing -flarge-source-files significantly increases the number of source lines that GCC can process before it stops tracking columns. ๐
๐ Passing Options to the Assembler ๐
You can pass options to the assembler. periodt. ๐
-Wa,optionโ pass option as an option to the assembler. If option contains commas, it is split into multiple options at the commas. โจ-Xassembler optionโ pass option as an option to the assembler. You can use this to supply system-specific assembler options that GCC does not recognize. ๐ฆ
If you want to pass an option that takes an argument, you must use -Xassembler twice, once for the option and once for the argument.
๐ Options for Linking ๐
These options come into play when the compiler links object files into an executable output file. They are meaningless if the compiler is not doing a link step. ๐
object-file-nameโ a file name that does not end in a special recognized suffix is considered to name an object file or library. (Object files are distinguished from libraries by the linker according to the file contents.) If linking is done, these object files are used as input to the linker. ๐ซถ-c-S-Eโ if any of these options is used, then the linker is not run, and object file names should not be used as arguments. ๐-flinker-output=typeโ this option controls code generation of the link-time optimizer. By default the linker output is automatically determined by the linker plugin. For debugging the compiler and if incremental linking with a non-LTO object file is desired, it may be useful to control the type manually. ๐
If type is exec, code generation produces a static binary. In this case -fpic and -fpie are both disabled.
If type is dyn, code generation produces a shared library. In this case -fpic or -fPIC is preserved, but not enabled automatically. This allows to build shared libraries without position-independent code on architectures where this is possible, i.e. on x86. ๐
If type is pie, code generation produces an -fpie executable. This results in similar optimizations as exec except that -fpie is not disabled if specified at compilation time.
If type is rel, the compiler assumes that incremental linking is done. The sections containing intermediate code for link-time optimization are merged, pre-optimized, and output to the resulting object file. In addition, if -ffat-lto-objects is specified, binary code is produced for future non-LTO linking. The object file produced by incremental linking is smaller than a static library produced from the same object files. At link time the result of incremental linking also loads faster than a static library assuming that the majority of objects in the library are used. ๐
Finally nolto-rel configures the compiler for incremental linking where code generation is forced, a final binary is produced, and the intermediate code for later link-time optimization is stripped. When multiple object files are linked together the resulting code is better optimized than with link-time optimizations disabled (for example, cross-module inlining happens), but most of benefits of whole program optimizations are lost. ๐ญ
During the incremental link (by -r) the linker plugin defaults to rel. With current interfaces to GNU Binutils it is however not possible to incrementally link LTO objects and non-LTO objects into a single mixed object file. If any of object files in incremental link cannot be used for link-time optimization, the linker plugin issues a warning and uses nolto-rel. To maintain whole program optimization, it is recommended to link such objects into static library instead. Alternatively it is possible to use H.J. Lu's binutils with support for mixed objects. ๐
-fuse-ld=bfdโ use thebfdlinker instead of the default linker. โญ-fuse-ld=goldโ use thegoldlinker instead of the default linker. โญ-fuse-ld=lldโ bestie, this says use the LLVMlldlinker instead of the default linker. swapping out the whole linker? iconic ๐-fuse-ld=moldโ same energy, but for the Modern Linker (mold) instead of the default linker. she's fast, she's modern, she's here. โจ-llibrary,-l libraryโ search the library named library when linking. ok real talk: the second form, where the library is a separate argument, exists only for POSIX compliance and is not recommended. (POSIX said jump, we said how high ๐ซถ)
The -l option gets passed directly to the linker by GCC. so for exact deets, go read your linker's documentation. everything described below is about the GNU linker specifically.
The linker goes shopping through a standard list of directories looking for the library. those directories include several standard system directories plus whatever you add with -L.
So static libraries are archives of object files, and their filenames look like liblibrary.a. some targets also do shared libraries, which typically have names like liblibrary.so. if the linker finds both static and shared versions, she prefers linking with the shared one โ unless you used -static, in which case nope. ๐
โโ๏ธ
warning bestie: where you put this option in the command matters a lot. the linker searches and processes libraries and object files in the exact order you list them. so like,foo.o -lz bar.osearches libraryzafter filefoo.obut beforebar.o. and ifbar.orefers to functions inz, those functions may not get loaded. not me learning this the hard way ๐ญ
-lobjcโ you need this special case of the-loption to link an Objective-C or Objective-C++ program. special little snowflake, love that for her ๐-nostartfilesโ do not use the standard system startup files when linking. the standard system libraries still get used normally, unless-nostdlib,-nolibc, or-nodefaultlibsis also in play.-nodefaultlibsโ do not use the standard system libraries when linking. only the libraries you specify get passed to the linker, and options that specify linkage of the system libraries โ like-static-libgccor-shared-libgccโ are straight up ignored. the standard startup files are still used normally, unless-nostartfilesis used.
Also heads up: the compiler may generate calls to memcmp, memset, memcpy and memmove. these are usually resolved by entries in libc. so when you use this option, you gotta supply those entry points through some other mechanism. don't forget, she will notice. ๐
-nolibcโ do not use the C library or system libraries tightly coupled with it when linking. you still link with the startup files, libgcc, or toolchain-provided language support libraries like libgnat, libgfortran or libstdc++ โ unless you also used options that prevent their inclusion. this typically removes-lcfrom the link command line, plus the system libraries that normally tag along and become meaningless once you're assuming there's no C library โ for example-lpthreador-lmin some configurations. this one is intended for bare-board targets when there is genuinely no C library available. bare metal vibes only ๐ฆ-nostdlibโ do not use the standard system startup files or libraries when linking. no startup files, and only the libraries you specify get passed to the linker. options specifying linkage of the system libraries, like-static-libgccor-shared-libgcc, are ignored. periodt.
Again: the compiler may generate calls to memcmp, memset, memcpy and memmove. these are usually resolved by entries in libc, and these entry points should be supplied through some other mechanism when this option is specified.
One of the standard libraries that -nostdlib and -nodefaultlibs bypass is libgcc.a โ a library of internal subroutines that GCC uses to overcome shortcomings of particular machines, or special needs for some languages.
And in most cases, you need libgcc.a even when you're trying to avoid other standard libraries. so like, when you specify -nostdlib or -nodefaultlibs, you should usually also specify -lgcc. this makes sure you have no unresolved references to internal GCC library subroutines. (one example of such an internal subroutine is __main, which is used to make sure C++ constructors get called.) ๐
-e entry,--entry=entryโ specify that the program entry point is entry. the argument gets interpreted by the linker, and the GNU linker accepts either a symbol name or an address. your call bestie ๐ซถ-pieโ produce a dynamically linked position independent executable on targets that support it. for predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you use this linker option. matchy-matchy or chaos, your pick ๐-no-pieโ don't produce a dynamically linked position independent executable. that's it, that's the whole thing.-static-pieโ produce a static position independent executable on targets that support it. a static position independent executable is similar to a static executable, but can be loaded at any address without a dynamic linker. and same rule as-pie: for predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you use this linker option.-pthreadโ link with the POSIX threads library. this option is supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets. on some targets this option also sets flags for the preprocessor, so use it consistently for both compilation and linking. no half-and-half, bestie ๐ฅ-rโ produce a relocatable object as output. also known as partial linking. lowkey a niche queen.-rdynamicโ pass the flag-export-dynamicto the ELF linker, on targets that support it. this tells the linker to add all symbols, not only the used ones, to the dynamic symbol table. you need this for some uses ofdlopen, or to allow obtaining backtraces from within a program. very "for the lore" energy. โจ-sโ remove all symbol table and relocation information from the executable. she's on a diet, she's lean, she's mysterious. ๐-staticโ on systems that support dynamic linking, this overrides-pieand prevents linking with the shared libraries. on other systems, this option has no effect. soz to those systems.-sharedโ produce a shared object which can then be linked with other objects to form an executable. not all systems support this option. and for predictable results, you must also specify the same set of options used for compilation (-fpic,-fPIC, or model suboptions) when you specify this linker option.[1]-shared-libgcc,-static-libgccโ on systems that provide libgcc as a shared library, these options force the use of either the shared or static version, respectively. if no shared version of libgcc was built when the compiler was configured, these options have no effect. (rip to those options, they tried ๐ญ)
There are several situations where an application should use the shared libgcc instead of the static version. the most common one is when the application wants to throw and catch exceptions across different shared libraries. in that case, each of the libraries and the application itself should use the shared libgcc.
So therefore, the G++ driver automatically adds -shared-libgcc whenever you build a shared library or a main executable โ because C++ programs typically use exceptions, so this is just the right thing to do. ๐
If instead you use the GCC driver to create shared libraries, you may find they're not always linked with the shared libgcc. here's the tea: if GCC finds, at its configuration time, that you have a non-GNU linker, or a GNU linker that does not support option --eh-frame-hdr, it links the shared version of libgcc into shared libraries by default. otherwise, it takes advantage of the linker and optimizes away the linking with the shared version of libgcc, linking with the static version of libgcc by default. this lets exceptions propagate through such shared libraries without incurring relocation costs at library load time. slay, efficiency queen.
However โ and this is the big however โ if a library or main executable is supposed to throw or catch exceptions, you must link it using the G++ driver, or using the option -shared-libgcc, such that it's linked with the shared libgcc. no shortcuts bestie, she will catch you ๐ซถ
-static-libasanโ when the-fsanitize=addressoption is used to link a program, the GCC driver automatically links against libasan. if libasan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libasan. the-static-libasanoption directs the GCC driver to link libasan statically, without necessarily linking other libraries statically. one static at a time, we're not monsters. โจ-static-libtsanโ when the-fsanitize=threadoption is used to link a program, the GCC driver automatically links against libtsan. if libtsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libtsan. the-static-libtsanoption directs the GCC driver to link libtsan statically, without necessarily linking other libraries statically.-static-liblsanโ when the-fsanitize=leakoption is used to link a program, the GCC driver automatically links against liblsan. if liblsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of liblsan. the-static-liblsanoption directs the GCC driver to link liblsan statically, without necessarily linking other libraries statically.-static-libubsanโ when the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links against libubsan. if libubsan is available as a shared library, and the-staticoption is not used, then this links against the shared version of libubsan. the-static-libubsanoption directs the GCC driver to link libubsan statically, without necessarily linking other libraries statically. (yes the pattern continues, they're a family, a whole squad ๐ง)-static-libstdc++โ when theg++program is used to link a C++ program, it normally automatically links against libstdc++. if libstdc++ is available as a shared library, and the-staticoption is not used, then this links against the shared version of libstdc++. that's normally fine, no notes. however, it is sometimes useful to freeze the version of libstdc++ used by the program without going all the way to a fully static link. the-static-libstdc++option directs theg++driver to link libstdc++ statically, without necessarily linking other libraries statically. it's giving โจcontrolled chaosโจ-symbolicโ bind references to global symbols when building a shared object. warn about any unresolved references (unless overridden by the link editor option-Xlinker -z -Xlinker defs). only a few systems support this option, so like... rare queen, not everyone can sit with her ๐-T scriptโ bestie, this one handsscriptover as the linker script โจ it's supported by most systems that use the GNU linker. Heads up though: on some targets, like bare-board targets that don't have an operating system at all,-Tmay be required when linking, otherwise you get references to undefined symbols and everything is giving chaos ๐-Xlinker optionโ passesoptionas an option to the linker ๐ซถ you use this to sneak in system-specific linker options that GCC itself doesn't recognize. So valid, so useful.
Now listen, because this part trips people up: if you want to pass an option that takes a separate argument, you have to use -Xlinker twice โ once for the option, once for the argument. Like, to pass -assert definitions, you literally write:
-Xlinker -assert -Xlinker definitions
And it does not work to write -Xlinker "-assert definitions", because that passes the entire string as a single argument, which is not what the linker expects ๐ no cap.
When you're using the GNU linker, it's usually more convenient to pass arguments to linker options using the option=value syntax than as separate arguments. For example, you can specify -Xlinker -Map=output.map rather than -Xlinker -Map -Xlinker output.map ๐
other linkers may not support this syntax for command-line options though, so vibe check your linker first.
-Wl,optionโ passesoptionas an option to the linker. Ifoptioncontains commas, it gets split into multiple options at the commas ๐ you can use this syntax to pass an argument to the option too. For example,-Wl,-Map,output.mappasses-Map output.mapto the linker. When using the GNU linker, you can also get the same effect with-Wl,-Map=output.mapโจ
NOTE: In Ubuntu 8.10 and later versions, forLDFLAGS, the option-Wl,-z,relrois used. To disable, use-Wl,-z,norelro. ๐ write that down bestie.
-u symbolโ pretend the symbolsymbolis undefined, to force linking of library modules to define it ๐ you can use-umultiple times with different symbols to force loading of additional library modules. Iconic behaviour honestly.-z keywordโ-zis passed directly on to the linker along with the keywordkeyword๐ see the section in the documentation of your linker for permitted values and their meanings (that part is on your linker's docs, not GCC's, iykyk).
๐ธ Options for Directory Search ๐ธ
These options specify directories to search for header files, for libraries and for parts of the compiler ๐ฆ directory drama, but make it useful.
-I dir-iquote dir-isystem dir-idirafter dir
Add the directory dir to the list of directories to be searched for header files during preprocessing โจ if dir begins with = or $SYSROOT, then the = or $SYSROOT is replaced by the sysroot prefix; see --sysroot and -isysroot.
Directories specified with -iquote apply only to the quote form of the directive, #include "file". Directories specified with -I, -isystem, or -idirafter apply to lookup for both the #include "file" and #include <file> directives ๐
You can specify any number or combination of these options on the command line to search for header files in several directories. The lookup order is as follows, bestie, in order:
- For the quote form of the include directive, the directory of the current file is searched first.
- For the quote form of the include directive, the directories specified by
-iquoteoptions are searched in left-to-right order, as they appear on the command line. - Directories specified with
-Ioptions are scanned in left-to-right order. - Directories specified with
-isystemoptions are scanned in left-to-right order. - Standard system directories are scanned.
- Directories specified with
-idirafteroptions are scanned in left-to-right order.
You can use -I to override a system header file, substituting your own version, since these directories are searched before the standard system header file directories ๐ however, you should not use this option to add directories that contain vendor-supplied system header files; use -isystem for that instead ๐ซถ
The -isystem and -idirafter options also mark the directory as a system directory, so that it gets the same special treatment that is applied to the standard system directories โจ
If a standard system include directory, or a directory specified with -isystem, is also specified with -I, the -I option is ignored ๐ญ the directory is still searched but as a system directory at its normal position in the system include chain. This is to ensure that GCC's procedure to fix buggy system headers and the ordering for the #include_next directive are not inadvertently changed. If you really, truly need to change the search order for system directories, use the -nostdinc and/or -isystem options, periodt.
-I-โ split the include path ๐ this option has been deprecated bestie, please use-iquoteinstead for-Idirectories before the-I-and remove the-I-option.
Any directories specified with -I options before -I- are searched only for headers requested with #include "file"; they are not searched for #include <file>. If additional directories are specified with -I options after the -I-, those directories are searched for all #include directives.
In addition, -I- inhibits the use of the directory of the current file directory as the first search directory for #include "file". There is no way to override this effect of -I- ๐ it's giving unhinged but that's just how it is.
-iprefix prefixโ specifyprefixas the prefix for subsequent-iwithprefixoptions ๐ if the prefix represents a directory, you should include the final/.-iwithprefix dir-iwithprefixbefore dir
Append dir to the prefix specified previously with -iprefix, and add the resulting directory to the include search path โจ -iwithprefixbefore puts it in the same place -I would; -iwithprefix puts it where -idirafter would. Cute, right?
-isysroot dirโ this option is like the--sysrootoption, but applies only to header files (except for Darwin targets, where it applies to both header files and libraries) ๐ see the--sysrootoption for more information.-imultilib dirโ usediras a subdirectory of the directory containing target-specific C++ headers ๐-nostdincโ do not search the standard system directories for header files ๐ซ only the directories explicitly specified with-I,-iquote,-isystem, and/or-idirafteroptions (and the directory of the current file, if appropriate) are searched. That's it, that's the list.-nostdinc++โ do not search for header files in the C++-specific standard directories, but do still search the other standard directories ๐ฆ (this option is used when building the C++ library.)-iplugindir=dirโ set the directory to search for plugins that are passed by-fplugin=nameinstead of-fplugin=path/name.soโจ this option is not meant to be used by the user, but only passed by the driver. So like, hands off bestie ๐-Ldirโ add directorydirto the list of directories to be searched for-l๐-Bprefixโ this option specifies where to find the executables, libraries, include files, and data files of the compiler itself ๐
The compiler driver program runs one or more of the subprograms cpp, cc1, as and ld. It tries prefix as a prefix for each program it tries to run, both with and without machine/version/ for the corresponding target machine and compiler version.
For each subprogram to be run, the compiler driver first tries the -B prefix, if any. If that name is not found, or if -B is not specified, the driver tries two standard prefixes, /usr/lib/gcc/ and /usr/local/lib/gcc/. If neither of those results in a file name that is found, the unmodified program name is searched for using the directories specified in your PATH environment variable ๐
The compiler checks to see if the path provided by -B refers to a directory, and if necessary it adds a directory separator character at the end of the path.
-B prefixes that effectively specify directory names also apply to libraries in the linker, because the compiler translates these options into -L options for the linker. They also apply to include files in the preprocessor, because the compiler translates these options into -isystem options for the preprocessor. In this case, the compiler appends include to the prefix.
The runtime support file libgcc.a can also be searched for using the -B prefix, if needed. If it is not found there, the two standard prefixes above are tried, and that is all. The file is left out of the link if it is not found by those means ๐ญ
Another way to specify a prefix much like the -B prefix is to use the environment variable GCC_EXEC_PREFIX โจ
As a special kludge, if the path provided by -B is [dir/]stageN/, where N is a number in the range 0 to 9, then it is replaced by [dir/]include. This is to help with boot-strapping the compiler ๐
-no-canonical-prefixesโ do not expand any symbolic links, resolve references to/../or/./, or make the path absolute when generating a relative prefix ๐--sysroot=dirโ usediras the logical root directory for headers and libraries ๐ธ for example, if the compiler normally searches for headers in/usr/includeand libraries in/usr/lib, it instead searchesdir/usr/includeanddir/usr/lib.
If you use both this option and the -isysroot option, then the --sysroot option applies to libraries, but the -isysroot option applies to header files.
The GNU linker (beginning with version 2.16) has the necessary support for this option ๐ if your linker does not support this option, the header file aspect of --sysroot still works, but the library aspect does not ๐
--no-sysroot-suffixโ for some targets, a suffix is added to the root directory specified with--sysroot, depending on the other options used, so that headers may for example be found indir/suffix/usr/includeinstead ofdir/usr/include๐ฆ this option disables the addition of such a suffix.
๐ Options for Code Generation Conventions ๐
These machine-independent options control the interface conventions used in code generation โจ interface lore, basically.
Most of them have both positive and negative forms; the negative form of -ffoo is -fno-foo ๐
in the table below, only one of the forms is listed โ the one that is not the default. You can figure out the other form by either removing no- or adding it. Easy, bestie ๐ซถ
-fstack-reuse=reuse-levelโ bestie, this one controls whether the compiler gets to reuse stack space for your user-declared local/auto variables and for the temporaries the compiler cooked up itself.reuse_levelcan beall,named_vars, ornone.allturns stack reuse on for everything โ every local and every temp.named_varsonly allows reuse for the user-defined locals that actually have names.nonekills stack reuse entirely, no takebacks. The default isall.
You need this option when your program does the spicy thing: extending the lifetime of a scoped local variable, or a compiler-generated temporary, past the end point that the language says it should die at. Here's the tea โ when a variable's lifetime ends, and that variable lives in memory, the optimizing compiler is free to reuse its stack space for other temporaries or scoped locals whose live range doesn't overlap with it. And legacy code that extends local lifetime? Yeah, it's probably gonna break with the stack reuse optimization. Not me warning you fr fr. ๐
For example,
int *p;
{
int local1;
p = &local1;
local1 = 10;
....
}
{
int local2;
local2 = 20;
...
}
if (*p == 10) // out of scope use of local1
{
}
Another example:
struct A
{
A(int k) : i(k), j(k) { }
int i;
int j;
};
A *ap;
void foo(const A& ar)
{
ap = &ar;
}
void bar()
{
foo(A(10)); // temp object's lifetime ends when foo returns
{
A a(20);
....
}
ap->i+= 10; // ap references out of scope temp whose space
// is reused with a. What is the value of ap->i?
}
Okay so the lifetime of a compiler-generated temporary is well defined by the C++ standard, that part's chill. When a temporary's lifetime ends, and if it lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped locals whose live range doesn't overlap. However โ some legacy code lowkey relies on how older compilers behaved, where temporaries' stack space was not reused, and the aggressive stack reuse can lead to runtime errors. That's the whole reason this option exists: to control the temporary stack reuse optimization. ๐
-ftrapvโ this one makes GCC generate traps for signed overflow onaddition,subtraction, andmultiplicationoperations. Catch it in the act, periodt.
And here's the messy part: -ftrapv and -fwrapv override each other. So if you put -ftrapv -fwrapv on the command-line, -fwrapv is the one that wins. Note that only active options override, so putting -ftrapv -fwrapv -fno-wrapv on the command-line results in -ftrapv being effective. The vibes are giving โจlast one standingโจ.
-fwrapvโ this option tells the compiler to assume that signed arithmetic overflow ofaddition,subtractionandmultiplicationwraps around using twos-complement representation. This flag enables some optimizations and disables others, so it's a whole trade-off moment.
Same override drama as above: -ftrapv and -fwrapv override each other, so -ftrapv -fwrapv on the command-line means -fwrapv is effective. And again, only active options override, so -ftrapv -fwrapv -fno-wrapv on the command-line leaves -ftrapv effective.
-fwrapv-pointerโ this one instructs the compiler to assume that pointer arithmetic overflow onadditionandsubtractionwraps around using twos-complement representation. Heads up though: this flag disables some optimizations which assume pointer overflow is invalid. Choices were made. ๐ซถ-fstrict-overflowโ this option implies-fno-wrapv -fno-wrapv-pointer, and when negated it implies-fwrapv -fwrapv-pointer. That's it, that's the whole thing, iykyk.-fexceptionsโ enables exception handling, bestie! It generates the extra code needed to propagate exceptions. For some targets this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead โ though it doesn't affect execution, so your runtime's fine.
If you don't specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that don't normally require it. But you may need to turn it on when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also want to disable it if you're compiling older C++ programs that don't use exception handling. Situational queen. ๐
-fnon-call-exceptionsโ generates code that allows trapping instructions to throw exceptions. Big caveat though: this requires platform-specific runtime support that does not exist everywhere. Moreover, it only allows trapping instructions to throw exceptions, i.e. memory references or floating-point instructions. It does not allow exceptions to be thrown from arbitrary signal handlers such asSIGALRM. This enables-fexceptions. ๐ธ-fdelete-dead-exceptionsโ treats instructions that may throw exceptions but don't otherwise contribute to the program's execution as fair game to be optimized away. This doesn't affect calls to functions, except those with thepureorconstattributes.
This option is enabled by default for the Ada and C++ compilers, as permitted by the language specifications. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. ๐
-funwind-tablesโ similar to-fexceptions, except it just generates any needed static data, and does not affect the generated code in any other way. You normally do not need to enable this option โ instead, a language processor that needs this handling enables it on your behalf. Let the language processor handle its own business. ๐-fasynchronous-unwind-tablesโ generates the unwind table in DWARF format, if it's supported by the target machine. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events โ like a debugger or a garbage collector. Exact at every single boundary, no cap. โจ-fno-gnu-uniqueโ okay so on systems with a recent GNU assembler and C library, the C++ compiler uses theSTB_GNU_UNIQUEbinding to make sure that definitions of template static data members and static local variables in inline functions stay unique even in the presence ofRTLD_LOCAL. Why does that matter? Because it's necessary to avoid problems with a library used by two differentRTLD_LOCALplugins depending on a definition in one of them โ and therefore disagreeing with the other one about the binding of the symbol. Whole lotta drama for one symbol, honestly.
But plot twist: this causes dlclose to be ignored for affected DSOs. So if your program relies on reinitialization of a DSO via dlclose and dlopen, you can use -fno-gnu-unique. Fix your life with one flag. ๐
-fpcc-struct-returnโ returnsshortstructandunionvalues in memory like longer ones, rather than in registers. This convention is less efficient, but it has the advantage of allowing intercallability between GCC-compiled files and files compiled with other compilers โ particularly the Portable C Compiler (pcc). Networking era, we love to see it.
The precise convention for returning structures in memory depends on the target configuration macros.
Short structures and unions are those whose size and alignment match that of some integer type.
Warning: code compiled with the-fpcc-struct-returnswitch is not binary compatible with code compiled with the-freg-struct-returnswitch. Use it to conform to a non-default application binary interface.
-freg-struct-returnโ returnsstructandunionvalues in registers when possible. For small structures this is more efficient than-fpcc-struct-return. Slay, performance. ๐ฅ
If you specify neither -fpcc-struct-return nor -freg-struct-return, GCC defaults to whichever convention is standard for the target. If there is no standard convention, GCC defaults to -fpcc-struct-return โ except on targets where GCC is the principal compiler. In those cases, we can choose the standard, and we chose the more efficient register return alternative. Main character decision making, periodt.
Warning: code compiled with the-freg-struct-returnswitch is not binary compatible with code compiled with the-fpcc-struct-returnswitch. Use it to conform to a non-default application binary interface.
-fshort-enumsโ allocates to anenumtype only as many bytes as it needs for the declared range of possible values. Specifically, theenumtype becomes equivalent to the smallest integer type that has enough room. Minimalist queen, she doesn't overpack. ๐
Warning: the -fshort-enums switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
-fshort-wcharโ overrides the underlying type forwchar_tto beshort unsigned intinstead of the default for the target. This option is useful for building programs to run under WINE. ๐ท
Warning: the -fshort-wchar switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface.
-fcommonโ in C code, this option controls the placement of global variables defined without an initializer, known as tentative definitions in the C standard. Tentative definitions are distinct from declarations of a variable with theexternkeyword โ those don't allocate storage, bestie, don't get it twisted.
The default is -fno-common, which specifies that the compiler places uninitialized global variables in the BSS section of the object file. This inhibits the merging of tentative definitions by the linker, so you get a multiple-definition error if the same variable is accidentally defined in more than one compilation unit. Which, honestly, is doing you a favor. ๐ญ
The -fcommon places uninitialized global variables in a common block. This allows the linker to resolve all tentative definitions of the same variable in different compilation units to the same object, or to a non-tentative definition. This behavior is inconsistent with C++, and on many targets it implies a speed and code size penalty on global variable references. It is mainly useful to enable legacy code to link without errors. Legacy code stays winning, I guess. ๐
-fno-identโ ignores the#identdirective. Short, sweet, iconic.-finhibit-size-directiveโ bestie, this one says don't emit that.sizeassembler directive, and don't emit anything else that would cause drama if a function gets split down the middle with its two halves yeeted to locations far apart in memory. It's used when compilingcrtstuff.c, and you should not need to use it for anything else. periodt. ๐-fverbose-asmโ okay so this one sprinkles extra commentary into the generated assembly so it's actually readable to a human. Genuinely only useful for the girlies who actually need to read the generated assembly (like, perhaps while debugging the compiler itself, iconic behaviour).
-fno-verbose-asm, the default, omits all that extra info, which is handy when you're comparing two assembler files. ๐ซถ
The added comments include:
- information on the compiler version and command-line options,
- the source code lines associated with the assembly instructions, in the form
FILENAME:LINENUMBER:CONTENT OF LINE, - hints on which high-level expressions correspond to the various assembly instruction operands.
For example, given this C source file:
int test (int n)
{
int i;
int total = 0;
for (i = 0; i < n; i++)
total += i * i;
return total;
}
compiling to (x86_64) assembly via -S and emitting the result direct to stdout via -o -
gcc -S test.c -fverbose-asm -Os -o -
gives output similar to this:
.file "test.c"
# GNU C11 (GCC) version 7.0.0 20160809 (experimental) (x86_64-pc-linux-gnu)
[...snip...]
# options passed:
[...snip...]
.text
.globl test
.type test, @function
test:
.LFB0:
.cfi_startproc
# test.c:4: int total = 0;
xorl %eax, %eax # <retval>
# test.c:6: for (i = 0; i < n; i++)
xorl %edx, %edx # i
.L2:
# test.c:6: for (i = 0; i < n; i++)
cmpl %edi, %edx # n, i
jge .L5 #,
# test.c:7: total += i * i;
movl %edx, %ecx # i, tmp92
imull %edx, %ecx # i, tmp92
# test.c:6: for (i = 0; i < n; i++)
incl %edx # i
# test.c:7: total += i * i;
addl %ecx, %eax # tmp92, <retval>
jmp .L2 #
.L5:
# test.c:10: }
ret
.cfi_endproc
.LFE0:
.size test, .-test
.ident "GCC: (GNU) 7.0.0 20160809 (experimental)"
.section .note.GNU-stack,"",@progbits
The comments are intended for humans rather than machines, so the precise format of the comments is subject to change. don't come for me, I'm just the messenger. ๐ญ
-frecord-gcc-switchesโ this switch makes the command line you used to invoke the compiler get recorded into the object file that's being created. It's only implemented on some targets, and the exact format of the recording depends on the target and the binary file format, but usually it takes the form of a section containing ASCII text. It's related to-fverbose-asm, except that one only records info in the assembler output file as comments โ so it never reaches the object file. See also-grecord-gcc-switchesfor another way of storing compiler options into the object file. โจ-fpicโ generate position-independent code (PIC) suitable for use in a shared library, if it's supported for the target machine. Code like this accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (heads up: the dynamic loader is not part of GCC โ it's part of the operating system). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker telling you that-fpicdoes not work; in that case, recompile with-fPICinstead. (These maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit.)
Position-independent code requires special support, and therefore works only on certain machines. For the x86, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always position-independent.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 1.
-fPICโ if it's supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on AArch64, m68k, PowerPC and SPARC. ๐ฅ
Position-independent code requires special support, and therefore works only on certain machines.
When this flag is set, the macros "__pic__" and "__PIC__" are defined to 2.
-fpie-fPIEโ these options are similar to-fpicand-fPIC, but the generated position-independent code can only be linked into executables. Usually these options are used to compile code that will be linked using the-pieGCC option.
-fpie and -fPIE both define the macros "__pie__" and "__PIE__". The macros have the value 1 for -fpie and 2 for -fPIE.
-fno-pltโ do not use the PLT for external function calls in position-independent code. Instead, load the callee address at call sites from the GOT and branch to it. This gives more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures like 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives the compiler more register allocation freedom. Lazy binding requires use of the PLT; with-fno-pltall external symbols are resolved at load time.
Alternatively, the function attribute "noplt" can be used to avoid calls through the PLT for specific external functions.
In position-dependent code, a few targets also convert calls to functions that are marked to not use the PLT to use the GOT instead.
-fno-jump-tablesโ do not use jump tables forswitchstatements even where it would be more efficient than other code generation strategies. This option is of use in conjunction with-fpicor-fPICfor building code that forms part of a dynamic linker and cannot reference the address of a jump table. On some targets, jump tables don't require a GOT and this option is not needed. ๐ฆ-fno-bit-testsโ do not use bit tests forswitchstatements even where it would be more efficient than other code generation strategies.-ffixed-regโ treat the register named reg as a fixed register; generated code should never refer to it (except perhaps as a stack pointer, frame pointer or in some other fixed role).
reg must be the name of a register. The register names accepted are machine-specific and are defined in the "REGISTER_NAMES" macro in the machine description macro file.
This flag does not have a negative form, because it specifies a three-way choice. ok so there's no -fno-fixed-reg, don't even try it. ๐
-fcall-used-regโ treat the register named reg as an allocable register that is clobbered by function calls. It may be allocated for temporaries or variables that do not live across a call. Functions compiled this way do not save and restore the register reg.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results. like, fr fr, do not. ๐ญ
This flag does not have a negative form, because it specifies a three-way choice.
-fcall-saved-regโ treat the register named reg as an allocable register saved by functions. It may be allocated even for temporaries or variables that live across a call. Functions compiled this way save and restore the register reg if they use it.
It is an error to use this flag with the frame pointer or stack pointer. Use of this flag for other registers that have fixed pervasive roles in the machine's execution model produces disastrous results.
A different sort of disaster results from the use of this flag for a register in which function values may be returned.
This flag does not have a negative form, because it specifies a three-way choice.
-fpack-struct[=n]โ without a value specified, pack all structure members together without holes. When a value n is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment โ that is, objects with default alignment requirements larger than this are output potentially unaligned at the next fitting location.
Warning: the -fpack-struct switch causes GCC to generate code that is not binary compatible with code generated without that switch. Additionally, it makes the code suboptimal. Use it to conform to a non-default application binary interface. slay but only if you must. ๐
-fleading-underscoreโ this option and its counterpart,-fno-leading-underscore, forcibly change the way C symbols are represented in the object file. One use is to help link with legacy assembly code.
Warning: the -fleading-underscore switch causes GCC to generate code that is not binary compatible with code generated without that switch. Use it to conform to a non-default application binary interface. Not all targets provide complete support for this switch.
-ftls-model=modelโ alter the thread-local storage model to be used. The model argument should be one ofglobal-dynamic,local-dynamic,initial-execorlocal-exec. Note that the choice is subject to optimization: the compiler may use a more efficient model for symbols not visible outside of the translation unit, or if-fpicis not given on the command line.
The default without -fpic is initial-exec; with -fpic the default is global-dynamic. ๐ธ
-ftrampolinesโ for targets that normally need trampolines for nested functions, this makes them always generate trampolines instead of using descriptors. For targets that don't need them, like HP-PA or IA-64, it does literally nothing. bestie, no cap.
A trampoline is a tiny piece of code created at run time on the stack when the address of a nested function is taken, and it's used to call the nested function indirectly. So yeah, it requires the stack to be made executable for the program to work properly. important!
-fno-trampolines is enabled by default on a language-by-language basis to let the compiler avoid generating them if it computes that this is safe, and replace them with descriptors. Descriptors are made up of data only, but the generated code must be prepared to deal with them. As of this writing, -fno-trampolines is enabled by default only for Ada.
Moreover, code compiled with -ftrampolines and code compiled with -fno-trampolines are not binary compatible if nested functions are present. This option must therefore be used on a program-wide basis and be manipulated with extreme care. like, extreme care extreme care.
For languages other than Ada, the -ftrampolines and -fno-trampolines options currently have no effect, and trampolines are always generated on platforms that need them for nested functions.
-fvisibility=[default|internal|hidden|protected]โ sets the default ELF image symbol visibility to the specified option. All symbols are marked with this unless overridden within the code. Using this feature can very substantially improve linking and load times of shared object libraries, produce more optimized code, provide near-perfect API export, and prevent symbol clashes. It is strongly recommended that you use this in any shared objects you distribute.
Despite the nomenclature, default always means public โ i.e., available to be linked against from outside the shared object. protected and internal are pretty useless in real-world usage, so the only other commonly used option is hidden. The default if -fvisibility isn't specified is default, i.e., make every symbol public.
A good explanation of the benefits offered by ensuring ELF symbols have the correct visibility is given by How To Write Shared Libraries by Ulrich Drepper (which can be found at <https://www.akkadia.org/drepper/>) โ however a superior solution made possible by this option to marking things hidden when the default is public is to make the default hidden and mark things public. This is the norm with DLLs on Windows, and with -fvisibility=hidden and "__attribute__ ((visibility("default")))" instead of "__declspec(dllexport)" you get almost identical semantics with identical syntax. This is a great boon to those working with cross-platform projects. slay cross-platform queen
For those adding visibility support to existing code, you may find "#pragma GCC visibility" of use. This works by you enclosing the declarations you wish to set visibility for with (for example) "#pragma GCC visibility push(hidden)" and "#pragma GCC visibility pop". Bear in mind that symbol visibility should be viewed as part of the API interface contract and thus all new code should always specify visibility when it is not the default; i.e., declarations only for use within the local DSO should always be marked explicitly as hidden as so to avoid PLT indirection overheads โ making this abundantly clear also aids readability and self-documentation of the code. Note that due to ISO C++ specification requirements, "operator new" and "operator delete" must always be of default visibility.
Be aware that headers from outside your project, in particular system headers and headers from any other library you use, may not be expecting to be compiled with visibility other than the default. You may need to explicitly say "#pragma GCC visibility push(default)" before including any such headers.
"extern" declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with no modifications. However, this means that calls to "extern" functions with no explicit visibility use the PLT, so it is more effective to use "__attribute ((visibility))" and/or "#pragma GCC visibility" to tell the compiler which "extern" declarations should be treated as hidden.
Note that -fvisibility does affect C++ vague linkage entities. This means that, for instance, an exception class that is thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs.
An overview of these techniques, their benefits and how to use them is at <https://gcc.gnu.org/wiki/Visibility>.
-fstrict-volatile-bitfieldsโ use this if accesses to volatile bit-fields (or other structure fields, although the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to a natural alignment if possible. For example, targets with memory-mapped peripheral registers might require all such accesses to be 16 bits wide; with this flag you can declare all peripheral bit-fields as"unsigned short"(assuming short is 16 bits on these targets) to force GCC to use 16-bit accesses instead of, perhaps, a more efficient 32-bit access.
If this option is disabled, the compiler uses the most efficient instruction. In the previous example, that might be a 32-bit load instruction, even though that accesses bytes that do not contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated.
In some cases, such as when the "packed" attribute is applied to a structure field, it may not be possible to access the field with a single read or write that is correctly aligned for the target machine. In this case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time.
Note: Due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It is therefore recommended to define all bits of the field's type as bit-field members.
The default value of this option is determined by the application binary interface for the target processor.
-fsync-libcallsโ controls whether any out-of-line instance of the"__sync"family of functions may be used to implement the C++11"__atomic"family of functions.
The default value of this option is enabled, thus the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library.
๐ฉโ๐ป GCC Developer Options ๐ฉโ๐ป
This section describes command-line options that are primarily of interest to GCC developers, including options to support compiler testing and investigation of compiler bugs and compile-time performance problems. This includes options that produce debug dumps at various points in the compilation; that print statistics such as memory use and execution time; and that print information about GCC's configuration, such as where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. like, for real, unless you're deep in the compiler sauce.
Many developer options that cause GCC to dump output to a file take an optional =filename suffix. You can specify stdout or - to dump to standard output, and stderr for standard error.
If =filename is omitted, a default dump file name is constructed by concatenating the base dump file name, a pass number, phase letter, and pass name. The base dump file name is the name of output file produced by the compiler if explicitly specified and not an executable; otherwise it is the source file name. The pass number is determined by the order passes are registered with the compiler's pass manager. This is generally the same as the order of execution, but passes registered by plugins, target-specific passes, or passes that are otherwise registered late are numbered higher than the pass named final, even if they are executed earlier. The phase letter is one of i (inter-procedural analysis), l (language-specific), r (RTL), or t (tree). The files are created in the directory of the output file.
-fcallgraph-info,-fcallgraph-info=MARKERSโ makes the compiler output callgraph information for the program, on a per-object-file basis. The information is generated in the common VCG format. It can be decorated with additional, per-node and/or per-edge information, if a list of comma-separated markers is additionally specified. When the"su"marker is specified, the callgraph is decorated with stack usage information; it is equivalent to-fstack-usage. When the"da"marker is specified, the callgraph is decorated with information about dynamically allocated objects.
When compiling with -flto, no callgraph information is output along with the object file. At LTO link time, -fcallgraph-info may generate multiple callgraph information files next to intermediate LTO output files.
-dletters,-fdump-rtl-pass,-fdump-rtl-pass=filenameโ says to make debugging dumps during compilation at times specified by letters. This is used for debugging the RTL-based passes of the compiler.
Some -dletters switches have different meaning when -E is used for preprocessing.
Debug dumps can be enabled with a -fdump-rtl switch or some -d option letters. Here are the possible letters for use in pass and letters, and their meanings:
-fdump-rtl-alignmentsโ dump after branch alignments have been computed.-fdump-rtl-asmconsโ dump after fixing rtl statements that have unsatisfied in/out constraints.-fdump-rtl-auto_inc_decโ dump after auto-inc-dec discovery. This pass is only run on architectures that have auto inc or auto dec instructions.-fdump-rtl-barriersโ dump after cleaning up the barrier instructions.-fdump-rtl-bbpartโ dump after partitioning hot and cold basic blocks.-fdump-rtl-bbroโ dump after block reordering.-fdump-rtl-btl1/-fdump-rtl-btl2โ these enable dumping after the two branch target load optimization passes.-fdump-rtl-bypassโ dump after jump bypassing and control flow optimizations.
-fdump-rtl-combineโ dumps everything right after the RTL instruction combination pass does its thing. โจ-fdump-rtl-compgotosโ dumps after the computed gotos get duplicated. ๐-fdump-rtl-ce1,-fdump-rtl-ce2,-fdump-rtl-ce3โ bestie these three enable dumping after the three if conversion passes. all three of them. yes queen, three passes. ๐-fdump-rtl-cprop_hardregโ dumps after hard register copy propagation. ๐-fdump-rtl-csaโ dumps after combining stack adjustments.-fdump-rtl-cse1,-fdump-rtl-cse2โ these two enable dumping after the two common subexpression elimination passes. two passes, two flags, we love symmetry. ๐ฆ-fdump-rtl-dceโ dumps after the standalone dead code elimination passes.-fdump-rtl-dbrโ dumps after delayed branch scheduling. ๐ธ-fdump-rtl-dce1,-fdump-rtl-dce2โ these two enable dumping after the two dead store elimination passes.-fdump-rtl-ehโ dumps after finalization of EH handling code.-fdump-rtl-eh_rangesโ dumps after conversion of EH handling range regions.-fdump-rtl-expandโ dumps after RTL generation. like, the very birth of the RTL. iconic. โญ-fdump-rtl-fwprop1,-fdump-rtl-fwprop2โ these two enable dumping after the two forward propagation passes.-fdump-rtl-gcse1,-fdump-rtl-gcse2โ these two enable dumping after global common subexpression elimination.-fdump-rtl-init-regsโ dumps after the initialization of the registers.-fdump-rtl-initvalsโ dumps after the computation of the initial value sets.-fdump-rtl-into_cfglayoutโ dumps after converting to cfglayout mode.-fdump-rtl-iraโ dumps after iterated register allocation. ๐-fdump-rtl-jumpโ dumps after the second jump optimization.-fdump-rtl-loop2โ enables dumping after the rtl loop optimization passes. loops on loops on loops ๐ฅ-fdump-rtl-machโ dumps after performing the machine dependent reorganization pass, if that pass exists. key detail bestie, sometimes it just doesn't exist.-fdump-rtl-mode_swโ dumps after removing redundant mode switches.-fdump-rtl-rnregโ dumps after register renumbering.-fdump-rtl-outof_cfglayoutโ dumps after converting from cfglayout mode.-fdump-rtl-peephole2โ dumps after the peephole pass.-fdump-rtl-postreloadโ dumps after post-reload optimizations.-fdump-rtl-pro_and_epilogueโ dumps after generating the function prologues and epilogues.-fdump-rtl-sched1,-fdump-rtl-sched2โ these two enable dumping after the basic block scheduling passes.-fdump-rtl-reeโ dumps after sign/zero extension elimination.-fdump-rtl-seqabstrโ dumps after common sequence discovery.-fdump-rtl-shortenโ dumps after shortening branches.-fdump-rtl-siblingโ dumps after sibling call optimizations.-fdump-rtl-split1,-fdump-rtl-split2,-fdump-rtl-split3,-fdump-rtl-split4,-fdump-rtl-split5โ these options enable dumping after five rounds of instruction splitting. five. that's not a typo, five whole rounds. ๐ญ-fdump-rtl-smsโ dumps after modulo scheduling. heads up tho, this pass is only run on some architectures. ๐-fdump-rtl-stackโ dumps after conversion from GCC's "flat register file" registers to the x87's stack-like registers. this pass is only run on x86 variants, so if you're not on x86 don't even worry about it.-fdump-rtl-subreg1,-fdump-rtl-subreg2โ these two enable dumping after the two subreg expansion passes.-fdump-rtl-unshareโ dumps after all rtl has been unshared.-fdump-rtl-vartrackโ dumps after variable tracking.-fdump-rtl-vregsโ dumps after converting virtual registers to hard registers.-fdump-rtl-webโ dumps after live range splitting.-fdump-rtl-regclass,-fdump-rtl-subregs_of_mode_init,-fdump-rtl-subregs_of_mode_finish,-fdump-rtl-dfinit,-fdump-rtl-dfinishโ okay so these dumps are defined but always produce empty files. not me getting excited over nothing ๐ they exist, they're real flags, they just give you nothing. lowkey a scam but it's documented so.-da,-fdump-rtl-allโ produce all the dumps listed above. all of them. every single one. your disk is gonna feel it bestie. ๐ฅ-dAโ annotate the assembler output with miscellaneous debugging information.-dDโ dump all macro definitions, at the end of preprocessing, in addition to normal output.-dHโ produce a core dump whenever an error occurs. yeah fr, an actual core dump. ๐ซถ-dpโ annotate the assembler output with a comment indicating which pattern and alternative is used. the length and cost of each instruction are also printed.-dPโ dump the RTL in the assembler output as a comment before each instruction. also turns on-dpannotation.-dxโ just generate RTL for a function instead of compiling it. usually used with-fdump-rtl-expand.
-fdump-debugโ dump debugging information generated during the debug generation phase. ๐-fdump-earlydebugโ dump debugging information generated during the early debug generation phase.-fdump-noaddrโ when doing debugging dumps, suppress address output. this makes it more feasible to usediffon debugging dumps for compiler invocations with different compiler binaries and/or different text / bss / data / heap / stack / dso start locations. so basically it lets you actually compare two dumps without the addresses ruining everything. ๐-freport-bugโ collect and dump debug information into a temporary file if an internal compiler error (ICE) occurs.-fdump-unnumberedโ when doing debugging dumps, suppress instruction numbers and address output. this makes it more feasible to usediffon debugging dumps for compiler invocations with different options, in particular with and without-g. ๐ฆ-fdump-unnumbered-linksโ when doing debugging dumps (see-doption above), suppress instruction numbers for the links to the previous and next instructions in a sequence.-fdump-ipa-switch,-fdump-ipa-switch-optionsโ control the dumping at various stages of inter-procedural analysis language tree to a file. the file name is generated by appending a switch specific suffix to the source file name, and the file is created in the same directory as the output file. the following dumps are possible:allโ enables all inter-procedural analysis dumps. โจcgraphโ dumps information about call-graph optimization, unused function removal, and inlining decisions.inlineโ dump after function inlining.
additionally, the options -optimized, -missed, -note, and -all can be provided, with the same meaning as for -fopt-info, defaulting to -optimized.
for example, -fdump-ipa-inline-optimized-missed will emit information on callsites that were inlined, along with callsites that were not inlined. ๐
by default, the dump will contain messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis.
-fdump-langโ dump language-specific information. the file name is made by appending.langto the source file name.-fdump-lang-all,-fdump-lang-switch,-fdump-lang-switch-options,-fdump-lang-switch-options=filenameโ control the dumping of language-specific information. the options and filename portions behave as described in the-fdump-treeoption. the following switch values are accepted:allโ enable all language-specific dumps.classโ dump class hierarchy information. virtual table information is emitted unless'slim'is specified. this option is applicable to C++ only.moduleโ dump module information. optionslineno(locations),graph(reachability),blocks(clusters),uid(serialization),alias(mergeable),asmname(Elrond),eh(mapper) &vops(macros) may provide additional information. this option is applicable to C++ only.rawโ dump the raw internal tree data. this option is applicable to C++ only.
-fdump-passesโ print on stderr the list of optimization passes that are turned on and off by the current command-line options. ๐-fdump-statistics-optionโ enable and control dumping of pass statistics in a separate file. the file name is generated by appending a suffix ending in.statisticsto the source file name, and the file is created in the same directory as the output file. if the-optionform is used,-statscauses counters to be summed over the whole compilation unit while-detailsdumps every event as the passes generate them. the default with no option is to sum counters for each function compiled.-fdump-tree-all,-fdump-tree-switch,-fdump-tree-switch-options,-fdump-tree-switch-options=filenameโ control the dumping at various stages of processing the intermediate language tree to a file. if the-optionsform is used,optionsis a list of-separated options which control the details of the dump. not all options are applicable to all dumps; those that are not meaningful are ignored. the following options are available:addressโ print the address of each node. usually this is not meaningful as it changes according to the environment and source file. its primary use is for tying up a dump file with a debug environment.asmnameโ if"DECL_ASSEMBLER_NAME"has been set for a given decl, use that in the dump instead of"DECL_NAME". its primary use is ease of use working backward from mangled names in the assembly file.slimโ when dumping front-end intermediate representations, inhibit dumping of members of a scope or body of a function merely because that scope has been reached. only dump such items when they are directly reachable by some other path.
when dumping pretty-printed trees, this option inhibits dumping the bodies of control structures.
when dumping RTL, print the RTL in slim (condensed) form instead of the default LISP-like representation.
rawโ print a raw representation of the tree. by default, trees are pretty-printed into a C-like representation. ๐ธ
detailsโ bestie this one turns the dial UP on detail, it enables way more detailed dumps (tho ngl, not every dump option honors it, rude). It also pulls in info from the optimization passes. ๐ซถstatsโ dumps a whole lil pile of statistics about the pass. Again: not honored by every dump option, so don't come for me if yours ghosts you.blocksโ shows you the basic block boundaries โจ (heads up: this one's disabled in raw dumps)graphโ okay so for each of the other indicated dump files (-fdump-rtl-pass), this dumps a representation of the control flow graph to a file calledfile.passid.pass.dot, and it's formatted so you can view it with GraphViz ๐ Every function in the file gets pretty-printed as a subgraph so GraphViz can render them ALL in a single plot. Iconic behavior fr. But note: this option currently only works for RTL dumps, and the RTL is always dumped in slim form.vopsโ shows virtual operands for every single statement ๐linenoโ shows line numbers for statements, so you can actually find things ๐ญuidโ shows the unique ID (DECL_UID) for each variable. Very demure, very mindful.verboseโ shows the tree dump for each statement ๐ณehโ shows the EH region number holding each statementscevโ shows scalar evolution analysis details ๐ฅoptimizedโ shows optimization information (only available in certain passes, so it's giving selective availability)missedโ shows missed optimization information (again, only available in certain passes)noteโ shows other detailed optimization information (only in certain passes, you know the drill)allโ turns on ALL the options, exceptraw,slim,verboseandlineno. Not me excluding those four specifically ๐optallโ turns on all the optimization options, i.e.optimized,missed, andnoteโจ
To figure out what tree dumps are even available, or to find the dump for a pass you're obsessed with, follow these steps bestie:
- Invoke GCC with
-fdump-passesand in the stderr output look for a code that corresponds to the pass you're interested in. For example, the codes"tree-evrp","tree-vrp1", and"tree-vrp2"correspond to the three Value Range Propagation passes. The number at the end distinguishes distinct invocations of the same pass. - To enable the creation of the dump file, append the pass code to the
-fdump-option prefix and invoke GCC with it. For example, to enable the dump from the Early Value Range Propagation pass, invoke GCC with the-fdump-tree-evrpoption. Optionally, you may specify the name of the dump file. If you don't specify one, GCC creates as described below. ๐ - Find the pass dump in a file whose name is composed of three components separated by a period: the name of the source file GCC was invoked to compile, a numeric suffix indicating the pass number followed by the letter
tfor tree passes (and the letterrfor RTL passes), and finally the pass code. For example, the Early VRP pass dump might be in a file namedmyfile.c.038t.evrpin the current working directory. Note that the numeric codes are not stable and may change from one version of GCC to another. So don't hardcode them, babe.
๐ -fopt-info ๐
โจ -fopt-info-options โจ
๐ฆ -fopt-info-options=filename ๐ฆ
Controls optimization dumps from various optimization passes. If the -options form is used, options is a list of - separated option keywords to select the dump details and optimizations. ๐
The options can be divided into three groups:
- options describing what kinds of messages should be emitted,
- options describing the verbosity of the dump, and
- options describing which optimizations should be included.
The options from each group can be freely mixed as they are non-overlapping. However, in case of any conflicts, the later options override the earlier options on the command line. Last one wins, periodt.
The following options control which kinds of messages should be emitted:
optimizedโ prints information when an optimization is successfully applied. It is up to a pass to decide which information is relevant. For example, the vectorizer passes print the source location of loops which are successfully vectorized. Slay.missedโ prints information about missed optimizations. Individual passes control which information to include in the output. (we're all a lil missed optimization sometimes ๐ญ)noteโ prints verbose information about optimizations, such as certain transformations, more detailed messages about decisions etc.allโ prints detailed optimization information. This includesoptimized,missed, andnote. The whole buffet bestie ๐
The following option controls the dump verbosity:
internalsโ by default, only "high-level" messages are emitted. This option enables additional, more detailed, messages, which are likely to only be of interest to GCC developers. iykyk
One or more of the following option keywords can be used to describe a group of optimizations:
ipaโ enable dumps from all interprocedural optimizations.loopโ enable dumps from all loop optimizations.inlineโ enable dumps from all inlining optimizations.ompโ enable dumps from all OMP (Offloading and Multi Processing) optimizations.vecโ enable dumps from all vectorization optimizations.optallโ enable dumps from all optimizations. This is a superset of the optimization groups listed above. ๐
If options is omitted, it defaults to optimized-optall, which means to dump messages about successful optimizations from all the passes, omitting messages that are treated as "internals". That's the default vibe, no cap.
If the filename is provided, then the dumps from all the applicable optimizations are concatenated into the filename. Otherwise the dump is output onto stderr. Though multiple -fopt-info options are accepted, only one of them can include a filename. If other filenames are provided then all but the first such option are ignored.
โ ๏ธ Note that the output filename is overwritten in case of multiple translation units. If a combined output from multiple translation units is desired, stderr should be used instead.
In the following example, the optimization info is output to stderr:
gcc -O3 -fopt-info
This example:
gcc -O3 -fopt-info-missed=missed.all
outputs missed optimization report from all the passes into missed.all, and this one:
gcc -O2 -ftree-vectorize -fopt-info-vec-missed
prints information about missed optimization opportunities from vectorization passes on stderr. Note that -fopt-info-vec-missed is equivalent to -fopt-info-missed-vec. The order of the optimization group names and message types listed after -fopt-info does not matter. We love a flexible queen ๐
As another example,
gcc -O3 -fopt-info-inline-optimized-missed=inline.txt
outputs information about missed optimizations as well as optimized locations from all the inlining passes into inline.txt. ๐
Finally, consider:
gcc -fopt-info-vec-missed=vec.miss -fopt-info-loop-optimized=loop.opt
Here the two output filenames vec.miss and loop.opt are in conflict since only one output file is allowed. In this case, only the first option takes effect and the subsequent options are ignored. Thus only vec.miss is produced which contains dumps from the vectorizer about missed opportunities. First come first served, bestie ๐ญ
๐ -fsave-optimization-record ๐
Write a SRCFILE.opt-record.json.gz file detailing what optimizations were performed, for those optimizations that support -fopt-info.
๐งช This option is experimental and the format of the data within the compressed JSON file is subject to change. Do not come for me when it changes, I warned you.
It is roughly equivalent to a machine-readable version of -fopt-info-all, as a collection of messages with source file, line number and column number, with the following additional data for each message:
- the execution count of the code being optimized, along with metadata about whether this was from actual profile data, or just an estimate, allowing consumers to prioritize messages by code hotness, ๐ฅ
- the function name of the code being optimized, where applicable,
- the "inlining chain" for the code being optimized, so that when a function is inlined into several different places (which might themselves be inlined), the reader can distinguish between the copies,
- objects identifying those parts of the message that refer to expressions, statements or symbol-table nodes, which of these categories they are, and, when available, their source code location,
- the GCC pass that emitted the message, and
- the location in GCC's own code from which the message was emitted
Additionally, some messages are logically nested within other messages, reflecting implementation details of the optimization passes. It's giving nesting dolls, but make it compilers.
๐ธ -fsched-verbose=n ๐ธ
On targets that use instruction scheduling, this option controls the amount of debugging output the scheduler prints to the dump files. ๐
For n greater than zero, -fsched-verbose outputs the same information as -fdump-rtl-sched1 and -fdump-rtl-sched2. For n greater than one, it also output basic block probabilities, detailed ready list information and unit/insn info. For n greater than two, it includes RTL at abort point, control-flow and regions info. And for n over four, -fsched-verbose also includes dependence info. The higher the number, the more it yaps, basically.
๐ -fenable-kind-pass ๐
๐ -fdisable-kind-pass=range-list ๐
This is a set of options that are used to explicitly disable/enable optimization passes. These options are intended for use for debugging GCC. Compiler users should use regular options for enabling/disabling passes instead. Yeah bestie, this is the developer backstage door, not the main entrance. ๐ช
-fdisable-ipa-pass
Disable IPA pass pass. pass is the pass name. If the same pass is statically invoked in the compiler multiple times, the pass name should be appended with a sequential number starting from 1. ๐ข
-fdisable-rtl-pass,-fdisable-rtl-pass=range-listโ bestie, this one turns OFF an RTL pass. pass is the pass name, and if the same pass gets statically invoked in the compiler multiple times, you gotta append a sequential number starting from1. ๐ range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon, and the range is inclusive on both ends. If the range is trivial, you can simplify the number pair into a single number. If the function's call graph node's uid falls within one of the specified ranges, the pass is disabled for that function. The uid is shown in the function header of a dump file, and you can dump the pass names with-fdump-passes. ๐-fdisable-tree-pass,-fdisable-tree-pass=range-listโ disables a tree pass, pass. Same energy as above โ see-fdisable-rtlfor how the option arguments work. ๐ธ-fenable-ipa-passโ enables an IPA pass, pass. Again, if the same pass is statically invoked multiple times, append a sequential number starting from1. โจ-fenable-rtl-pass,-fenable-rtl-pass=range-listโ enables an RTL pass, pass. See-fdisable-rtlfor the option argument description and examples. ๐ฆ-fenable-tree-pass,-fenable-tree-pass=range-listโ enables a tree pass, pass. See-fdisable-rtlfor the description of option arguments. ๐
Here are some examples showing uses of these options, and they ate, fr fr:
# disable ccp1 for all functions
-fdisable-tree-ccp1
# disable complete unroll for function whose cgraph node uid is 1
-fenable-tree-cunroll=1
# disable gcse2 for functions at the following ranges [1,1],
# [300,400], and [400,1000]
# disable gcse2 for functions foo and foo2
-fdisable-rtl-gcse2=foo,foo2
# disable early inlining
-fdisable-tree-einline
# disable ipa inlining
-fdisable-ipa-inline
# enable tree full unroll
-fenable-tree-unroll
-fchecking,-fchecking=nโ turns on internal consistency checking. The default depends on the compiler configuration, so it's giving "it depends" energy.-fchecking=2enables further internal consistency checking that might affect code generation. ๐-frandom-seed=stringโ this option hands GCC a seed to use in place of random numbers when it's generating certain symbol names that have to be different in every compiled file. It's also used to place unique stamps in coverage data files and the object files that produce them. And here's the slay: you can use-frandom-seedto produce reproducibly identical object files. ๐
The string can be either a number (decimal, octal or hex) or an arbitrary string โ in which case it gets converted to a number by computing CRC32.
The string should be different for every file you compile. No cap.
-save-tempsโ stores the usual "temporary" intermediate files permanently instead of yeeting them. It names them as auxiliary output files, as specified described under-dumpbaseand-dumpdir. ๐
When used in combination with the -x command-line option, -save-temps is sensible enough to avoid overwriting an input source file with the same extension as an intermediate file. The corresponding intermediate file may be obtained by renaming the source file before using -save-temps.
-save-temps=cwdโ equivalent to-save-temps -dumpdir ./. Short, sweet, iconic. โจ-save-temps=objโ equivalent to-save-temps -dumpdir outdir/, where outdir/ is the directory of the output file specified after the-ooption, including any directory separators. If the-ooption is not used, the-save-temps=objswitch behaves like-save-temps=cwd. ๐-time[=file]โ reports the CPU time taken by each subprocess in the compilation sequence. For C source files, this is the compiler proper and assembler (plus the linker if linking is done). โฑ๏ธ
Without the specification of an output file, the output looks like this:
# cc1 0.12 0.01
# as 0.00 0.01
The first number on each line is the "user time" โ that is, time spent executing the program itself. The second number is "system time", time spent executing operating system routines on behalf of the program. Both numbers are in seconds. ๐ฐ๏ธ
With the specification of an output file, the output is appended to the named file, and it looks like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
The "user time" and the "system time" are moved before the program name, and the options passed to the program are displayed, so that one can later tell what file was being compiled, and with which options. Receipts. ๐งพ
-fdump-final-insns[=file]โ dumps the final internal representation (RTL) to file. If the optional argument is omitted (or if file is.), the name of the dump file is determined by appending.gkdto the dump base name, see-dumpbase. ๐๏ธ-fcompare-debug[=opts]โ okay so if no error occurs during compilation, this runs the compiler a second time, adding opts and-fcompare-debug-secondto the arguments passed to the second compilation. It dumps the final internal representation in both compilations, and prints an error if they differ. ๐
If the equal sign is omitted, the default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, then it is used for opts, otherwise the default -gtoggle is used.
-fcompare-debug=, with the equal sign but without opts, is equivalent to -fno-compare-debug, which disables the dumping of the final representation and the second compilation, preventing even GCC_COMPARE_DEBUG from taking effect. ๐ซ
To verify full coverage during -fcompare-debug testing, set GCC_COMPARE_DEBUG to say -fcompare-debug-not-overridden, which GCC rejects as an invalid option in any actual compilation (rather than preprocessing, assembly or linking). To get just a warning, setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do. ๐ญ
-fcompare-debug-secondโ this option is implicitly passed to the compiler for the second compilation requested by-fcompare-debug, along with options to silence warnings, and omitting other options that would cause the compiler to produce output to files or to standard output as a side effect. Dump files and preserved temporary files are renamed so as to contain the.gkadditional extension during the second compilation, to avoid overwriting those generated by the first. ๐
When this option is passed to the compiler driver, it causes the first compilation to be skipped, which makes it useful for little other than debugging the compiler proper. Ngl, it's a niche icon. ๐
-gtoggleโ turns off generation of debug info if leaving out this option generates it, or turns it on at level 2 otherwise. The position of this argument in the command line does not matter; it takes effect after all other options are processed, and it does so only once, no matter how many times it is given. This is mainly intended to be used with-fcompare-debug. ๐-fvar-tracking-assignments-toggleโ toggles-fvar-tracking-assignments, in the same way that-gtoggletoggles-g. ๐๏ธ-Qโ makes the compiler print out each function name as it is compiled, and print some statistics about each pass when it finishes. Live commentary, basically. ๐ฃ-ftime-reportโ makes the compiler print some statistics about the time consumed by each pass when it finishes. โณ-ftime-report-detailsโ records the time consumed by infrastructure parts separately for each pass. Extra detailed, extra slay. ๐-fira-verbose=nโ controls the verbosity of the dump file for the integrated register allocator. The default value is5. If the value n is greater or equal to10, the dump output is sent to stderr using the same format as n minus 10. ๐ฃ๏ธ-flto-reportโ prints a report with internal details on the workings of the link-time optimizer. The contents of this report vary from version to version. It is meant to be useful to GCC developers when processing object files in LTO mode (via-flto). ๐ฅ
Disabled by default.
-flto-report-wpaโ like-flto-report, but only prints for the WPA phase of link-time optimization. ๐ฏ-fmem-reportโ makes the compiler print some statistics about permanent memory allocation when it finishes. ๐ง-fmem-report-wpaโ makes the compiler print some statistics about permanent memory allocation for the WPA phase only. ๐งฉ-fpre-ipa-mem-report,-fpost-ipa-mem-reportโ makes the compiler print some statistics about permanent memory allocation before or after interprocedural optimization. Before and after pics, but for memory. ๐ธ-fprofile-reportโ makes the compiler print some statistics about consistency of the (estimated) profile and effect of individual passes. ๐ฏ-fstack-usageโ makes the compiler output stack usage information for the program, on a per-function basis. The filename for the dump is made by appending.suto the auxname. auxname is generated from the name of the output file, if explicitly specified and it is not an executable, otherwise it is the basename of the source file. An entry is made up of three fields: ๐ธ- The name of the function.
- A number of bytes.
- One or more qualifiers:
"static","dynamic","bounded".
The qualifier "static" means that the function manipulates the stack statically: a fixed number of bytes are allocated for the frame on function entry and released on function exit; no stack adjustments are otherwise made in the function. The second field is this fixed number of bytes. ๐
The qualifier "dynamic" means the function is out here doing the absolute most โ it manipulates the stack dynamically ๐: on top of the static allocation we just talked about, it also makes stack adjustments inside the function body, like pushing/popping args around function calls. And if "bounded" is also hanging out there too? Then the amount of those adjustments is bounded at compile time, and that second field is an upper bound of the total stack the function uses. If "bounded" is not present, the adjustments are not bounded at compile time, and the second field only represents the bounded part. periodt.
-fstatsโ Emit statistics about front-end processing at the end of the compilation. Ngl this one is supported only by the C++ front end, and the info is generally only useful to the G++ development team. iykyk ๐-fdbg-cnt-listโ Print the name and the counter upper bound for all debug counters.-fdbg-cnt=counter-value-listโ Set the internal debug counter lower and upper bound.counter-value-listis a comma-separated list ofname:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...]tuples which sets the name of the counter and list of closed intervals. Thelower_boundis optional and is zero initialized if not set. For example, with-fdbg-cnt=dce:2-4:10-11,tail_call:10,dbg_cnt(dce)returns true only for second, third, fourth, tenth and eleventh invocation. Fordbg_cnt(tail_call)true is returned for first 10 invocations. โจ-print-file-name=libraryโ Print the full absolute name of the library file library that would be used when linking โ and don't do anything else. With this option, GCC does not compile or link anything; it just prints the file name. Just a lil peek, no commitment ๐ซถ-print-multi-directoryโ Print the directory name corresponding to the multilib selected by any other switches present in the command line. This directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ Print the mapping from multilib directory names to compiler switches that enable them. The directory name is separated from the switches by;, and each switch starts with an@instead of the-, without spaces between multiple switches. This is supposed to ease shell processing. iconic shell-girl behavior ๐ธ-print-multi-os-directoryโ Print the path to OS libraries for the selected multilib, relative to somelibsubdirectory. If OS libraries are present in thelibsubdirectory and no multilibs are used, this is usually just., if OS libraries are present inlibsuffixsibling directories this prints e.g.../lib64,../libor../lib32, or if OS libraries are present inlib/subdirsubdirectories it prints e.g.amd64,sparcv9orev6.-print-multiarchโ Print the path to OS libraries for the selected multiarch, relative to somelibsubdirectory.-print-prog-name=programโ Like-print-file-name, but searches for a program such ascpp. ๐-print-libgcc-file-nameโ Same as-print-file-name=libgcc.a.
This is useful when you use -nostdlib or -nodefaultlibs but you do want to link with libgcc.a. You can do:
gcc -nostdlib <files>... `gcc -print-libgcc-file-name`
-print-search-dirsโ Print the name of the configured installation directory and a list of program and library directoriesgccsearches โ and don't do anything else.
This is useful when gcc prints the error message installation problem, cannot exec cpp0: No such file or directory. To resolve this you either need to put cpp0 and the other compiler components where gcc expects to find them, or you can set the environment variable GCC_EXEC_PREFIX to the directory where you installed them. Don't forget the trailing /. (Not me forgetting the trailing slash every single time ๐ญ)
-print-sysrootโ Print the target sysroot directory that is used during compilation. This is the target sysroot specified either at configure time or using the--sysrootoption, possibly with an extra suffix that depends on compilation options. If no target sysroot is specified, the option prints nothing. literally nothing. silence. ๐-print-sysroot-headers-suffixโ Print the suffix added to the target sysroot when searching for headers, or give an error if the compiler is not configured with such a suffix โ and don't do anything else.-dumpmachineโ Print the compiler's target machine (for example,i686-pc-linux-gnu) โ and don't do anything else.-dumpversionโ Print the compiler version (for example,3.0,6.3.0or7) โ and don't do anything else. This is the compiler version used in filesystem paths and specs. Depending on how the compiler has been configured it can be just a single number (major version), two numbers separated by a dot (major and minor version) or three numbers separated by dots (major, minor and patchlevel version).-dumpfullversionโ Print the full compiler version โ and don't do anything else. The output is always three numbers separated by dots, major, minor and patchlevel version. no shortcuts, full send ๐-dumpspecsโ Print the compiler's built-in specs โ and don't do anything else. (This is used when GCC itself is being built.) meta fr fr ๐ง
Machine-Dependent Options ๐ ๏ธ
Each target machine supported by GCC can have its own options โ for example, to allow you to compile for a particular processor variant or ABI, or to control optimizations specific to that machine. By convention, the names of machine-specific options start with -m. bestie's lil family of options ๐
Some configurations of the compiler also support additional target-specific options, usually for compatibility with other compilers on the same platform.
AArch64 Options ๐
These options are defined for AArch64 implementations:
-mabi=nameโ Generate code for the specified data model. Permissible values areilp32for SysV-like data model whereint,long intand pointers are 32 bits, andlp64for SysV-like data model whereintis 32 bits, butlong intand pointers are 64 bits.
The default depends on the specific target configuration. Note that the LP64 and ILP32 ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. > do NOT mix these, bestie, I'm begging ๐ it will not slay.
-mbig-endianโ Generate big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target.-mgeneral-regs-onlyโ Generate code which uses only the general-purpose registers. This will prevent the compiler from using floating-point and Advanced SIMD registers but will not impose any restrictions on the assembler. regs-only era โจ-mlittle-endianโ Generate little-endian code. This is the default when GCC is configured for anaarch64-*-*but not anaarch64_be-*-*target.-mcmodel=tinyโ Generate code for the tiny code model. The program and its statically defined symbols must be within 1MB of each other. Programs can be statically or dynamically linked. smol but mighty ๐-mcmodel=smallโ Generate code for the small code model. The program and its statically defined symbols must be within 4GB of each other. Programs can be statically or dynamically linked. This is the default code model. the moment โจ-mcmodel=largeโ Generate code for the large code model. This makes no assumptions about addresses and sizes of sections. Programs can be statically linked only. The-mcmodel=largeoption is incompatible with-mabi=ilp32,-fpicand-fPIC. > incompatible bestie!! they do not vibe together ๐-mstrict-align/-mno-strict-alignโ Avoid or allow generating memory accesses that may not be aligned on a natural object boundary as described in the architecture specification.-momit-leaf-frame-pointer/-mno-omit-leaf-frame-pointerโ Omit or keep the frame pointer in leaf functions. The former behavior is the default. ๐-mstack-protector-guard=guard/-mstack-protector-guard-reg=reg/-mstack-protector-guard-offset=offsetโ Generate stack protection code using canary at guard. Supported locations areglobalfor a global canary orsysregfor a canary in an appropriate system register.
With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which system register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel. ๐ง no defaults here, it's giving Linux-kernel-only energy
-mtls-dialect=descโ Use TLS descriptors as the thread-local storage mechanism for dynamic accesses of TLS variables. This is the default.-mtls-dialect=traditionalโ Use traditional TLS as the thread-local storage mechanism for dynamic accesses of TLS variables. old-school but valid ๐-mtls-size=sizeโ Specify bit size of immediate TLS offsets. Valid values are12,24,32,48. This option requires binutils 2.26 or newer. check ur binutils bestie โญ-mfix-cortex-a53-835769/-mno-fix-cortex-a53-835769โ Enable or disable the workaround for the ARM Cortex-A53 erratum number 835769. This involves inserting aNOPinstruction between memory instructions and 64-bit integer multiply-accumulate instructions.-mfix-cortex-a53-843419/-mno-fix-cortex-a53-843419โ Enable or disable the workaround for the ARM Cortex-A53 erratum number 843419. This erratum workaround is made at link time and this will only pass the corresponding flag to the linker. ๐-mlow-precision-recip-sqrt/-mno-low-precision-recip-sqrtโ Enable or disable the reciprocal square root approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of reciprocal square root results to about 16 bits for single precision and to 32 bits for double precision. (lowkey less accurate but highkey faster ๐)-mlow-precision-sqrt/-mno-low-precision-sqrtโ Enable or disable the square root approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of square root results to about 16 bits for single precision and to 32 bits for double precision. If enabled, it implies-mlow-precision-recip-sqrt. ๐ธ-mlow-precision-div/-mno-low-precision-divโ Enable or disable the division approximation. This option only has an effect if-ffast-mathor-funsafe-math-optimizationsis used as well. Enabling this reduces precision of division results to about 16 bits for single precision and to 32 bits for double precision. ๐ฅ-mtrack-speculation,-mno-track-speculationโ turn on (or off ๐ค) generating extra code that tracks speculative execution through conditional branches. That tracked state can then be used by the compiler when it's expanding calls to__builtin_speculation_safe_copy, which lets it cook up a more efficient code sequence. ๐ต๏ธโ๏ธโจ-moutline-atomics,-mno-outline-atomicsโ enable/disable calls out to out-of-line helpers that implement atomic operations. These helpers figure out at runtime whether the LSE instructions from ARMv8.1-A are usable; if they're not, they fall back to the load/store-exclusive instructions that live in the base ARMv8.0 ISA. ๐ง
This one only matters when you're compiling for the base ARMv8.0 instruction set. If you're on a later revision โ like -march=armv8.1-a or -march=armv8-a+lse โ the ARMv8.1-Atomics instructions get used directly. Same deal with -mcpu= when the cpu you picked supports the lse feature. And bestie, this option is on by default. ๐
-march=nameโ say which target architecture you want, and optionally tack on one or more feature modifiers. The shape is:
-march=arch{+[no]feature}*
Here's the rundown of what arch can be and what each one pulls in by default:
armv8-aโ Architecture: Armv8-A โ includes by default:+fp,+simdarmv8.1-aโ Architecture: Armv8.1-A โ includes by default:armv8-a,+crc,+lse,+rdmaarmv8.2-aโ Architecture: Armv8.2-A โ includes by default:armv8.1-aarmv8.3-aโ Architecture: Armv8.3-A โ includes by default:armv8.2-a,+pautharmv8.4-aโ Architecture: Armv8.4-A โ includes by default:armv8.3-a,+flagm,+fp16fml,+dotprodarmv8.5-aโ Architecture: Armv8.5-A โ includes by default:armv8.4-a,+sb,+ssbs,+predresarmv8.6-aโ Architecture: Armv8.6-A โ includes by default:armv8.5-a,+bf16,+i8mmarmv8.7-aโ Architecture: Armv8.7-A โ includes by default:armv8.6-a,+ls64armv8.8-aโ Architecture: Armv8.8-a โ includes by default:armv8.7-a,+mopsarmv9-aโ Architecture: Armv9-A โ includes by default:armv8.5-a,+sve,+sve2armv8-rโ Architecture: Armv8-R โ includes by default:armv8-r
The value native is available on native AArch64 GNU/Linux, and it makes the compiler just pick whatever the host system's architecture is. Heads up though โ this option does nothing if the compiler can't recognize the host's architecture. ๐
The allowed values for feature are listed down in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. And if you specify conflicting feature modifiers? The right-most feature wins. Periodt. ๐
GCC uses name to decide what kind of instructions it's allowed to emit when it generates assembly code. And if you give -march without also giving -mtune or -mcpu, the code gets tuned to perform well across a whole range of target processors that implement the target architecture. ๐
-mtune=nameโ name the target processor GCC should tune the performance of the code for. The permissible values are:generic,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,cortex-a76,cortex-a76ae,cortex-a77,cortex-a65,cortex-a65ae,cortex-a34,cortex-a78,cortex-a78ae,cortex-a78c,ares,exynos-m1,emag,falkor,neoverse-512tvb,neoverse-e1,neoverse-n1,neoverse-n2,neoverse-v1,neoverse-v2,grace,qdf24xx,saphira,phecda,xgene1,vulcan,octeontx,octeontx81,octeontx83,octeontx2,octeontx2t98,octeontx2t96octeontx2t93,octeontx2f95,octeontx2f95n,octeontx2f95mm,a64fx,thunderx,thunderxt88,thunderxt88p1,thunderxt81,tsv110,thunderxt83,thunderx2t99,thunderx3t110,zeus,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53,cortex-a75.cortex-a55,cortex-a76.cortex-a55,cortex-r82,cortex-x1,cortex-x2,cortex-a510,cortex-a710,ampere1,ampere1a,cobalt-100andnative. ๐ฎโ๐จ that's a lot of names, I know.
The values cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a73.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55 mean GCC should tune for a big.LITTLE system. ๐๐ญ
The value neoverse-512tvb means GCC should tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. Put another way: it tells GCC to tune for Neoverse cores that can run 4 128-bit Advanced SIMD arithmetic instructions per cycle, and can run an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). It's more general than tuning for one specific core like Neoverse V1, but more specific than the default tuning described below. ๐ฏ
Also, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. This option does nothing if the compiler can't recognize the host system's processor. ๐ญ
Where none of -mtune=, -mcpu= or -march= are specified, the code is tuned to perform well across a range of target processors.
This option cannot be suffixed by feature modifiers. No add-ons, bestie. ๐ซ
-mcpu=nameโ name the target processor, optionally with one or more feature modifiers tacked on the end. The shape is:
-mcpu=cpu{+[no]feature}*
where the permissible values for cpu are exactly the same as the ones available for -mtune. The permissible values for feature are documented in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers show up, the right-most feature is the one that counts. ๐
GCC uses name to figure out what kind of instructions it can emit when generating assembly code (as if by -march), and to figure out the target processor to tune for performance (as if by -mtune). And when you use this option together with -march or -mtune, those options take precedence over the appropriate part of this one. ๐
-mcpu=neoverse-512tvb is special โ it doesn't point at one specific core, it points at all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless -march overrides it, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with those properties. And unless -mtune overrides it, -mcpu=neoverse-512tvb tunes code the exact same way as -mtune=neoverse-512tvb. โจ
-moverride=stringโ override tuning decisions the back-end made in response to a-mtune=switch. The syntax, semantics and accepted values forstringhere are not guaranteed to be consistent across releases. ๐ฌ
This option is only meant to be useful when you're developing GCC itself. Not for casual use, bestie.
-mverbose-cost-dumpโ turn on verbose cost model dumping in the debug dump files. This option exists purely for debugging the compiler. ๐-mpc-relative-literal-loads,-mno-pc-relative-literal-loadsโ enable/disable PC-relative literal loads. With this on, literal pools are accessed using a single instruction and emitted after each function. This caps the maximum size of functions at 1MB. It's enabled by default for-mcmodel=tiny. ๐-msign-return-address=scopeโ choose the function scope where return address signing gets applied. Permissible values arenone, which disables return address signing entirely,non-leaf, which enables pointer signing for functions that aren't leaf functions, andall, which enables pointer signing for every function. The default value isnone.
โ ๏ธ This option has been deprecated by -mbranch-protection. It's giving legacy energy, ngl.
-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ pick which branch protection features to use.noneis the default and turns off every type of branch protection.standardturns on all types of branch protection features โ and if a feature has extra tuning options,standardsets it to its standard level.pac-ret[+leaf]turns on return address signing at its standard level: signing functions that save the return address to memory (non-leaf functions will practically always do this) using the a-key. The optional argumentleafextends the signing to include leaf functions too. The optional argumentb-keysigns the functions with the B-key instead of the A-key. Andbtiturns on the branch target identification mechanism. ๐ก๏ธ-mharden-sls=optsโ turn on compiler hardening against straight line speculation (SLS).optsis a comma-separated list of the following options:retbrblr
On top of that, -mharden-sls=all enables all SLS hardening, while -mharden-sls=none disables all of it. ๐ช
-msve-vector-bits=bitsโ set the number of bits in an SVE vector register. This option only does anything when SVE is enabled.
GCC supports two flavours of SVE code generation: "vector-length agnostic" output that works with any size of vector register, and "vector-length specific" output that lets GCC make assumptions about the vector length when that's useful for optimization reasons. The possible values of bits are: scalable, 128, 256, 512, 1024 and 2048. Specifying scalable selects vector-length agnostic output. At present, -msve-vector-bits=128 also generates vector-length agnostic output for big-endian targets. All other values generate vector-length specific code. The behaviour of these values may change in future releases, and no value except scalable should be relied on for producing code that's portable across different hardware SVE vector lengths. ๐ตโ๐ซ
The default is -msve-vector-bits=scalable, which produces vector-length agnostic code. ๐ฆ
โจ -march and -mcpu Feature Modifiers โจ
Feature modifiers you can use with -march and -mcpu are any of the following, plus their inverses nofeature:
crcโ enable the CRC extension. This is on by default for-march=armv8.1-a.cryptoโ enable the Crypto extension. This also enables Advanced SIMD and floating-point instructions. ๐fpโ enable floating-point instructions. This is on by default for all possible values for the options-marchand-mcpu.simdโ enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for the options-marchand-mcpu.sveโ enable Scalable Vector Extension instructions. This also enables Advanced SIMD and floating-point instructions. ๐lseโ enable Large System Extension instructions. This is on by default for-march=armv8.1-a.rdmaโ enable Round Double Multiply Accumulate instructions. This is on by default for-march=armv8.1-a.fp16โ turns on the FP16 extension, bestie. And like, it also enables floating-point instructions, so it's giving two-for-one ๐fp16fmlโ enables the FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. It's on by default for-march=armv8.4-a. ๐ Heads up tho: using this with architectures before Armv8.2-A is not supported. Not a vibe.rcpcโ enables the RcPc extension. Lowkey it doesn't change code generation from GCC at all, it just gets passed on to the assembler, which lets your inlineasmstatements use instructions from the RcPc extension. iykyk โจdotprodโ enables the Dot Product extension. Also enables Advanced SIMD instructions. ๐aesโ enables the Armv8-aaesandpmullcrypto extension. Also enables Advanced SIMD instructions. ๐ฅsha2โ enables the Armv8-asha2crypto extension. Also enables Advanced SIMD instructions. ๐ธsha3โ enables thesha512andsha3crypto extension. Also enables Advanced SIMD instructions. Real talk: using this with architectures before Armv8.2-A is not supported. ๐ญsm4โ enables thesm3andsm4crypto extension. Also enables Advanced SIMD instructions. And again, architectures before Armv8.2-A? Not supported. ๐profileโ enables the Statistical Profiling extension. Just so we're clear, this one is only to enable the extension at the assembler level โ it does not affect code generation. Periodt.rngโ enables the Armv8.5-a Random Number instructions. Same deal: assembler-level only, does not affect code generation. ๐memtagโ enables the Armv8.5-a Memory Tagging Extensions. Use of this with architectures before Armv8.5-A is not supported. ๐ซsbโ enables the Armv8-a Speculation Barrier instruction. Only enables the extension at the assembler level, does not affect code generation. It's enabled by default for-march=armv8.5-a. โจssbsโ enables the Armv8-a Speculative Store Bypass Safe instruction. Assembler level only, no effect on code generation. On by default for-march=armv8.5-a. ๐ฆpredresโ enables the Armv8-a Execution and Data Prediction Restriction instructions. Again: assembler level only, does not affect code generation. Default for-march=armv8.5-a. โญsve2โ enables the Armv8-a Scalable Vector Extension 2. Also enables SVE instructions. ๐sve2-bitpermโ enables SVE2 bitperm instructions. Also enables SVE2 instructions. ๐sve2-sm4โ enables SVE2sm4instructions. Also enables SVE2 instructions. ๐sve2-aesโ enables SVE2aesinstructions. Also enables SVE2 instructions. ๐sve2-sha3โ enables SVE2sha3instructions. Also enables SVE2 instructions. ๐งtmeโ enables the Transactional Memory Extension. ๐i8mmโ enables 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions, and it's on by default for-march=armv8.6-a. But fr fr, using this with architectures before Armv8.2-A is not supported. ๐ญf32mmโ enables 32-bit Floating point Matrix Multiply instructions. Also enables SVE instructions. Architectures before Armv8.2-A? Not supported, no cap. ๐f64mmโ enables 64-bit Floating point Matrix Multiply instructions. Also enables SVE instructions. And yeah, architectures before Armv8.2-A are not supported. ๐bf16โ enables brain half-precision floating-point instructions. Also enables Advanced SIMD and floating-point instructions. On by default for-march=armv8.6-a. Architectures before Armv8.2-A: not supported. ๐ls64โ enables the 64-byte atomic load and store instructions for accelerators. Enabled by default for-march=armv8.7-a. ๐ฅmopsโ enables the instructions that accelerate memory operations likememcpy,memmove, andmemset. Enabled by default for-march=armv8.8-a. โกflagmโ enables the Flag Manipulation instructions Extension. โจpauthโ enables the Pointer Authentication Extension. ๐ฆ
Okay so here's the gossip on how these features relate to each other, and it's giving โจdramaโจ:
Feature crypto implies aes, sha2, and simd, which implies fp. Conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2.
๐ฆ Adapteva Epiphany Options ๐ฆ
These -m options are defined for Adapteva Epiphany:
-mhalf-reg-fileโ Don't allocate any register in the ranger32...r63. That way your code can run on hardware variants that are missing those registers. ๐-mprefer-short-insn-regsโ Preferentially allocate registers that allow short instruction generation. Not me telling you this can increase instruction count tho โ so it might reduce or increase overall code size. It's giving chaos. ๐ญ-mbranch-cost=numโ Set the cost of branches to roughly num "simple" instructions. Just so you know, this cost is only a heuristic and is not guaranteed to produce consistent results across releases. ๐-mcmoveโ Enable the generation of conditional moves. ๐-mnops=numโ Emit num NOPs before every other generated instruction. Every. Other. One. ๐ซถ-mno-soft-cmpsfโ For single-precision floating-point comparisons, emit anfsubinstruction and test the flags. This is faster than a software comparison, but it can get incorrect results in the presence of NaNs, or when two different small numbers are compared such that their difference is calculated as zero. ๐ฌ The default is-msoft-cmpsf, which uses slower, but IEEE-compliant, software comparisons.-mstack-offset=numโ Set the offset between the top of the stack and the stack pointer. E.g., a value of 8 means that the eight bytes in the rangesp+0...sp+7can be used by leaf functions without stack allocation. Values other than 8 or 16 are untested and unlikely to work. ๐จ Also note that this option changes the ABI; compiling a program with a different stack offset than the libraries have been compiled with generally does not work. This option can be useful if you want to evaluate if a different stack offset would give you better code, but to actually use a different stack offset to build working programs, it is recommended to configure the toolchain with the appropriate--with-stack-offset=numoption.-mno-round-nearestโ Make the scheduler assume that the rounding mode has been set to truncating. The default is-mround-nearest. ๐ธ-mlong-callsโ If not otherwise specified by an attribute, assume all calls might be beyond the offset range of theb/blinstructions, and therefore load the function address into a register before performing a (otherwise direct) call. This is the default. โจ-mshort-callsโ If not otherwise specified by an attribute, assume all direct calls are in the range of theb/blinstructions, so use these instructions for direct calls. The default is-mlong-calls. ๐ฆ-msmall16โ Assume addresses can be loaded as 16-bit unsigned values. This does not apply to function addresses for which-mlong-callssemantics are in effect. ๐-mfp-mode=modeโ Set the prevailing mode of the floating-point unit. This determines the floating-point mode that is provided and expected at function call and return time. Making this mode match the mode you predominantly need at function start can make your programs smaller and faster by avoiding unnecessary mode switches. ๐
mode can be set to one the following values:
callerโ Any mode at function entry is valid, and retained or restored when the function returns, and when it calls other functions. This mode is useful for compiling libraries or other compilation units you might want to incorporate into different programs with different prevailing FPU modes, and the convenience of being able to use a single object file outweighs the size and speed overhead for any extra mode switching that might be needed, compared with what would be needed with a more specific choice of prevailing FPU mode. ๐truncateโ This is the mode used for floating-point calculations with truncating (i.e. round towards zero) rounding mode. That includes conversion from floating point to integer. ๐round-nearestโ This is the mode used for floating-point calculations with round-to-nearest-or-even rounding mode. ๐งintโ This is the mode used to perform integer calculations in the FPU, e.g. integer multiply, or integer multiply-and-accumulate. ๐
The default is -mfp-mode=caller.
-mno-split-lohi-mno-postinc-mno-postmodifyโ Code generation tweaks that disable, respectively, splitting of 32-bit loads, generation of post-increment addresses, and generation of post-modify addresses. The defaults aremsplit-lohi,-mpost-inc, and-mpost-modify. ๐-mnovect-doubleโ Change the preferred SIMD mode to SImode. The default is-mvect-double, which uses DImode as preferred SIMD mode. ๐ฅ-max-vect-align=numโ The maximum alignment for SIMD vector mode types. num may be 4 or 8. The default is 8. Note that this is an ABI change, even though many library function interfaces are unaffected if they don't use SIMD vector modes in places that affect size and/or alignment of relevant types. ๐ญ-msplit-vecmove-earlyโ Split vector moves into single word moves before reload. In theory this can give better register allocation, but so far the reverse seems to be generally the case. It's giving "sounds great, isn't". ๐-m1reg-regโ Specify a register to hold the constant -1, which makes loading small negative constants and certain bitmasks faster. Allowable values for reg arer43andr63, which specify use of that register as a fixed register, andnone, which means that no register is used for this purpose. The default is-m1reg-none. ๐
๐ AMD GCN Options ๐
These options are defined specifically for the AMD GCN port.
-march=gpu-mtune=gpuโ Set architecture type or tuning for gpu. Supported values for gpu are:fijiโ Compile for GCN3 Fiji devices (gfx803). ๐ฆgfx900โ Compile for GCN5 Vega 10 devices (gfx900). โญgfx906โ Compile for GCN5 Vega 20 devices (gfx906). ๐
-msram-ecc=on,-msram-ecc=off,-msram-ecc=anyโ bestie, this is how you tell the compiler what kind of SRAM-ECC device your binary is gonna live on: one with the feature turned on, one with it turned off, or honestly either mode. On some devices you can flip this per-process, but here's the tea: the compiled code has to match the device mode, no negotiating. The default isany, for the devices that even support it. ๐-mstack-size=bytesโ how manybytesof stack space should get requested for every single GPU thread (aka a wave-front)? ๐ซถ Heads up though: there can be a lot of threads and not a lot of memory, so think before you go wild. The size of the stack allocation can also mess with run-time performance, lowkey. Default is32KBwhen you're using OpenACC or OpenMP, and1MBotherwise. โจ-mxnackโ compiles binaries for devices where the XNACK feature is enabled. Some devices literally always require XNACK, some let the user configure it. Again: the compiled code must match the device mode. Default is-mno-xnack. And ngl, at present this option is just a placeholder for support that isn't implemented yet. ๐ญ
๐ ARC Options ๐
Okay so these next ones control the architecture variant your code is getting compiled for, periodt. ๐
-mbarrel-shifterโ generate instructions that the barrel shifter supports. This is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect. ๐-mjli-alwaysโ force calling a function using thejli_sinstruction. Valid only for the ARCv2 architecture, so don't try it anywhere else. ๐ซ-mcpu=cpuโ sets the architecture type, register usage, and instruction scheduling parameters forcpu. There are also shortcut alias options kicking around for backward compatibility and convenience. Supported values forcpuare:arc600โ compile for ARC600. Aliases:-mA6,-mARC600.arc601โ compile for ARC601. Alias:-mARC601.arc700โ compile for ARC700. Aliases:-mA7,-mARC700. This is the default when configured with--with-cpu=arc700.arcemโ compile for ARC EM.archsโ compile for ARC HS.emโ compile for ARC EM CPU with no hardware extensions.em4โ compile for ARC EM4 CPU.em4_dmipsโ compile for ARC EM4 DMIPS CPU.em4_fpusโ compile for ARC EM4 DMIPS CPU with the single-precision floating-point extension.em4_fpudaโ compile for ARC EM4 DMIPS CPU with single-precision floating-point and double assist instructions.hsโ compile for ARC HS CPU with no hardware extensions except the atomic instructions.hs34โ compile for ARC HS34 CPU.hs38โ compile for ARC HS38 CPU.hs38_linuxโ compile for ARC HS38 CPU with all hardware extensions on. โจarc600_normโ compile for ARC 600 CPU with "norm" instructions enabled.arc600_mul32x16โ compile for ARC 600 CPU with "norm" and 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU with "norm" and "mul64"-family instructions enabled.arc601_normโ compile for ARC 601 CPU with "norm" instructions enabled.arc601_mul32x16โ compile for ARC 601 CPU with "norm" and 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU with "norm" and "mul64"-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring a reduced register set. ๐ง
-mdpfp,-mdpfp-compactโ generate double-precision FPX instructions, tuned for the compact implementation. ๐-mdpfp-fastโ generate double-precision FPX instructions, tuned for the fast implementation. ๐ฅ-mno-dpfp-lrsrโ disables thelrandsrinstructions from using FPX extension aux registers. ๐ซ-meaโ generate extended arithmetic instructions. Currently onlydivaw,adds,subs, andsat16are supported. Only valid for-mcpu=ARC700. ๐-mno-mpyโ do not generatempy-family instructions for ARC700. Heads up bestie, this option is deprecated. โ ๏ธ-mmul32x16โ generate 32x16-bit multiply and multiply-accumulate instructions. ๐-mmul64โ generatemul64andmulu64instructions. Only valid for-mcpu=ARC600. ๐ธ-mnormโ generatenorminstructions. This is the default if-mcpu=ARC700is in effect. โจ-mspfp,-mspfp-compactโ generate single-precision FPX instructions, tuned for the compact implementation. ๐-mspfp-fastโ generate single-precision FPX instructions, tuned for the fast implementation. ๐ฅ-msimdโ enables generation of ARC SIMD instructions via target-specific builtins. Only valid for-mcpu=ARC700. ๐-msoft-floatโ okay so plot twist, this option is ignored; it's only here for compatibility purposes. Software floating-point code is emitted by default, and that default can be overridden by FPX options:-mspfp,-mspfp-compact, or-mspfp-fastfor single precision, and-mdpfp,-mdpfp-compact, or-mdpfp-fastfor double precision. ๐-mswapโ generateswapinstructions. ๐-matomicโ enables use of the locked load/store conditional extension to implement atomic memory built-in functions. Not available for ARC 6xx or ARC EM cores. ๐-mdiv-remโ enabledivandreminstructions for ARCv2 cores. โ-mcode-densityโ enable code density instructions for ARC EM. This option is on by default for ARC HS. ๐-mll64โ enable double load/store operations for ARC HS cores. ๐ซถ-mtp-regno=regnoโ specify the thread pointer register number. ๐ข-mmpy-option=multoโ compile ARCv2 code with a multiplier design option. You can specify the option using either a string or a numeric value formulto.wlh1is the default value. The recognized values are:0,noneโ no multiplier available.1,wโ 16x16 multiplier, fully pipelined. The following instructions are enabled:mpywandmpyuw.2,wlh1โ 32x32 multiplier, fully pipelined (1 stage). The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.3,wlh2โ 32x32 multiplier, fully pipelined (2 stages). The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.4,wlh3โ two 16x16 multipliers, blocking, sequential. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.5,wlh4โ one 16x16 multiplier, blocking, sequential. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.6,wlh5โ one 32x4 multiplier, blocking, sequential. The following instructions are additionally enabled:mpy,mpyu,mpym,mpymu, andmpy_s.7,plus_dmpyโ ARC HS SIMD support.8,plus_macdโ ARC HS SIMD support.9,plus_qmacwโ ARC HS SIMD support.
This option is only available for ARCv2 cores. ๐
-mfpu=fpuโ enables support for specific floating-point hardware extensions for ARCv2 cores. Supported values forfpuare:fpusโ enables support for single-precision floating-point hardware extensions.fpudโ enables support for double-precision floating-point hardware extensions. The single-precision floating-point extension is also enabled. Not available for ARC EM.fpudaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point extension is also enabled. This option is only available for ARC EM.fpuda_divโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point, square-root, and divide extensions are also enabled. This option is only available for ARC EM.fpuda_fmaโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. The single-precision floating-point and fused multiply and add hardware extensions are also enabled. This option is only available for ARC EM.fpuda_allโ enables support for double-precision floating-point hardware extensions using double-precision assist instructions. All single-precision floating-point hardware extensions are also enabled. This option is only available for ARC EM.fpus_divโ enables support for single-precision floating-point, square-root and divide hardware extensions.fpud_divโ enables support for double-precision floating-point, square-root and divide hardware extensions. This option includes optionfpus_div. Not available for ARC EM.fpus_fmaโ enables support for single-precision floating-point and fused multiply and add hardware extensions.fpud_fmaโ enables support for double-precision floating-point and fused multiply and add hardware extensions. This option includes optionfpus_fma. Not available for ARC EM.fpus_allโ enables support for all single-precision floating-point hardware extensions.fpud_allโ enables support for all single- and double-precision floating-point hardware extensions. Not available for ARC EM.
๐๐
-mirq-ctrl-saved=register-range, blink, lp_countโ specifies general-purpose registers that the processor automatically saves/restores on interrupt entry and exit.register-rangeis specified as two registers separated by a dash. The register range always starts withr0, and the upper limit is thefpregister.blinkandlp_countare optional. This option is only valid for ARC EM and ARC HS cores. ๐-mrgf-banked-regs=number โ tells the compiler how many registers get replicated into the second register bank when you enter a fast interrupt. Bestie, fast interrupts are the interrupts with the absolute highest priority level, P0 โ main character interrupts, truly ๐. They only savePCandSTATUS32registers so they can dodge memory transactions during interrupt entry and exit. Use this one when you're running fast interrupts on an ARC V2 family processor. The values you're allowed to use are4,8,16, and32. That's it, that's the list.-mlpc-width=width โ sets the width of thelp_countregister. Valid values for width are8,16,20,24,28and32bits, and the default width is locked in at32bits. If the width is less than 32, the compiler will not try to transform loops in your program to use the zero-delay loop mechanism unless it's known that thelp_countregister can hold the required loop-counter value. Depending on the width you pick, the compiler and run-time library might keep using the loop mechanism for various needs anyway. This option defines the macro__ARC_LPC_WIDTH__with the value of width. Cute, right? ๐-mrf16โ instructs the compiler to generate code for a 16-entry register file. This option defines the__ARC_RF16__preprocessor macro.-mbranch-indexโ turns on use ofbiorbihinstructions to implement jump tables.
The following options get passed straight through to the assembler, and they also define preprocessor macro symbols. Two-for-one deal, we love that ๐ซถ
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. Also sets the preprocessor symbol__Xdsp_packa. Heads up: this option is deprecated ๐ซ .-mdvbfโ passed down to the assembler to enable the dual Viterbi butterfly extension. Also sets the preprocessor symbol__Xdvbf. This option is deprecated.-mlockโ passed down to the assembler to enable the locked load/store conditional extension. Also sets the preprocessor symbol__Xlock.-mmac-d16โ passed down to the assembler. Also sets the preprocessor symbol__Xxmac_d16. This option is deprecated.-mmac-24โ passed down to the assembler. Also sets the preprocessor symbol__Xxmac_24. This option is deprecated.-mrtscโ passed down to the assembler to enable the 64-bit time-stamp counter extension instruction. Also sets the preprocessor symbol__Xrtsc. This option is deprecated.-mswapeโ passed down to the assembler to enable the swap byte ordering extension instruction. Also sets the preprocessor symbol__Xswape.-mtelephonyโ passed down to the assembler to enable dual- and single-operand instructions for telephony. Also sets the preprocessor symbol__Xtelephony. This option is deprecated.-mxyโ passed down to the assembler to enable the XY memory extension. Also sets the preprocessor symbol__Xxy.
The following options control how the assembly code gets annotated โจ:
-misizeโ annotate assembler instructions with estimated addresses.-mannotate-alignโ explain what alignment considerations led to the decision to make an instruction short or long.
The following options get passed through to the linker ๐:
-marclinuxโ passed through to the linker, to specify use of thearclinuxemulation. This option is enabled by default in tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets when profiling is not requested.-marclinux_profโ passed through to the linker, to specify use of thearclinux_profemulation. This option is enabled by default in tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets when profiling is requested.
The following options control the semantics of generated code ๐ง :
-mlong-callsโ generate calls as register indirect calls, which gives you access to the full 32-bit address range. The whole range, bestie. No crumbs.-mmedium-callsโ don't use less than 25-bit addressing range for calls, which is the offset available for an unconditional branch-and-link instruction. Conditional execution of function calls is suppressed here, so you can use the 25-bit range instead of the 21-bit range with conditional branch-and-link. This is the default for tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets.-G numโ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. The default value of num is4for any ARC configuration, or8when we have double load/store operations.-mno-sdataโ do not generate sdata references. This is the default for tool chains built forarc-linux-uclibcandarceb-linux-uclibctargets.-mvolatile-cacheโ use ordinarily cached memory accesses for volatile references. This is the default.-mno-volatile-cacheโ enable cache bypass for volatile references.
The following options fine tune code generation ๐ง:
-malign-callโ does nothing. Preserved for backward compatibility.-mauto-modify-regโ enable the use of pre/post modify with register displacement.-mbbit-peepholeโ enable bbit peephole2.-mno-brccโ this option disables a target-specific pass inarc_reorgto generate compare-and-branch (brcc) instructions. It has no effect on generation of these instructions driven by the combiner pass.-mcase-vector-pcrelโ use PC-relative switch case tables to enable case table shortening. This is the default for-Os.-mcompact-casesiโ enable compactcasesipattern. This is the default for-Os, and only available for ARCv1 cores. This option is deprecated.-mno-cond-execโ disable the ARCompact-specific pass to generate conditional execution instructions.
Okay so here's the lore ๐: due to delay slot scheduling and interactions between operand numbers, literal sizes, instruction lengths, and the support for conditional execution, the target-independent pass to generate conditional execution is often lacking, so the ARC port has kept a special pass around that tries to find more conditional execution generation opportunities after register allocation, branch shortening, and delay slot scheduling have been done. This pass generally โ but not always โ improves performance and code size, at the cost of extra compilation time, which is why there's an option to switch it off. If you have a problem with call instructions exceeding their allowable offset range because they are conditionalized, you should consider using -mmedium-calls instead.
-mearly-cbranchsiโ enable pre-reload use of thecbranchsipattern.-mexpand-adddiโ expandadddi3andsubdi3at RTL generation time intoadd.f,adcetc. This option is deprecated.-mindexed-loadsโ enable the use of indexed loads. This can be problematic because some optimizers then assume that indexed stores exist, which is not the case ๐ญ.-mlraโ enable Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e.-mno-lra).-mlra-priority-noneโ don't indicate any priority for target registers.-mlra-priority-compactโ indicate target register priority forr0..r3/r12..r15.-mlra-priority-noncompactโ reduce target register priority forr0..r3/r12..r15.-mmillicodeโ when optimizing for size (using-Os), prologues and epilogues that have to save or restore a large number of registers are often shortened by using a call to a special function in libgcc; this is referred to as a millicode call. Since these calls can pose performance issues, and/or cause linking issues when linking in a nonstandard way, this option is provided to turn millicode call generation on or off.-mcode-density-frameโ this option enables the compiler to emitenterandleaveinstructions. These instructions are only valid for CPUs with the code-density feature.-mmixed-codeโ does nothing. Preserved for backward compatibility.-mq-classโ this option is deprecated. Enable q instruction alternatives. This is the default for-Os.-mRcqโ enable Rcq constraint handling. Most short code generation depends on this. This is the default.-mRcwโ enable Rcw constraint handling. Most ccfsm condexec mostly depends on this. This is the default.-msize-level=level โ fine-tune size optimization with regards to instruction lengths and alignment. The recognized values for level are:0โ No size optimization. This level is deprecated and treated like1.1โ Short instructions are used opportunistically.2โ In addition, alignment of loops and of code after barriers are dropped.3โ In addition, optional data alignment is dropped, and the optionOsis enabled.
This defaults to 3 when -Os is in effect. Otherwise, the behavior when this is not set is equivalent to level 1.
-mtune=cpu โ set instruction scheduling parameters for cpu, overriding any implied by-mcpu=.
Supported values for cpu are
ARC600โ Tune for ARC600 CPU.ARC601โ Tune for ARC601 CPU.ARC700โ Tune for ARC700 CPU with standard multiplier block.ARC700-xmacโ Tune for ARC700 CPU with XMAC block.ARC725Dโ Tune for ARC725D CPU.ARC750Dโ Tune for ARC750D CPU.
-mmultcost=num โ cost to assume for a multiply instruction, with4being equal to a normal instruction.-munalign-prob-threshold=probability โ does nothing. Preserved for backward compatibility.
The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release. Consider this your official warning ๐จ:
-margonautโ obsolete FPX.-mbig-endian,-EBโ compile code for big-endian targets. Use of these options is now deprecated. Big-endian code is supported by configuring GCC to buildarceb-elf32andarceb-linux-uclibctargets, for which big endian is the default.-mlittle-endian,-ELโ compile code for little-endian targets. Use of these options is now deprecated. Little-endian code is supported by configuring GCC to buildarc-elf32andarc-linux-uclibctargets, for which little endian is the default.-mbarrel_shifterโ replaced by-mbarrel-shifter.-mdpfp_compactโ replaced by-mdpfp-compact.-mdpfp_fastโ replaced by-mdpfp-fast.-mdsp_packaโ girlypop this one's gone, it got replaced by-mdsp-packa(underscore to hyphen, glow up ๐ ).-mEAโ replaced by-mea. lowercase era, we love to see it.-mmac_24โ replaced by-mmac-24.-mmac_d16โ replaced by-mmac-d16.-mspfp_compactโ replaced by-mspfp-compact.-mspfp_fastโ replaced by-mspfp-fast.-mtune=cpuโ so the valuesarc600,arc601,arc700andarc700-xmacfor cpu are replaced byARC600,ARC601,ARC700andARC700-xmacrespectively. yes bestie, all caps now, it's giving main character ๐-multcost=numโ replaced by-mmultcost. (the=went to therapy and left)
๐ ARM Options ๐
okay these -m options are the ones defined for the ARM port specifically. buckle up buttercup, there's a lot ๐ฆ
-mabi=nameโ generate code for the ABI you name. permissible values are:apcs-gnu,atpcs,aapcs,aapcs-linuxandiwmmxt.-mapcs-frameโ generate a stack frame that's compliant with the ARM Procedure Call Standard for all functions, even when it's not strictly necessary for the code to actually run right. if you also pass-fomit-frame-pointerwith this, then stack frames just don't get generated for leaf functions. the default is-mno-apcs-frame.
โ ๏ธ this option is deprecated. it's giving vintage but like, in the "please stop using this" way.
-mapcsโ this is just a synonym for-mapcs-frame, and it is deprecated too.-mthumb-interworkโ generate code that supports calling back and forth between the ARM and Thumb instruction sets. without this option, on pre-v5 architectures the two instruction sets literally cannot be reliably used inside one program ๐ญ. the default is-mno-thumb-interwork, because you get slightly larger code when you specify-mthumb-interwork. in AAPCS configurations this option is meaningless (it just sits there, no thoughts head empty).-mno-sched-prologโ stops the reordering of instructions in the function prologue, and stops those instructions getting merged with instructions in the function's body. what that buys you: every function starts with a recognizable set of instructions (or actually one of a choice from a small set of different function prologues), and that info can be used to locate where functions start inside an executable piece of code ๐. the default is-msched-prolog.-mfloat-abi=nameโ specifies which floating-point ABI to use. permissible values are:soft,softfpandhard.softโ causes GCC to generate output containing library calls for floating-point operations.softfpโ allows generating code that uses hardware floating-point instructions, but still uses the soft-float calling conventions.hardโ allows generation of floating-point instructions and uses FPU-specific calling conventions.
the default depends on the specific target configuration. note: the hard-float and soft-float ABIs are not link-compatible โ you have to compile your entire program with the same ABI and link with a compatible set of libraries. no mixing bestie, this is not a smoothie ๐
-mgeneral-regs-onlyโ generate code that uses only the general-purpose registers. this stops the compiler from using floating-point and Advanced SIMD registers, but it does not put any restrictions on the assembler.-mlittle-endianโ generate code for a processor running in little-endian mode. this is the default for all standard configurations ๐-mbig-endianโ generate code for a processor running in big-endian mode; the default is to compile code for a little-endian processor.-mbe8,-mbe32โ when you're linking a big-endian image, these select between BE8 and BE32 formats. the option has no effect for little-endian images and is ignored (it's just vibing). the default depends on the selected target architecture: for ARMv6 and later architectures the default is BE8, and for older architectures the default is BE32.
๐จ BE32 format has been deprecated by ARM. rip bozo.
-march=name[+extension...]โ this specifies the name of the target ARM architecture. GCC uses this name to figure out what kind of instructions it's allowed to emit when generating assembly code. you can use this option alongside-mcpu=or instead of it.
permissible names are:
armv4t, armv5t, armv5te, armv6, armv6j, armv6k, armv6kz, armv6t2, armv6z, armv6zk, armv7, armv7-a, armv7ve, armv8-a, armv8.1-a, armv8.2-a, armv8.3-a, armv8.4-a, armv8.5-a, armv8.6-a, armv9-a, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, armv9-a, iwmmxt and iwmmxt2.
additionally, the following architectures โ which lack support for the Thumb execution state โ are recognized, but support is deprecated: armv4.
a lot of these architectures support extensions โจ you add them by appending +extension to the architecture name. extension options get processed in order and the capabilities accumulate. an extension will also enable any necessary base extensions it depends on โ for example, the +crypto extension will always enable the +simd extension. the exception to this additive construction is for extensions prefixed with +no...: those disable the specified option and any other extensions that might depend on that extension being present.
for example, -march=armv7-a+simd+nofp+vfpv4 is equivalent to writing -march=armv7-a+vfpv4, since the +simd option is entirely disabled by the +nofp option that follows it. the audacity of +nofp, honestly ๐ญ
most extension names are generically named, but their effect depends on the architecture they're applied to. for example, the +simd option can be applied to both armv7-a and armv8-a architectures, but it'll enable the original ARMv7-A Advanced SIMD (Neon) extensions for armv7-a, and the ARMv8-A variant for armv8-a. same name, different personality ๐
the list below has the supported extensions for each architecture. architectures not mentioned do not support any extensions.
armv5te,armv6,armv6j,armv6k,armv6kz,armv6t2,armv6z,armv6zk+fpโ the VFPv2 floating-point instructions. the extension+vfpv2can be used as an alias for this extension.+nofpโ disable the floating-point instructions.
armv7- the common subset of the ARMv7-A, ARMv7-R and ARMv7-M architectures.
+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this extension. note that floating-point is not supported by the base ARMv7-M architecture, but it is compatible with both the ARMv7-A and ARMv7-R architectures.+nofpโ disable the floating-point instructions.
armv7-a+mpโ the multiprocessing extension.+secโ the security extension.+fpโ the VFPv3 floating-point instructions, with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this extension.+simdโ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extensions+neonand+neon-vfpv3can be used as aliases for this extension.+vfpv3โ the VFPv3 floating-point instructions, with 32 double-precision registers.+vfpv3-d16-fp16โ the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.+vfpv3-fp16โ the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.+vfpv4-d16โ the VFPv4 floating-point instructions, with 16 double-precision registers.+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers.+neon-fp16โ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.+neon-vfpv4โ the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions.+nosimdโ disable the Advanced SIMD instructions (it does not disable floating point).+nofpโ disable the floating-point and Advanced SIMD instructions.
armv7ve- the extended version of the ARMv7-A architecture with support for virtualization.
+fpโ the VFPv4 floating-point instructions, with 16 double-precision registers. the extension+vfpv4-d16can be used as an alias for this extension.+simdโ the Advanced SIMD (Neon) v2 and the VFPv4 floating-point instructions. the extension+neon-vfpv4can be used as an alias for this extension.+vfpv3-d16โ the VFPv3 floating-point instructions, with 16 double-precision registers.+vfpv3โ the VFPv3 floating-point instructions, with 32 double-precision registers.+vfpv3-d16-fp16โ the VFPv3 floating-point instructions, with 16 double-precision registers and the half-precision floating-point conversion operations.+vfpv3-fp16โ the VFPv3 floating-point instructions, with 32 double-precision registers and the half-precision floating-point conversion operations.+vfpv4-d16โ the VFPv4 floating-point instructions, with 16 double-precision registers.+vfpv4โ the VFPv4 floating-point instructions, with 32 double-precision registers.+neonโ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions. the extension+neon-vfpv3can be used as an alias for this extension.+neon-fp16โ the Advanced SIMD (Neon) v1 and the VFPv3 floating-point instructions, with the half-precision floating-point conversion operations.+nosimdโ disable the Advanced SIMD instructions (it does not disable floating point).+nofpโ disable the floating-point and Advanced SIMD instructions.
armv8-a+crcโ the Cyclic Redundancy Check (CRC) instructions.+simdโ the ARMv8-A Advanced SIMD and floating-point instructions.+cryptoโ the cryptographic instructions.
+nocryptoโ Disable the cryptographic instructions. bye crypto ๐+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions. all of it? gone, bestie.+sbโ Speculation Barrier Instruction. โจ+predresโ Execution and Data Prediction Restriction Instructions.
armv8.1-a โจ
+simdโ The ARMv8.1-A Advanced SIMD and floating-point instructions.+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions.+nocryptoโ Disable the cryptographic instructions.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.+sbโ Speculation Barrier Instruction.+predresโ Execution and Data Prediction Restriction Instructions.
armv8.2-a ๐ฆ
armv8.3-a ๐ฆ
Both of these share the same extension menu, so here it is once, no gatekeeping:
+fp16โ The half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions.+fp16fmlโ The half-precision floating-point fmla extension. This also enables the half-precision floating-point extension and Advanced SIMD and floating-point instructions.+simdโ The ARMv8.1-A Advanced SIMD and floating-point instructions.+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions.+dotprodโ Enable the Dot Product extension. This also enables Advanced SIMD instructions.+nocryptoโ Disable the cryptographic extension.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.+sbโ Speculation Barrier Instruction.+predresโ Execution and Data Prediction Restriction Instructions.+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions.
armv8.4-a ๐
+fp16โ The half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension.+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension.+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension.+nocryptoโ Disable the cryptographic extension.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.+sbโ Speculation Barrier Instruction.+predresโ Execution and Data Prediction Restriction Instructions.+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions.
armv8.5-a ๐ธ
+fp16โ The half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension.+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension.+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension.+nocryptoโ Disable the cryptographic extension.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions.
armv8.6-a ๐
+fp16โ The half-precision floating-point data processing instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension and the half-precision floating-point fmla extension.+simdโ The ARMv8.3-A Advanced SIMD and floating-point instructions as well as the Dot Product extension.+cryptoโ The cryptographic instructions. This also enables the Advanced SIMD and floating-point instructions as well as the Dot Product extension.+nocryptoโ Disable the cryptographic extension.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.+i8mmโ 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. This also enables Advanced SIMD and floating-point instructions.
armv7-r ๐
+fp.spโ The single-precision VFPv3 floating-point instructions. The extension+vfpv3xdcan be used as an alias for this extension.+fpโ The VFPv3 floating-point instructions with 16 double-precision registers. The extension+vfpv3-d16can be used as an alias for this extension.+vfpv3xd-d16-fp16โ The single-precision VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations.+vfpv3-d16-fp16โ The VFPv3 floating-point instructions with 16 double-precision registers and the half-precision floating-point conversion operations.+nofpโ Disable the floating-point extension.+idivโ The ARM-state integer division instructions.+noidivโ Disable the ARM-state integer division extension.
armv7e-m ๐ง
+fpโ The single-precision VFPv4 floating-point instructions.+fpv5โ The single-precision FPv5 floating-point instructions.+fp.dpโ The single- and double-precision FPv5 floating-point instructions.+nofpโ Disable the floating-point extensions.
armv8.1-m.main ๐
+dspโ The DSP instructions.+mveโ The M-Profile Vector Extension (MVE) integer instructions.+mve.fpโ The M-Profile Vector Extension (MVE) integer and single precision floating-point instructions.+fpโ The single-precision floating-point instructions.+fp.dpโ The single- and double-precision floating-point instructions.+nofpโ Disable the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7.
armv8-m.main ๐ซถ
+dspโ The DSP instructions.+nodspโ Disable the DSP extension.+fpโ The single-precision floating-point instructions.+fp.dpโ The single- and double-precision floating-point instructions.+nofpโ Disable the floating-point extension.+cdecp0,+cdecp1, ... ,+cdecp7โ Enable the Custom Datapath Extension (CDE) on selected coprocessors according to the numbers given in the options in the range 0 to 7.
armv8-r โญ
+crcโ The Cyclic Redundancy Check (CRC) instructions.+fp.spโ The single-precision FPv5 floating-point instructions.+simdโ The ARMv8-A Advanced SIMD and floating-point instructions.+cryptoโ The cryptographic instructions.+nocryptoโ Disable the cryptographic instructions.+nofpโ Disable the floating-point, Advanced SIMD and cryptographic instructions.-march=nativeโ causes the compiler to auto-detect the architecture of the build computer. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful the option has no effect.-mtune=nameโ bestie, this is the "which ARM chip am I vibing with" knob ๐ . It names the target ARM processor GCC should tune the performance of the code for. Some ARM implementations genuinely get better perf from this, no cap. The permissible names are:arm7tdmi,arm7tdmi-s,arm710t,arm720t,arm740t,strongarm,strongarm110,strongarm1100,strongarm1110,arm8,arm810,arm9,arm9e,arm920,arm920t,arm922t,arm946e-s,arm966e-s,arm968e-s,arm926ej-s,arm940t,arm9tdmi,arm10tdmi,arm1020t,arm1026ej-s,arm10e,arm1020e,arm1022e,arm1136j-s,arm1136jf-s,mpcore,mpcorenovfp,arm1156t2-s,arm1156t2f-s,arm1176jz-s,arm1176jzf-s,generic-armv7-a,cortex-a5,cortex-a7,cortex-a8,cortex-a9,cortex-a12,cortex-a15,cortex-a17,cortex-a32,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,cortex-a76,cortex-a76ae,cortex-a77,cortex-a78,cortex-a78ae,cortex-a78c,cortex-a710,ares,cortex-r4,cortex-r4f,cortex-r5,cortex-r7,cortex-r8,cortex-r52,cortex-r52plus,cortex-m0,cortex-m0plus,cortex-m1,cortex-m3,cortex-m4,cortex-m7,cortex-m23,cortex-m33,cortex-m35p,cortex-m55,cortex-x1,cortex-m1.small-multiply,cortex-m0.small-multiply,cortex-m0plus.small-multiply,exynos-m1,marvell-pj4,neoverse-n1,neoverse-n2,neoverse-v1,xscale,iwmmxt,iwmmxt2,ep9312,fa526,fa626,fa606te,fa626te,fmp626,fa726te,xgene1.
AND โ plot twist โ this option can also tell GCC to tune for a big.LITTLE system โจ. Permissible names for that are: cortex-a15.cortex-a7, cortex-a17.cortex-a7, cortex-a57.cortex-a53, cortex-a72.cortex-a53, cortex-a72.cortex-a35, cortex-a73.cortex-a53, cortex-a75.cortex-a55, cortex-a76.cortex-a55.
-mtune=generic-arch says "tune me for a blend of processors inside architecture arch". The whole goal is code that runs well on the currently most popular processors โ balancing the optimizations that help some CPUs in the range against avoiding the performance pitfalls of the others ๐. Heads up though: the effects of this option may change in future GCC versions, because CPU models come and go, iykyk ๐.
-mtune lets you use the same extension options as -mcpu, but the extension options do not affect the tuning of the generated code. Periodt.
-mtune=native makes the compiler auto-detect the CPU of the build computer ๐ต๏ธโโ๏ธ. At present this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful, the option has no effect (it's giving "we tried" ๐ญ).
-mcpu=name[+extension...]โ this one names the target ARM processor, and GCC is so efficient about it: it uses the name to derive the target ARM architecture (as if you'd said-march) and the ARM processor type to tune for performance (as if you'd said-mtune) ๐. But when this option is used alongside-marchor-mtune, those options take precedence over the appropriate part of this one. Sorry bestie, they're the main characters.
Many of the supported CPUs implement optional architectural extensions, and where that's the case those extensions are normally enabled by default. If implementations exist that lack the extension, the extension syntax is how you disable the ones that got omitted. For floating-point and Advanced SIMD (Neon) instructions, the settings of -mfloat-abi and -mfpu also have to be considered: floating-point and Advanced SIMD instructions will only be used if -mfloat-abi is not set to soft; and any setting of -mfpu other than auto will override the available floating-point and SIMD extension instructions.
For example, cortex-a9 can be found in three major configurations: integer only, with just a floating-point unit, or with floating-point and Advanced SIMD. The default is to enable all the instructions, but the extensions +nosimd and +nofp can be used to disable just the SIMD, or both the SIMD and floating-point instructions respectively ๐ฆ.
Permissible names for this option are the same as those for -mtune.
The following extension options are common to the listed CPUs:
+nodspโ Disable the DSP instructions oncortex-m33,cortex-m35p.+nofpโ Disables the floating-point instructions onarm9e,arm946e-s,arm966e-s,arm968e-s,arm10e,arm1020e,arm1022e,arm926ej-s,arm1026ej-s,cortex-r5,cortex-r7,cortex-r8,cortex-m4,cortex-m7,cortex-m33andcortex-m35p. Disables the floating-point and SIMD instructions ongeneric-armv7-a,cortex-a5,cortex-a7,cortex-a8,cortex-a9,cortex-a12,cortex-a15,cortex-a17,cortex-a15.cortex-a7,cortex-a17.cortex-a7,cortex-a32,cortex-a35,cortex-a53andcortex-a55.+nofp.dpโ Disables the double-precision component of the floating-point instructions oncortex-r5,cortex-r7,cortex-r8,cortex-r52,cortex-r52plusandcortex-m7.+nosimdโ Disables the SIMD (but not floating-point) instructions ongeneric-armv7-a,cortex-a5,cortex-a7andcortex-a9.+cryptoโ Enables the cryptographic instructions oncortex-a32,cortex-a35,cortex-a53,cortex-a55,cortex-a57,cortex-a72,cortex-a73,cortex-a75,exynos-m1,xgene1,cortex-a57.cortex-a53,cortex-a72.cortex-a53,cortex-a73.cortex-a35,cortex-a73.cortex-a53andcortex-a75.cortex-a55.
Additionally, the generic-armv7-a pseudo target defaults to VFPv3 with 16 double-precision registers ๐. It supports the following extension options: mp, sec, vfpv3-d16, vfpv3, vfpv3-d16-fp16, vfpv3-fp16, vfpv4-d16, vfpv4, neon, neon-vfpv3, neon-fp16, neon-vfpv4. The meanings are the same as for the extensions to -march=armv7-a.
-mcpu=generic-arch is also permissible, and is equivalent to -march=arch -mtune=generic-arch. See -mtune for more information.
-mcpu=native causes the compiler to auto-detect the CPU of the build computer ๐. At present, this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect is unsuccessful, the option has no effect.
-mfpu=nameโ tells everyone what floating-point hardware (or hardware emulation) is available on the target ๐ธ. Permissible names are:auto,vfpv2,vfpv3,vfpv3-fp16,vfpv3-d16,vfpv3-d16-fp16,vfpv3xd,vfpv3xd-fp16,neon-vfpv3,neon-fp16,vfpv4,vfpv4-d16,fpv4-sp-d16,neon-vfpv4,fpv5-d16,fpv5-sp-d16,fp-armv8,neon-fp-armv8andcrypto-neon-fp-armv8. Note thatneonis an alias forneon-vfpv3andvfpis an alias forvfpv2.
The setting auto is the default and it's special โจ โ it makes the compiler select the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.
If the selected floating-point hardware includes the NEON extension (e.g. -mfpu=neon), note that floating-point operations are not generated by GCC's auto-vectorization pass unless -funsafe-math-optimizations is also specified. Why? Because NEON hardware does not fully implement the IEEE 754 standard for floating-point arithmetic (in particular, denormal values are treated as zero), so using NEON instructions may lead to a loss of precision ๐ญ. Not the precision bestie.
You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas ๐
.
-mfp16-format=nameโ Specify the format of the__fp16half-precision floating-point type. Permissible names arenone,ieee, andalternative; the default isnone, in which case the__fp16type is not defined ๐.-mstructure-size-boundary=nโ The sizes of all structures and unions get rounded up to a multiple of the number of bits set by this option. Permissible values are8,32and64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is8. A value of64is only allowed if the underlying ABI supports it.
Specifying a larger number can produce faster, more efficient code ๐ฅ, but it can also increase the size of the program. Different values are potentially incompatible. Code compiled with one value cannot necessarily expect to work with code or libraries compiled with another value, if they exchange information using structures or unions.
This option is deprecated. ๐
-mabort-on-noreturnโ Generate a call to the functionabortat the end of anoreturnfunction. It is executed if the function tries to return ๐.-mlong-calls-mno-long-callsโ Tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register ๐. This switch is needed if the target function lies outside of the 64-megabyte addressing range of the offset-based version of subroutine call instruction.
Even if this switch is enabled, not all function calls are turned into long calls. The heuristic is that static functions, functions that have the short_call attribute, functions that are inside the scope of a #pragma no_long_calls directive, and functions whose definitions have already been compiled within the current compilation unit are not turned into long calls. The exceptions to this rule are that weak function definitions, functions with the long_call attribute or the section attribute, and functions that are within the scope of a #pragma long_calls directive are always turned into long calls ๐.
This feature is not enabled by default. Specifying -mno-long-calls restores the default behavior, as does placing the function calls within the scope of a #pragma long_calls_off directive. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers ๐ฆ.
-msingle-pic-baseโ Treat the register used for PIC addressing as read-only, rather than loading it in the prologue for each function ๐. The runtime system is responsible for initializing this register with an appropriate value before execution begins. So like, that's on the runtime, not on us.-mpic-register=regโ Specify the register to be used for PIC addressing ๐ฏ. For the standard PIC base case, the default is any suitable register determined by the compiler. For the single PIC base case, the default isR9if the target is EABI based or stack-checking is enabled, otherwise the default isR10.
-mpic-data-is-text-relativeโ bestie, this one says: assume the gap between the text segment and the data segment is locked in at static link time ๐. That lets GCC use PC-relative addressing to grab stuff it knows lives in the data segment. For non-VxWorks RTP targets it's on by default โจ. And if you turn it off on those targets, it'll switch on-msingle-pic-baseby default. Little domino effect, iconic.-mpoke-function-nameโ writes the name of every function straight into the text section, sitting right before the function prologue. The generated code looks like this:
t0
.ascii "arm_poke_function_name", 0
.align
t1
.word 0xff000000 + (t1 - t0)
arm_poke_function_name
mov ip, sp
stmfd sp!, {fp, ip, lr, pc}
sub fp, ip, #4
So when you're doing a stack backtrace, the code can peek at the value of pc stored at fp + 0 ๐. If the trace function then looks at location pc - 12 and the top 8 bits are set, then we know there's a function name embedded immediately before this location, and it has length ((pc[-3]) & 0xff000000). Detective work fr fr ๐.
-mthumb-marmโ pick your fighter: code that executes in ARM state, or code that executes in Thumb state ๐ . For most configurations the default is ARM state, but that default can be changed by configuring GCC with the--with-mode=stateconfigure option. You can also override ARM/Thumb mode per function using thetarget("thumb")andtarget("arm")function attributes or pragmas. Per-function vibes, we love to see it.-mflip-thumbโ switches ARM/Thumb modes on alternating functions. This option exists purely for regression testing of mixed Thumb/ARM code generation, and it is not meant for ordinary use when compiling code ๐. It's a compiler-dev toy, not a you toy.-mtpcs-frameโ generates a stack frame that's compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that doesn't call any other functions โ it's just out there living its solo life ๐.) The default is-mno-tpcs-frame.-mtpcs-leaf-frameโ same energy but for all leaf functions. (Again: a leaf function is one that does not call any other functions.) The default is-mno-apcs-leaf-frame.-mcallee-super-interworkingโ gives every externally visible function in the file being compiled an ARM instruction set header that switches to Thumb mode before running the rest of the function. This lets those functions be called from non-interworking code ๐ซถ. Heads up: this option is not valid in AAPCS configurations, because interworking is already enabled by default there.-mcaller-super-interworkingโ lets calls through function pointers (including virtual functions) execute correctly no matter whether the target code was compiled for interworking or not. There's a small overhead in the cost of executing a function pointer if this is enabled โ ๏ธ. And same as above: not valid in AAPCS configurations, because interworking is on by default there.-mtp=nameโ specifies the access model for the thread local storage pointer. Valid models aresoft, which generates calls to__aeabi_read_tp;cp15, which fetches the thread pointer fromcp15directly (supported in thearm6karchitecture); andauto, which uses the best available method for the selected processor ๐. The default setting isauto.-mtls-dialect=dialectโ specifies the dialect to use for accessing thread local storage. Two dialects are supported โgnuandgnu2. Thegnudialect selects the original GNU scheme for supporting local and global dynamic TLS models. Thegnu2dialect selects the GNU descriptor scheme, which gives better performance for shared libraries ๐. The GNU descriptor scheme is compatible with the original scheme, but it does require new assembler, linker and library support. Initial and local exec TLS models are unaffected by this option and always use the original scheme.-mword-relocationsโ only generates absolute relocations on word-sized values (i.e.R_ARM_ABS32). This is enabled by default on targets (uClinux, SymbianOS) where the runtime loader imposes this restriction, and when-fpicor-fPICis specified. This option conflicts with-mslow-flash-dataโ they cannot sit together, no cap ๐.-mfix-cortex-m3-ldrdโ some Cortex-M3 cores can cause data corruption whenldrdinstructions with overlapping destination and base registers are used ๐ญ. This option avoids generating those instructions. It's enabled by default when-mcpu=cortex-m3is specified.-mfix-cortex-a57-aes-1742098-mno-fix-cortex-a57-aes-1742098-mfix-cortex-a72-aes-1655431-mno-fix-cortex-a72-aes-1655431โ enable (or disable) mitigation for an erratum on Cortex-A57 and Cortex-A72 that affects the AES cryptographic instructions ๐. This option is enabled by default when either-mcpu=cortex-a57or-mcpu=cortex-a72is specified.-munaligned-access-mno-unaligned-accessโ enables (or disables) reading and writing of 16- and 32-bit values from addresses that are not 16- or 32-bit aligned. By default, unaligned access is disabled for all pre-ARMv6, all ARMv6-M and for ARMv8-M Baseline architectures, and enabled for all other architectures. If unaligned access isn't enabled, then words in packed data structures are accessed a byte at a time ๐.
The ARM attribute Tag_CPU_unaligned_access is set in the generated object file to either true or false, depending on the setting of this option. And if unaligned access is enabled, the preprocessor symbol __ARM_FEATURE_UNALIGNED is also defined โจ.
-mneon-for-64bitsโ this option is deprecated and has no effect. That's it, that's the whole thing ๐.-mslow-flash-dataโ assumes loading data from flash is slower than fetching instructions. Therefore literal loads are minimized for better performance. This option is only supported when compiling for ARMv7 M-profile and it's off by default. It conflicts with-mword-relocationsโ ๏ธ.-masm-syntax-unifiedโ assumes inline assembler is using unified asm syntax. The default is currently off, which implies divided syntax. This option has no impact on Thumb2. However, this may change in future releases of GCC. Divided syntax should be considered deprecated ๐ฌ.-mrestrict-itโ restricts generation of IT blocks to conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This option is on by default for ARMv8-A Thumb mode.-mprint-tune-infoโ prints CPU tuning information as a comment in the assembler file. This is an option used only for regression testing of the compiler and is not intended for ordinary use in compiling code. It's disabled by default ๐ .-mverbose-cost-dumpโ enables verbose cost model dumping in the debug dump files. This option is provided for use in debugging the compiler ๐ง.-mpure-codeโ does not allow constant data to be placed in code sections. Also, when compiling for ELF object format, gives all text sections the ELF processor-specific section attributeSHF_ARM_PURECODE. This option is only available when generating non-pic code for M-profile targets.-mcmseโ generates secure code as per the ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification, which can be found on <https://developer.arm.com/documentation/ecm0359818/latest/>. Secure code, she's fancy ๐.-mfix-cmse-cve-2021-35465โ mitigates against a potential security issue with theVLLDMinstruction in some M-profile devices when using CMSE (CVE-2021-365465). This option is enabled by default when the option-mcpu=is used withcortex-m33,cortex-m35porcortex-m55. The option-mno-fix-cmse-cve-2021-35465can be used to disable the mitigation ๐.-mstack-protector-guard=guard-mstack-protector-guard-offset=offsetโ generates stack protection code using a canary at guard. Supported locations areglobalfor a global canary, ortlsfor a canary accessible via the TLS register. The option-mstack-protector-guard-offset=is for use with-fstack-protector-guard=tlsand not for use in user-land code โ ๏ธ.-mfdpic-mno-fdpicโ selects the FDPIC ABI, which uses 64-bit function descriptors to represent pointers to functions. When the compiler is configured forarm-*-uclinuxfdpiceabitargets, this option is on by default and implies-fPIEif none of the PIC/PIE-related options is provided. On other targets, it only enables the FDPIC-specific code generation features, and you should explicitly provide the PIC/PIE-related options as needed.
Note that static linking is not supported, because it would still involve the dynamic linker when the program self-relocates ๐ญ. If such behavior is acceptable, use -static and -Wl,-dynamic-linker options.
The opposite -mno-fdpic option is useful (and required) to build the Linux kernel using the same (arm-*-uclinuxfdpiceabi) toolchain as the one used to build the userland programs.
๐ฆ AVR Options ๐ฆ
These options are defined for AVR implementations:
-mmcu=mcuโ specify Atmel AVR instruction set architectures (ISA) or MCU type. The default for this option isavr2๐ฏ.
GCC supports the following AVR devices and ISAs:
avr2โ "Classic" devices with up to 8 KiB of program memory. mcu =attiny22,attiny26,at90s2313,at90s2323,at90s2333,at90s2343,at90s4414,at90s4433,at90s4434,at90c8534,at90s8515,at90s8535.avr25โ "Classic" devices with up to 8 KiB of program memory and with theMOVWinstruction. mcu =attiny13,attiny13a,attiny24,attiny24a,attiny25,attiny261,attiny261a,attiny2313,attiny2313a,attiny43u,attiny44,attiny44a,attiny45,attiny48,attiny441,attiny461,attiny461a,attiny4313,attiny84,attiny84a,attiny85,attiny87,attiny88,attiny828,attiny841,attiny861,attiny861a,ata5272,ata6616c,at86rf401.avr3โ "Classic" devices with 16 KiB up to 64 KiB of program memory. mcu =at76c711,at43usb355.avr31โ "Classic" devices with 128 KiB of program memory. mcu =atmega103,at43usb320.
"avr35"โ so these are the "Classic" girlies with 16 KiB up to 64 KiB of program memory and the"MOVW"instruction, iconic behavior ๐ โจ- mcu =
"attiny167","attiny1634","atmega8u2","atmega16u2","atmega32u2","ata5505","ata6617c","ata664251","at90usb82","at90usb162".
- mcu =
"avr4"โ the "Enhanced" babes, up to 8 KiB of program memory ๐ฆ- mcu =
"atmega48","atmega48a","atmega48p","atmega48pa","atmega48pb","atmega8","atmega8a","atmega8hva","atmega88","atmega88a","atmega88p","atmega88pa","atmega88pb","atmega8515","atmega8535","ata5795","ata6285","ata6286","ata6289","ata6612c","at90pwm1","at90pwm2","at90pwm2b","at90pwm3","at90pwm3b","at90pwm81".
- mcu =
"avr5"โ "Enhanced" devices with 16 KiB up to 64 KiB of program memory. okay this list is long bestie, buckle up ๐- mcu =
"atmega16","atmega16a","atmega16hva","atmega16hva2","atmega16hvb","atmega16hvbrevb","atmega16m1","atmega16u4","atmega161","atmega162","atmega163","atmega164a","atmega164p","atmega164pa","atmega165","atmega165a","atmega165p","atmega165pa","atmega168","atmega168a","atmega168p","atmega168pa","atmega168pb","atmega169","atmega169a","atmega169p","atmega169pa","atmega32","atmega32a","atmega32c1","atmega32hvb","atmega32hvbrevb","atmega32m1","atmega32u4","atmega32u6","atmega323","atmega324a","atmega324p","atmega324pa","atmega324pb","atmega325","atmega325a","atmega325p","atmega325pa","atmega328","atmega328p","atmega328pb","atmega329","atmega329a","atmega329p","atmega329pa","atmega3250","atmega3250a","atmega3250p","atmega3250pa","atmega3290","atmega3290a","atmega3290p","atmega3290pa","atmega406","atmega64","atmega64a","atmega64c1","atmega64hve","atmega64hve2","atmega64m1","atmega64rfr2","atmega640","atmega644","atmega644a","atmega644p","atmega644pa","atmega644rfr2","atmega645","atmega645a","atmega645p","atmega649","atmega649a","atmega649p","atmega6450","atmega6450a","atmega6450p","atmega6490","atmega6490a","atmega6490p","ata5790","ata5790n","ata5791","ata6613c","ata6614q","ata5782","ata5831","ata8210","ata8510","ata5787","ata5835","ata5700m322","ata5702m322","at90pwm161","at90pwm216","at90pwm316","at90can32","at90can64","at90scr100","at90usb646","at90usb647","at94k","m3000".
- mcu =
"avr51"โ "Enhanced" devices with 128 KiB of program memory ๐ธ- mcu =
"atmega128","atmega128a","atmega128rfa1","atmega128rfr2","atmega1280","atmega1281","atmega1284","atmega1284p","atmega1284rfr2","at90can128","at90usb1286","at90usb1287".
- mcu =
"avr6"โ "Enhanced" devices with a 3-byte PC, i.e. with more than 128 KiB of program memory ๐- mcu =
"atmega256rfr2","atmega2560","atmega2561","atmega2564rfr2".
- mcu =
"avrxmega2"โ "XMEGA" devices with more than 8 KiB and up to 64 KiB of program memory โจ- mcu =
"atxmega8e5","atxmega16a4","atxmega16a4u","atxmega16c4","atxmega16d4","atxmega16e5","atxmega32a4","atxmega32a4u","atxmega32c3","atxmega32c4","atxmega32d3","atxmega32d4","atxmega32e5","avr64da28","avr64da32","avr64da48","avr64da64","avr64db28","avr64db32","avr64db48","avr64db64","avr64dd14","avr64dd20","avr64dd28","avr64dd32","avr64du28","avr64du32","avr64ea28","avr64ea32","avr64ea48".
- mcu =
"avrxmega3"โ "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space. the way that they just merge the address spaces? obsessed ๐ซถ- mcu =
"attiny202","attiny204","attiny212","attiny214","attiny402","attiny404","attiny406","attiny412","attiny414","attiny416","attiny416auto","attiny417","attiny424","attiny426","attiny427","attiny804","attiny806","attiny807","attiny814","attiny816","attiny817","attiny824","attiny826","attiny827","attiny1604","attiny1606","attiny1607","attiny1614","attiny1616","attiny1617","attiny1624","attiny1626","attiny1627","attiny3214","attiny3216","attiny3217","attiny3224","attiny3226","attiny3227","atmega808","atmega809","atmega1608","atmega1609","atmega3208","atmega3209","atmega4808","atmega4809","avr16dd14","avr16dd20","avr16dd28","avr16dd32","avr16du14","avr16du20","avr16du28","avr16du32","avr16ea28","avr16ea32","avr16ea48","avr16eb14","avr16eb20","avr16eb28","avr16eb32","avr32da28","avr32da32","avr32da48","avr32db28","avr32db32","avr32db48","avr32dd14","avr32dd20","avr32dd28","avr32dd32","avr32du14","avr32du20","avr32du28","avr32du32","avr32ea28","avr32ea32","avr32ea48".
- mcu =
"avrxmega4"โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory ๐- mcu =
"atxmega64a3","atxmega64a3u","atxmega64a4u","atxmega64b1","atxmega64b3","atxmega64c3","atxmega64d3","atxmega64d4","avr128da28","avr128da32","avr128da48","avr128da64","avr128db28","avr128db32","avr128db48","avr128db64".
- mcu =
"avrxmega5"โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM. double the resources, double the slay ๐- mcu =
"atxmega64a1","atxmega64a1u".
- mcu =
"avrxmega6"โ "XMEGA" devices with more than 128 KiB of program memory ๐ฅ- mcu =
"atxmega128a3","atxmega128a3u","atxmega128b1","atxmega128b3","atxmega128c3","atxmega128d3","atxmega128d4","atxmega192a3","atxmega192a3u","atxmega192c3","atxmega192d3","atxmega256a3","atxmega256a3b","atxmega256a3bu","atxmega256a3u","atxmega256c3","atxmega256d3","atxmega384c3","atxmega384d3".
- mcu =
"avrxmega7"โ "XMEGA" devices with more than 128 KiB of program memory and more than 64 KiB of RAM ๐- mcu =
"atxmega128a1","atxmega128a1u","atxmega128a4u".
- mcu =
"avrtiny"โ "TINY" Tiny core devices with 512 B up to 4 KiB of program memory. smol but mighty ๐ง- mcu =
"attiny4","attiny5","attiny9","attiny10","attiny102","attiny104","attiny20","attiny40".
- mcu =
"avr1"โ this ISA is implemented by the minimal AVR core and is supported for assembler only, bestie. no C code here, just vibes ๐- mcu =
"attiny11","attiny12","attiny15","attiny28","at90s1200".
- mcu =
-mabsdataโ assume that all the data chilling in static storage can be reached byLDS/STSinstructions ๐ซ heads up though: this option only does anything on reduced Tiny devices like ATtiny40. see also the"absdata"AVR Variable Attributes, variable attribute.-maccumulate-argsโ this one accumulates outgoing function arguments and grabs/releases the stack space they need once, in the function prologue/epilogue. without it, outgoing arguments get pushed before a function call and popped afterwards ๐ซ
and why do we care? because popping arguments after the call can be expensive on AVR, so accumulating the stack space can lead to smaller executables, since the arguments don't need to be yanked off the stack after such a call.
it can also shrink your code for functions that make several calls to functions that get their arguments on the stack โ like calls to printf-like functions. fr fr ๐
-mbranch-cost=costโ sets the branch costs for conditional branch instructions to cost. reasonable values for cost are small, non-negative integers. the default branch cost is0โจ-mcall-prologuesโ function prologues/epilogues get expanded as calls to the appropriate subroutines. code size is smaller ๐-mdouble=bits-mlong-double=bitsโ set the size (in bits) of the"double"or"long double"type, respectively. possible values for bits are32and64. whether a specific value for bits is even allowed depends on the--with-double=and--with-long-double=configure options (https://gcc.gnu.org/install/configure.html#avr), and the same applies for the default values of the options. iykyk ๐-mgas-isr-prologuesโ interrupt service routines (ISRs) may use the__gcc_isrpseudo instruction supported by GNU Binutils. if this option is on, the feature can still be disabled for individual ISRs by means of the AVR Function Attributes,"no_gccisr"function attribute. this feature is activated per default if optimization is on (but not with-Og, Optimize Options), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683) ๐ธ-mint8โ assume"int"to be an 8-bit integer. this affects the sizes of all the types: a"char"is 1 byte, an"int"is 1 byte, a"long"is 2 bytes, and"long long"is 4 bytes. ngl bestie, please note that this option does not conform to the C standards, but it results in smaller code size ๐-mmain-is-OS_taskโ do not save registers in"main". the effect is the same as attaching the attribute AVR Function Attributes,"OS_task"to"main". it's activated per default if optimization is on โญ-mn-flash=numโ assume that the flash memory has a size of num times 64 KiB ๐ฆ-mno-interruptsโ generated code is not compatible with hardware interrupts. code size is smaller. pick your battles, bestie ๐ญ-mrelaxโ try to replace"CALL"resp."JMP"instruction by the shorter"RCALL"resp."RJMP"instruction if applicable. setting-mrelaxjust adds the--mlink-relaxoption to the assembler's command line and the--relaxoption to the linker's command line โจ
jump relaxing is performed by the linker because jump offsets aren't known before the code is located. therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from the instructions in the assembler code ๐
relaxing must be turned on if linker stubs are needed, see the section on "EIND" and linker stubs below. don't skip this one bestie, it matters ๐
-mrmwโ assume that the device supports the Read-Modify-Write instructions"XCH","LAC","LAS"and"LAT"๐ฅ-mshort-callsโ assume that"RJMP"and"RCALL"can target the whole program memory. quick note: this option is used internally for multilib selection. it is not an optimization option, and you don't need to set it by hand ๐ซถ-msp8โ treat the stack pointer register as an 8-bit register, i.e. assume the high byte of the stack pointer is zero. in general, you don't need to set this option by hand either ๐-mstrict-Xโ bestie, this one makes theXaddress register behave exactly how the hardware intended. That meansXonly gets used in indirect, post-increment or pre-decrement addressing. periodt. ๐
Without this option? The X register is allowed to vibe like Y or Z do, and the compiler just emulates that with extra instructions. For example, loading a value with X+const addressing where const < 64 and non-negative, into some register Rn, gets done like this:
adiw r26, const ; X += const
ld <Rn>, X ; <Rn> = *X
sbiw r26, const ; X -= const
-mtiny-stackโ only touches the lower 8 bits of the stack pointer. tiny stack, tiny changes, we love a minimalist queen. ๐-mfract-convert-truncateโ lets the compiler use truncation instead of rounding toward zero for fractional fixed-point types. ๐ฅ-nodevicelibโ do NOT link against AVR-LibC's device-specific librarylib<mcu>.a. ๐ซ-nodevicespecsโ stops the compiler driver from adding-specs=device-specs/specs-mcuto its own command line. When you do this, you are taking full responsibility for feeding the sub-processes (compiler proper, assembler, linker) the right command-line options. Which means you have to hand over your own private device specs file via-specs=path-to-specs-file. And ngl, once you're here there's no more need for the-mmcu=mcuoption at all. โจ
This option can also step in as a replacement for the older way of specifying custom device-specs files โ the one that needed -B some-path to point at a directory containing a folder named device-specs, which itself contained a specs file named specs-mcu, where mcu was specified by -mmcu=mcu. legacy behavior, we're moving on. ๐
-Waddr-space-convertโ warns you about conversions between address spaces when the resulting address space is not contained in the incoming address space. โ ๏ธ-Wmisspelled-isrโ warns if the ISR is misspelled, like, if it's missing the__vectorprefix. Enabled by default. she's always watching ๐
โจ "EIND" and Devices with More Than 128 Ki Bytes of Flash โจ
Pointers in this implementation are 16 bits wide, bestie. The address of a function or label is stored as a word address, so indirect jumps and calls can reach any code address in the range of 64 Ki words. ๐
So that indirect jumps work on devices with more than 128 Ki bytes of program memory space, there's a special function register called EIND, and it acts as the most significant part of the target address whenever EICALL or EIJMP instructions are used. iconic.
Indirect jumps and calls on these devices get handled like this by the compiler, and they come with some limitations, so listen up ๐ซถ:
- The compiler never sets
EIND. - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions, or it might readEINDdirectly to emulate an indirect call/jump using aRETinstruction. - The compiler assumes
EINDnever changes during the startup code or during the application. Specifically,EINDis not saved/restored in function or interrupt service routine prologue/epilogue. ๐ญ - For indirect calls to functions and computed goto, the linker generates stubs. Stubs are jump pads, sometimes also called trampolines. So the indirect call/jump jumps to such a stub, and the stub contains a direct jump to the desired address. ๐ฆ
- Linker relaxation must be turned on so the linker generates the stubs correctly in every situation. See the compiler option
-mrelaxand the linker option--relax. Heads up: there are corner cases where the linker is supposed to generate stubs but just aborts without relaxation and without a helpful error message. ๐ - The default linker script is arranged for code with
EIND = 0. If your code is supposed to work for a setup withEIND != 0, you have to use a custom linker script to place the sections whose name starts with.trampolinesinto the segment whereEINDpoints to. - The startup code from libgcc never sets
EIND. Notice that startup code is a blend of code from libgcc and AVR-LibC. For the impact of AVR-LibC onEIND, go check the AVR-LibC user manual (http://nongnu.org/avr-libc/user-manual/). - It's totally legitimate for user-specific startup code to set up
EINDearly โ for example with initialization code living in section.init3. Code like that runs before the general startup code that initializes RAM and calls constructors, but after the bit of startup code from AVR-LibC that setsEINDto the segment where the vector table lives. ๐
#include <avr/io.h>
static void
__attribute__((section(".init3"),naked,used,no_instrument_function))
init3_set_eind (void)
{
__asm volatile ("ldi r24,pm_hh8(__trampolines_start)\n\t"
"out %i0,r24" :: "n" (&EIND) : "r24","memory");
}
The __trampolines_start symbol is defined in the linker script.
- Stubs get generated automatically by the linker if these two conditions are both met:
- The address of a label is taken by means of the
gsmodifier (short for generate stubs), like so:
- The address of a label is taken by means of the
LDI r24, lo8(gs(<func>))
LDI r25, hi8(gs(<func>))
- The final location of that label is in a code segment outside the segment where the stubs are located.
- The compiler emits those
gsmodifiers for code labels in these situations:- Taking address of a function or code label.
- Computed goto.
- If prologue-save function is used โ see the
-mcall-prologuescommand-line option. - Switch/case dispatch tables. If you do not want such dispatch tables, you can specify the
-fno-jump-tablescommand-line option. - C and C++ constructors/destructors called during startup/shutdown.
- If the tools hit a
gs()modifier explained above.
- Jumping to non-symbolic addresses like this is not supported, no cap:
int main (void)
{
/* Call function at word address 0x2 */
return ((int(*)(void)) 0x2)();
}
Instead, you have to set up a stub โ meaning the function has to be called through a symbol (func_4 in the example):
int main (void)
{
extern int func_4 (void);
/* Call function at byte address 0x4 */
return func_4();
}
and then the application gets linked with -Wl,--defsym,func_4=0x4. Alternatively, func_4 can be defined in the linker script. โจ
๐ Handling of the "RAMPD", "RAMPX", "RAMPY" and "RAMPZ" Special Function Registers ๐
Some AVR devices support memories bigger than that 64 KiB range you can reach with 16-bit pointers. To access memory locations outside this 64 KiB range, the content of a RAMP register gets used as the high part of the address: the X, Y, Z address register is concatenated with the RAMPX, RAMPY, RAMPZ special function register respectively, giving you a wide address. Similarly, RAMPD is used together with direct addressing. she's got range, literally ๐ธ
- The startup code initializes the
RAMPspecial function registers with zero. - If an AVR Named Address Space โ a named address space other than generic or
__flashโ is used, thenRAMPZgets set as needed before the operation. - If the device supports RAM larger than 64 KiB and the compiler needs to change
RAMPZto accomplish an operation,RAMPZis reset to zero after the operation. ๐ฅ - If the device comes with a specific
RAMPregister, the ISR prologue/epilogue saves/restores that SFR and initializes it with zero in case the ISR code might (implicitly) use it. - RAM larger than 64 KiB is not supported by GCC for AVR targets. If you use inline assembler to read from locations outside the 16-bit address range and change one of the
RAMPregisters, you must reset it to zero after the access. don't forget bestie ๐ญ
๐ AVR Built-in Macros ๐
GCC defines a bunch of built-in macros so your user code can test for the presence or absence of features. Almost all of the built-in macros below get deduced from device capabilities and are therefore triggered by the -mmcu= command-line option.
For even more AVR-specific built-in macros, see AVR Named Address Spaces and AVR Built-in Functions. ๐ฆ
__AVR_ARCH__โ a build-in macro that resolves to a decimal number identifying the architecture, and it depends on the-mmcu=mcuoption. Possible values are:
2, 25, 3, 31, 35, 4, 5, 51, 6
for mcu = avr2, avr25, avr3, avr31, avr35, avr4, avr5, avr51, avr6 respectively, and
100, 102, 103, 104, 105, 106, 107
for mcu = avrtiny, avrxmega2, avrxmega3, avrxmega4, avrxmega5, avrxmega6, avrxmega7 respectively. If mcu specifies a device, this built-in macro is set accordingly. For example, with -mmcu=atmega8 the macro is defined to 4. ๐
__AVR_Device__โ setting-mmcu=devicedefines this built-in macro, which reflects the device's name. For example,-mmcu=atmega8defines the built-in macro__AVR_ATmega8__,-mmcu=attiny261adefines__AVR_ATtiny261A__, etc.
The built-in macros' names follow the scheme __AVR_Device__, where Device is the device name as from the AVR user manual. The difference between Device in the built-in macro and device in -mmcu=device is that the latter is always lowercase.
If device is not a device but only a core architecture like avr51, this macro is not defined. ๐
__AVR_DEVICE_NAME__โ setting-mmcu=devicedefines this built-in macro to the device's name. For example, with-mmcu=atmega8the macro is defined toatmega8.
If device is not a device but only a core architecture like avr51, this macro is not defined.
__AVR_XMEGA__โ the device / architecture belongs to the XMEGA family of devices. โจ__AVR_HAVE_ELPM__โ the device has theELPMinstruction.__AVR_HAVE_ELPMX__โ the device has theELPM Rn,ZandELPM Rn,Z+instructions.__AVR_HAVE_MOVW__โ the device has theMOVWinstruction to perform 16-bit register-register moves. ๐__AVR_HAVE_LPMX__โ bestie, your device has theLPM Rn,ZandLPM Rn,Z+instructions. slay ๐__AVR_HAVE_MUL__โ the device has a hardware multiplier. math girlie behavior โจ__AVR_HAVE_JMP_CALL__โ the device has theJMPandCALLinstructions. This is the case for devices with more than 8 KiB of program memory. no cap.__AVR_HAVE_EIJMP_EICALL__,__AVR_3_BYTE_PC__โ the device has theEIJMPandEICALLinstructions. This is the case for devices with more than 128 KiB of program memory. This also means that the program counter (PC) is 3 bytes wide. big PC energy ๐ซถ__AVR_2_BYTE_PC__โ the program counter (PC) is 2 bytes wide. This is the case for devices with up to 128 KiB of program memory.__AVR_HAVE_8BIT_SP__,__AVR_HAVE_16BIT_SP__โ the stack pointer (SP) register is treated as 8-bit respectively 16-bit register by the compiler. The definition of these macros is affected by-mtiny-stack.__AVR_HAVE_SPH__,__AVR_SP8__โ the device has the SPH (high part of stack pointer) special function register or has an 8-bit stack pointer, respectively. The definition of these macros is affected by-mmcu=and in the cases of-mmcu=avr2and-mmcu=avr25also by-msp8.__AVR_HAVE_RAMPD__,__AVR_HAVE_RAMPX__,__AVR_HAVE_RAMPY__,__AVR_HAVE_RAMPZ__โ the device has theRAMPD,RAMPX,RAMPY,RAMPZspecial function register, respectively.__NO_INTERRUPTS__โ this macro reflects the-mno-interruptscommand-line option.__AVR_ERRATA_SKIP__,__AVR_ERRATA_SKIP_JMP_CALL__โ some AVR devices (AT90S8515, ATmega103) must not skip 32-bit instructions because of a hardware erratum. Skip instructions areSBRS,SBRC,SBIS,SBICandCPSE. The second macro is only defined if__AVR_HAVE_JMP_CALL__is also set. hardware drama, but make it make sense ๐__AVR_ISA_RMW__โ the device has Read-Modify-Write instructions (XCH, LAC, LAS and LAT).__AVR_SFR_OFFSET__=offsetโ instructions that can address I/O special function registers directly likeIN,OUT,SBI, etc. may use a different address as if addressed by an instruction to access RAM likeLDorSTS. This offset depends on the device architecture and has to be subtracted from the RAM address in order to get the respective I/O address.__AVR_SHORT_CALLS__โ the-mshort-callscommand line option is set.__AVR_PM_BASE_ADDRESS__=addrโ some devices support reading from flash memory by means ofLD*instructions. The flash memory is seen in the data address space at an offset of__AVR_PM_BASE_ADDRESS__. If this macro is not defined, this feature is not available. If defined, the address space is linear and there is no need to put.rodatainto RAM. This is handled by the default linker description file, and is currently available foravrtinyandavrxmega3. Even more convenient, there is no need to use address spaces like__flashor features like attributeprogmemandpgm_read_*. flash memory glow up ๐__WITH_AVRLIBC__โ the compiler is configured to be used together with AVR-Libc. See the--with-avrlibcconfigure option.__HAVE_DOUBLE_MULTILIB__โ defined if-mdouble=acts as a multilib option.__HAVE_DOUBLE32__,__HAVE_DOUBLE64__โ defined if the compiler supports 32-bit double resp. 64-bit double. The actual layout is specified by option-mdouble=.__DEFAULT_DOUBLE__โ the size in bits ofdoubleif-mdouble=is not set. To test the layout ofdoublein a program, use the built-in macro__SIZEOF_DOUBLE__.__HAVE_LONG_DOUBLE32__,__HAVE_LONG_DOUBLE64__,__HAVE_LONG_DOUBLE_MULTILIB__,__DEFAULT_LONG_DOUBLE__โ same as above, but forlong doubleinstead ofdouble. long double? she's fancy ๐__WITH_DOUBLE_COMPARISON__โ reflects the--with-double-comparison={tristate|bool|libf7}configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to 2 or 3.__WITH_LIBF7_LIBGCC__,__WITH_LIBF7_MATH__,__WITH_LIBF7_MATH_SYMBOLS__โ reflects the--with-libf7={libgcc|math|math-symbols}configure option (https://gcc.gnu.org/install/configure.html#avr).
โจ Blackfin Options โจ
-mcpu=cpu[-sirevision]โ bestie, this specifies the name of the target Blackfin processor. Currently,cpucan be one ofbf512,bf514,bf516,bf518,bf522,bf523,bf524,bf525,bf526,bf527,bf531,bf532,bf533,bf534,bf536,bf537,bf538,bf539,bf542,bf544,bf547,bf548,bf549,bf542m,bf544m,bf547m,bf548m,bf549m,bf561,bf592. That's a whole roster, periodt ๐- The optional
sirevisionspecifies the silicon revision of the target Blackfin processor. Any workarounds available for the targeted silicon revision are enabled. Ifsirevisionisnone, no workarounds are enabled. Ifsirevisionisany, all workarounds for the targeted processor are enabled. The__SILICON_REVISION__macro is defined to two hexadecimal digits representing the major and minor numbers in the silicon revision. Ifsirevisionisnone, the__SILICON_REVISION__is not defined. Ifsirevisionisany, the__SILICON_REVISION__is defined to be0xffff. If this optionalsirevisionis not used, GCC assumes the latest known silicon revision of the targeted Blackfin processor. - GCC defines a preprocessor macro for the specified
cpu. For thebfin-elftoolchain, this option causes the hardware BSP provided by libgloss to be linked in if-msimis not given. - Without this option,
bf532is used as the processor by default. - Note that support for
bf561is incomplete. Forbf561, only the preprocessor macro is defined.
- The optional
-msimโ says the program will be run on the simulator. This causes the simulator BSP provided by libgloss to be linked in. This option has effect only forbfin-elftoolchain. Certain other options, such as-mid-shared-libraryand-mfdpic, imply-msim.-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. This avoids the instructions to save, set up and restore frame pointers and makes an extra register available in leaf functions. leaf functions stay unbothered ๐ฟ-mspecld-anomalyโ when enabled, the compiler ensures that the generated code does not contain speculative loads after jump instructions. If this option is used,__WORKAROUND_SPECULATIVE_LOADSis defined.-mno-specld-anomalyโ don't generate extra code to prevent speculative loads from occurring.-mcsync-anomalyโ when enabled, the compiler ensures that the generated code does not contain CSYNC or SSYNC instructions too soon after conditional branches. If this option is used,__WORKAROUND_SPECULATIVE_SYNCSis defined.-mno-csync-anomalyโ don't generate extra code to prevent CSYNC or SSYNC instructions from occurring too soon after a conditional branch.-mlow64kโ when enabled, the compiler is free to take advantage of the knowledge that the entire program fits into the low 64k of memory.-mno-low64kโ assume that the program is arbitrarily large. This is the default.-mstack-check-l1โ do stack checking using information placed into L1 scratchpad memory by the uClinux kernel.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. This allows for execute in place and shared libraries in an environment without virtual memory management. This option implies-fPIC. With abfin-elftarget, this option implies-msim.-mno-id-shared-libraryโ generate code that doesn't assume ID-based shared libraries are being used. This is the default.-mleaf-id-shared-libraryโ generate code that supports shared libraries via the library ID method, but assumes that this library or executable won't link against any other ID shared libraries. That allows the compiler to use faster code for jumps and calls.-mno-leaf-id-shared-libraryโ do not assume that the code being compiled won't link against any ID shared libraries. Slower code is generated for jump and call insns.-mshared-library-id=nโ specifies the identification number of the ID-based shared library being compiled. Specifying a value of0generates more compact code; specifying other values forces the allocation of that number to the current library but is no more space- or time-efficient than omitting this option.-msep-dataโ generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute in place in an environment without virtual memory management by eliminating relocations against the text section.-mno-sep-dataโ generate code that assumes that the data segment follows the text segment. This is the default.-mlong-calls,-mno-long-callsโ tells the compiler to perform function calls by first loading the address of the function into a register and then performing a subroutine call on this register. This switch is needed if the target function lies outside of the 24-bit addressing range of the offset-based version of subroutine call instruction.- This feature is not enabled by default. Specifying
-mno-long-callsrestores the default behavior. Note these switches have no effect on how the compiler generates code to handle function calls via function pointers.
- This feature is not enabled by default. Specifying
-mfast-fpโ link with the fast floating-point library. This library relaxes some of the IEEE floating-point standard's rules for checking inputs against Not-a-Number (NAN), in the interest of performance.-minline-pltโ enable inlining of PLT entries in function calls to functions that are not known to bind locally. It has no effect without-mfdpic.-mmulticoreโ build a standalone application for multicore Blackfin processors. This option causes proper start files and link scripts supporting multicore to be used, and defines the macro__BFIN_MULTICORE. It can only be used with-mcpu=bf561[-sirevision].- This option can be used with
-mcoreaor-mcoreb, which selects the one-application-per-core programming model. Without-mcoreaor-mcoreb, the single-application/dual-core programming model is used. In this model, the main function of Core B should be named ascoreb_main. - If this option is not used, the single-core application programming model is used.
- This option can be used with
-mcoreaโ okay so this one builds a standalone app for Core A of BF561 when you're doing the whole one-application-per-core thing ๐ . It pulls in the proper start files and link scripts for Core A, and it defines the macro"__BFIN_COREA". Big caveat bestie: this option can only be used together with-mmulticore. No solo runs, it's giving duo energy only.-mcorebโ same vibe, but for Core B of BF561 in the one-application-per-core programming model โจ. Proper start files and link scripts for Core B get used, and the macro"__BFIN_COREB"is defined. When you use this, use"coreb_main"instead of"main"(yes, really, main character rules apply differently here). And again: this option can only be used in conjunction with-mmulticore.-msdramโ builds a standalone application for SDRAM ๐ซถ. Proper start files and link scripts get used to put the app into SDRAM, and the macro"__BFIN_SDRAM"is defined. Heads up though: the loader should initialize SDRAM before loading the application, so don't come for me if you skip that.-micplbโ assumes that ICPLBs are enabled at run time. This lowkey matters because it affects certain anomaly workarounds. For Linux targets, the default is to assume ICPLBs are enabled; for standalone applications the default is off ๐.
โจ C6X Options โจ
-march=nameโ this specifies the name of the target architecture ๐. GCC uses this name to figure out what kind of instructions it can emit when it's generating assembly code. The permissible names are:c62x,c64x,c64x+,c67x,c67x+,c674x.-mbig-endianโ generate code for a big-endian target ๐ฅ.-mlittle-endianโ generate code for a little-endian target. This is the default ๐ธ.-msimโ choose startup files and linker script suitable for the simulator ๐ง.-msdata=defaultโ put small global and static data in the.neardatasection, which is pointed to by registerB14โญ. Put small uninitialized global and static data in the.bsssection, which is adjacent to the.neardatasection. Put small read-only data into the.rodatasection. And the corresponding sections used for large pieces of data? Those are.fardata,.farand.const.-msdata=allโ put all data, not just small objects, into the sections reserved for small data, and use addressing relative to theB14register to access them ๐ .-msdata=noneโ make no use of the sections reserved for small data, and use absolute addresses to access all data. Put all initialized global and static data in the.fardatasection, and all uninitialized data in the.farsection. Put all constant data into the.constsection. Clean, absolute, no notes โจ.
๐ CRIS Options ๐
These options are defined specifically for the CRIS ports, iykyk.
-march=architecture-type-mcpu=architecture-type
Generate code for the specified architecture ๐. The choices for architecture-type are v3, v8 and v10 for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. Default is v0.
-mtune=architecture-typeโ tune to architecture-type everything applicable about the generated code, except for the ABI and the set of available instructions ๐. The choices for architecture-type are the same as for-march=architecture-type.-mmax-stack-frame=nโ warn when the stack frame of a function exceeds n bytes ๐.-metrax4-metrax100
The options -metrax4 and -metrax100 are synonyms for -march=v3 and -march=v8 respectively ๐ฆ.
-mmul-bug-workaround-mno-mul-bug-workaround
Work around a bug in the "muls" and "mulu" instructions for CPU models where it applies ๐. This option is disabled by default.
-mpdebugโ enable CRIS-specific verbose debug-related information in the assembly code ๐. This option also has the effect of turning off the#NO_APPformatted-code indicator to the assembler at the beginning of the assembly file.-mcc-initโ do not use condition-code results from previous instruction; always emit compare and test instructions before use of condition codes โจ.-mno-side-effectsโ do not emit instructions with side effects in addressing modes other than post-increment ๐.-mstack-align-mno-stack-align-mdata-align-mno-data-align-mconst-align-mno-const-align
These options (the no- ones) arrange (eliminate arrangements) for the stack frame, individual data and constants to be aligned for the maximum single data access size for the chosen CPU model ๐
. The default is to arrange for 32-bit alignment. ABI details such as structure layout are not affected by these options, so breathe.
-m32-bit-m16-bit-m8-bit
Similar to the stack- data- and const-align options above, these options arrange for stack frame, writable data and constants to all be 32-bit, 16-bit or 8-bit aligned โญ. The default is 32-bit alignment.
-mno-prologue-epilogue-mprologue-epilogue
With -mno-prologue-epilogue, the normal function prologue and epilogue which set up the stack frame are omitted and no return instructions or return sequences are generated in the code ๐ญ.
Use this option only together with visual inspection of the compiled code: no warnings or errors are generated when call-saved registers must be saved, or storage for local variables needs to be allocated. Like, it will simply not tell you. Eyes on the code, bestie.
-melfโ legacy no-op option ๐ซ . It's giving nothing, it does nothing.-simโ this option arranges to link with input-output functions from a simulator library ๐ธ. Code, initialized data and zero-initialized data are allocated consecutively.-sim2โ like-sim, but pass linker options to locate initialized data at0x40000000and zero-initialized data at0x80000000๐ฅ.
๐ CR16 Options ๐
These options are defined specifically for the CR16 ports, periodt.
-mmacโ enable the use of multiply-accumulate instructions ๐. Disabled by default.-mcr16cplus-mcr16c
Generate code for CR16C or CR16C+ architecture. CR16C+ architecture is the default ๐.
-msimโ links the librarylibsim.awhich is in compatible with simulator ๐ง. Applicable to ELF compiler only.-mint32โ choose integer type as 32-bit wide โจ.-mbit-opsโ generates"sbit"/"cbit"instructions for bit manipulations ๐ .-mdata-model=modelโ choose a data model ๐ธ. The choices for model arenear,farormedium.mediumis default. However,faris not valid with-mcr16c, because the CR16C architecture does not support the far data model. So don't try it, it's not gonna slay.
๐ฆ C-SKY Options ๐ฆ
GCC supports these options when compiling for C-SKY V2 processors ๐.
-march=archโ specify the C-SKY target architecture โญ. Valid values for arch are:ck801,ck802,ck803,ck807, andck810. The default isck810.-mcpu=cpuโ specify the C-SKY target processor ๐. Valid values for cpu are:ck801,ck801t,ck802,ck802t,ck802j,ck803,ck803h,ck803t,ck803ht,ck803f,ck803fh,ck803e,ck803eh,ck803et,ck803eht,ck803ef,ck803efh,ck803ft,ck803eft,ck803efht,ck803r1,ck803hr1,ck803tr1,ck803htr1,ck803fr1,ck803fhr1,ck803er1,ck803ehr1,ck803etr1,ck803ehtr1,ck803efr1,ck803efhr1,ck803ftr1,ck803eftr1,ck803efhtr1,ck803s,ck803st,ck803se,ck803sf,ck803sef,ck803seft,ck807e,ck807ef,ck807,ck807f,ck810e,ck810et,ck810ef,ck810eft,ck810,ck810v,ck810f,ck810t,ck810fv,ck810tv,ck810ft, andck810ftv. Yes, that's a lot. It's iconic, we don't question it.-mbig-endian-EB-mlittle-endian-EL
Select big- or little-endian code ๐. The default is little-endian.
-mfloat-abi=nameโ specifies which floating-point ABI to use ๐. Permissible values are:soft,softfpandhard.
Specifying soft causes GCC to generate output containing library calls for floating-point operations. softfp allows the generation of code using hardware floating-point instructions, but still uses the soft-float calling conventions. hard allows generation of floating-point instructions and uses FPU-specific calling conventions.
The default depends on the specific target configuration. Note that the hard-float and soft-float ABIs are not link-compatible; you must compile your entire program with the same ABI, and link with a compatible set of libraries. Mixing them is a crime, fr fr ๐จ.
-mhard-float-msoft-float
Select hardware or software floating-point implementations ๐. The default is soft float.
-mdouble-float-mno-double-float
When -mhard-float is in effect, enable generation of double-precision float instructions โจ. This is the default except when compiling for CK803.
-mfdivdu-mno-fdivdu
When -mhard-float is in effect, enable generation of "frecipd", "fsqrtd", and "fdivd" instructions ๐ฅ. This is the default except when compiling for CK803.
-mfpu=fpuโ select the floating-point processor ๐ . This option can only be used with-mhard-float. Values for fpu arefpv2_sf(equivalent to-mno-double-float -mno-fdivdu),fpv2(-mdouble-float -mno-divdu), andfpv2_divd(-mdouble-float -mdivdu).-melrw-mno-elrw
Enable the extended "lrw" instruction ๐ฆ. This option defaults to on for CK801 and off otherwise.
-mistack-mno-istack
Enable interrupt stack instructions; the default is off ๐.
The -mistack option is required to handle the "interrupt" and "isr" function attributes.
-mmpโ enable multiprocessor instructions; the default is off.-mcpโ enable coprocessor instructions; the default is off.-mcacheโ enable coprocessor instructions; the default is off.-msecurityโ enable C-SKY security instructions; the default is off ๐.-mtrustโ enable C-SKY trust instructions; the default is off ๐ซถ.-mdsp-medsp-mvdsp
Enable C-SKY DSP, Enhanced DSP, or Vector DSP instructions, respectively โญ. All of these options default to off.
-mdiv-mno-div
Generate divide instructions. Default is off ๐.
-msmart-mno-smart
Generate code for Smart Mode, using only registers numbered 0-7 to allow use of 16-bit instructions โจ. This option is ignored for CK801 where this is the required behavior, and it defaults to on for CK802. For other targets, the default is off.
-mhigh-registers-mno-high-registers
Generate code using the high registers numbered 16-31 ๐. This option is not supported on CK801, CK802, or CK803, and is enabled by default for other processors.
-manchor-mno-anchor
Generate code using global anchor symbol addresses ๐ธ.
-mpushpop-mno-pushpop
Generate code using "push" and "pop" instructions ๐. This option defaults to on.
-mmultiple-stld,-mstm,-mno-multiple-stld,-mno-stmโ makes code that uses thestmandldminstructions โจ. Fair warning bestie: this one is not supported on CK801, but it's enabled by default on all the other processors.-mconstpool,-mno-constpoolโ builds the constant pools inside the compiler instead of handing that job off to the assembler. This is the default, and it's required for correct code generation on CK801 and CK802, and it's optional on the other processors.-mstack-size,-mno-stack-sizeโ emits.stack_sizedirectives for every function in the assembly output. Defaults to off.-mccrt,-mno-ccrtโ generates code for the C-SKY compiler runtime instead of libgcc. Defaults to off.-mbranch-cost=nโ sets the branch costs to roughlyninstructions. The default is1.-msched-prolog,-mno-sched-prologโ lets the compiler schedule function prologue and epilogue sequences ๐. But bestie, using this can give you code that is not compliant with the C-SKY V2 ABI prologue requirements โ code that cannot be debugged or backtraced. It's disabled by default, and now you know why.-msimโ links the librarylibsemi.awhich is in compatible with simulator. Applicable to ELF compiler only.
Darwin Options ๐๐
These options are defined for all architectures running the Darwin operating system.
FSF GCC on Darwin does not create "fat" object files; it creates an object file for the single architecture that GCC was built to target. Apple's GCC on Darwin does create "fat" files if multiple -arch options are used โ it does that by running the compiler or linker multiple times and joining the results together with lipo. Iconic behavior, honestly.
The subtype of the file created (like ppc7400 or ppc970 or i686) is decided by the flags that specify the ISA GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can override all of that.
The Darwin tools are... not consistent when you hand them an ISA mismatch ๐ญ:
- The assembler,
as, only permits instructions that are valid for the subtype of the file it's generating, so you cannot put 64-bit instructions in appc750object file. - The linker for shared libraries,
/usr/bin/libtool, fails and prints an error if you ask it to create a shared library with a less restrictive subtype than its input files (for instance, trying to put appc970object file in appc7400library). - The linker for executables,
ld, quietly gives the executable the most restrictive subtype of any of its input files. Sneaky. -Fdirโ adds the framework directory dir to the head of the list of directories searched for header files. These directories get interleaved with the ones from-Ioptions and are scanned in a left-to-right order.
A framework directory is a directory with frameworks in it. A framework is a directory with a Headers and/or PrivateHeaders directory contained directly in it that ends in .framework. The name of a framework is the name of this directory excluding the .framework. Headers associated with the framework are found in one of those two directories, with Headers being searched first. A subframework is a framework directory that's in a framework's Frameworks directory. Includes of subframework headers can only appear in a header of a framework that contains the subframework, or in a sibling subframework header. Two subframeworks are siblings if they occur in the same framework. A subframework should not have the same name as a framework; a warning is issued if this is violated. Currently a subframework cannot have subframeworks; in the future, the mechanism may be extended to support this. The standard frameworks live in /System/Library/Frameworks and /Library/Frameworks. An example include looks like #include <Framework/header.h>, where Framework denotes the name of the framework and header.h is found in the PrivateHeaders or Headers directory.
-iframeworkdirโ like-Fexcept the directory is treated as a system directory ๐ซถ. The main difference between-iframeworkand-Fis that with-iframeworkthe compiler does not warn about constructs contained within header files found via dir. This option is valid only for the C family of languages.-gusedโ emits debugging information for symbols that are used. For the stabs debugging format, this enables-feliminate-unused-debug-symbols. This is by default ON.-gfullโ emits debugging information for all symbols and types. All of them. No crumbs.-fconstant-cfstringsโ the-fconstant-cfstringsis an alias for-mconstant-cfstrings.-mconstant-cfstringsโ when the NeXT runtime is being used (the default on these systems), overrides any-fconstant-string-classsetting and causes"@"...""literals to be laid out as constant CoreFoundation strings.-mmacosx-version-min=versionโ the earliest version of MacOS X that this executable will run on is version. Typical values supported for version include12,10.12, and10.5.8.
If the compiler was built to use the system's headers by default, then the default for this option is the system version on which the compiler is running, otherwise the default is to make choices that are compatible with as many systems and code bases as possible.
-mkernelโ enables kernel development mode ๐. The-mkerneloption sets-static,-fno-common,-fno-use-cxa-atexit,-fno-exceptions,-fno-non-call-exceptions,-fapple-kext,-fno-weakand-fno-rttiwhere applicable. This mode also sets-mno-altivec,-msoft-float,-fno-builtinand-mlong-branchfor PowerPC targets.-mone-byte-boolโ overrides the defaults forboolso thatsizeof(bool)==1. By defaultsizeof(bool)is4when compiling for Darwin/PowerPC and1when compiling for Darwin/x86, so this option has no effect on x86.
Warning: The -mone-byte-bool switch causes GCC to generate code that is not binary compatible with code generated without that switch. Using this switch may require recompiling all other modules in a program, including system libraries. Use this switch to conform to a non-default data model. So like... know what you're doing ๐
-mfix-and-continue,-ffix-and-continue,-findirect-dataโ generates code suitable for fast turnaround development, like letting GDB dynamically load.ofiles into already-running programs.-findirect-dataand-ffix-and-continueare provided for backwards compatibility.-all_loadโ loads all members of static archive libraries. Seeman ld(1)for more information.-arch_errors_fatalโ causes the errors having to do with files that have the wrong architecture to be fatal.-bind_at_loadโ causes the output file to be marked such that the dynamic linker will bind all undefined references when the file is loaded or launched.-bundleโ produces a Mach-o bundle format file. Seeman ld(1)for more information.-bundle_loader executableโ specifies the executable that will load the build output file being linked. Seeman ld(1)for more information.-dynamiclibโ when passed this option, GCC produces a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand.-force_cpusubtype_ALLโ this causes GCC's output file to have theALLsubtype, instead of one controlled by the-mcpuor-marchoption.-allowable_client client_name,-client_name,-compatibility_version,-current_version,-dead_strip,-dependency-file,-dylib_file,-dylinker_install_name,-dynamic,-exported_symbols_list,-filelist,-flat_namespace,-force_flat_namespace,-headerpad_max_install_names,-image_base,-init,-install_name,-keep_private_externs,-multi_module,-multiply_defined,-multiply_defined_unused,-noall_load,-no_dead_strip_inits_and_terms,-nofixprebinding,-nomultidefs,-noprebind,-noseglinkedit,-pagezero_size,-prebind,-prebind_all_twolevel_modules,-private_bundle,-read_only_relocs,-sectalign,-sectobjectsymbols,-whyload,-seg1addr,-sectcreate,-sectobjectsymbols,-sectorder,-segaddr,-segs_read_only_addr,-segs_read_write_addr,-seg_addr_table,-seg_addr_table_filename,-seglinkedit,-segprot,-segs_read_only_addr,-segs_read_write_addr,-single_module,-static,-sub_library,-sub_umbrella,-twolevel_namespace,-umbrella,-undefined,-unexported_symbols_list,-weak_reference_mismatches,-whatsloadedโ these options are passed to the Darwin linker. The Darwin linker man page describes them in detail. That's it, that's the whole vibe โ just hand them over and letldcook ๐ณ
DEC Alpha Options ๐๐ฆ
These -m options are defined for the DEC Alpha implementations:
-mno-soft-float,-msoft-floatโ use (do not use) the hardware floating-point instructions for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. Unless they're replaced by routines that emulate the floating-point operations, or compiled in such a way as to call such emulation routines, these routines issue floating-point operations. If you're compiling for an Alpha without floating-point operations, you must make sure the library is built so as not to call them.
Note that Alpha implementations without floating-point operations are required to have floating-point registers. Yeah, I know, read it twice, it really does say that ๐
-mfp-reg,-mno-fp-regsโ generate code that uses (does not use) the floating-point register set.-mno-fp-regsimplies-msoft-float. If the floating-point register set is not used, floating-point operands are passed in integer registers as if they were integers, and floating-point results are passed in$0instead of$f0. This is a non-standard calling sequence, so any function with a floating-point argument or return value called by code compiled with-mno-fp-regsmust also be compiled with that option. No half-measures, bestie.
A typical use of this option is building a kernel that does not use โ and therefore doesn't need to save and restore โ any floating-point registers. Very demure, very mindful kernel โจ
-mieeeโ okay so the Alpha architecture has floating-point hardware that's built for max performance, right? And it's mostly compliant with the IEEE floating-point standard. But for full compliance, you need software help. This option generates code that's fully IEEE-compliant โ with one lil exception: the inexact-flag isn't maintained (more on that below ๐). When this is turned on, the preprocessor macro_IEEE_FPgets defined during compilation. The resulting code is less efficient but it can correctly support denormalized numbers and exceptional IEEE values like not-a-number and plus/minus infinity. Other Alpha compilers call this option-ieee_with_no_inexact.
DEBIAN SPECIFIC: This option is on by default foralpha-linux-gnu, unless-ffinite-math-only(which is part of the-ffast-mathset) is specified โ and the reason is wild: the software functions in the GNU libc math libraries generate denormalized numbers, NaNs, and infs, and all of those will cause a program toSIGFPEwhen it tries to use the results without-mieee. ๐
-mieee-with-inexactโ this is like-mieeeexcept the generated code also maintains the IEEE inexact-flag. Turning this on makes the generated code implement fully-compliant IEEE math. Besides_IEEE_FP, it also defines_IEEE_FP_EXACTas a preprocessor macro. Now, on some Alpha implementations the resulting code may execute significantly slower than the code generated by default. And since there's very little code that actually depends on the inexact-flag, you should normally not specify this option. Other Alpha compilers call this option-ieee_with_inexact.-mfp-trap-mode=trap-modeโ this one controls which floating-point related traps are enabled. Other Alpha compilers call this option-fptm trap-mode. The trap mode can be set to one of four values:nโ the default (normal) setting. The only traps enabled are the ones that cannot be disabled in software (e.g., division by zero trap).uโ in addition to the traps enabled byn, underflow traps are enabled as well.suโ likeu, but the instructions are marked to be safe for software completion (see the Alpha architecture manual for the deets ๐).suiโ likesu, but inexact traps are enabled as well.
-mfp-rounding-mode=rounding-modeโ selects the IEEE rounding mode. Other Alpha compilers call this option-fprm rounding-mode. The rounding-mode can be one of:nโ Normal IEEE rounding mode. Floating-point numbers are rounded towards the nearest machine number, or towards the even machine number in case of a tie.mโ Round towards minus infinity.cโ Chopped rounding mode. Floating-point numbers are rounded towards zero.dโ Dynamic rounding mode. A field in the floating-point control register (fpcr, see the Alpha architecture reference manual) controls the rounding mode in effect. The C library initializes this register for rounding towards plus infinity. So unless your program modifies thefpcr,dcorresponds to round towards plus infinity.
-mtrap-precision=trap-precisionโ in the Alpha architecture, floating-point traps are imprecise, bestie ๐ญ. That means that without software assistance it's impossible to recover from a floating trap, and program execution normally needs to be terminated. GCC can generate code that helps operating system trap handlers figure out the exact location that caused a floating-point trap. Depending on what your app needs, you can pick different levels of precision:pโ Program precision. This is the default, and it means a trap handler can only identify which program caused a floating-point exception.fโ Function precision. The trap handler can determine the function that caused a floating-point exception.iโ Instruction precision. The trap handler can determine the exact instruction that caused a floating-point exception.
Other Alpha compilers provide the equivalent options called -scope_safe and -resumption_safe.
-mieee-conformantโ this option marks the generated code as IEEE conformant. โ ๏ธ You must not use this option unless you also specify-mtrap-precision=iand either-mfp-trap-mode=suor-mfp-trap-mode=sui. Its only effect is to emit the line.eflag 48in the function prologue of the generated assembly file.-mbuild-constantsโ normally GCC examines a 32- or 64-bit integer constant to see if it can construct it from smaller constants in two or three instructions. If it can't, it outputs the constant as a literal and generates code to load it from the data segment at run time. Use this option to require GCC to construct all integer constants using code, even if it takes more instructions (the maximum is six). You typically use this for building a shared library dynamic loader โ it's itself a shared library, so it has to relocate itself in memory before it can find the variables and constants in its own data segment. Sneaky lil guy ๐ซถ-mbwx,-mno-bwx,-mcix,-mno-cix,-mfix,-mno-fix,-mmax,-mno-maxโ these indicate whether GCC should generate code to use the optional BWX, CIX, FIX and MAX instruction sets. The default is to use the instruction sets supported by the CPU type specified via the-mcpu=option, or that of the CPU on which GCC was built if none is specified.-mfloat-vax,-mfloat-ieeeโ generate code that uses (or does not use) VAX F and G floating-point arithmetic instead of IEEE single and double precision.-mexplicit-relocs,-mno-explicit-relocsโ so older Alpha assemblers had no way to generate symbol relocations except via assembler macros. And using those macros? Doesn't allow optimal instruction scheduling, periodt. GNU binutils as of version2.12supports a new syntax that lets the compiler explicitly mark which relocations should apply to which instructions. This option is mostly useful for debugging, since GCC detects the capabilities of the assembler when it is built and sets the default accordingly.-msmall-data,-mlarge-dataโ when-mexplicit-relocsis in effect, static data is accessed via gp-relative relocations. When-msmall-datais used, objects 8 bytes long or smaller get placed in a small data area (the.sdataand.sbsssections) and are accessed via 16-bit relocations off of the$gpregister. This limits the size of the small data area to64KB, but it lets the variables be directly accessed via a single instruction. โจ
The default is -mlarge-data. With this option the data area is limited to just below 2GB. Programs that require more than 2GB of data must use malloc or mmap to allocate the data in the heap instead of in the program's data segment.
When generating code for shared libraries, -fpic implies -msmall-data and -fPIC implies -mlarge-data.
-msmall-text,-mlarge-textโ when-msmall-textis used, the compiler assumes that the code of the entire program (or shared library) fits in4MB, and is thus reachable with a branch instruction. When-msmall-datais used, the compiler can assume that all local symbols share the same$gpvalue, and thus reduce the number of instructions required for a function call from4to1. The default is-mlarge-text.-mcpu=cpu_typeโ sets the instruction set and instruction scheduling parameters for machine type cpu_type. You can specify either the EV style name or the corresponding chip number. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors and chooses the default values for the instruction set from the processor you specify. If you don't specify a processor type, GCC defaults to the processor on which the compiler was built.
Supported values for cpu_type are:
ev4ev4521064โ Schedules as an EV4 and has no instruction set extensions.ev521164โ Schedules as an EV5 and has no instruction set extensions.ev5621164aโ Schedules as an EV5 and supports the BWX extension.pca5621164pc21164PCโ Schedules as an EV5 and supports the BWX and MAX extensions.ev621264โ Schedules as an EV6 and supports the BWX, FIX, and MAX extensions.ev6721264aโ Schedules as an EV6 and supports the BWX, CIX, FIX, and MAX extensions.
Native toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor.
-mtune=cpu_typeโ sets only the instruction scheduling parameters for machine type cpu_type. The instruction set is not changed, bestie. Native toolchains also support the valuenative, which selects the best architecture option for the host processor.-mtune=nativehas no effect if GCC does not recognize the processor.-mmemory-latency=timeโ sets the latency the scheduler should assume for typical memory references as seen by the application. This number is highly dependent on the memory access patterns used by the application and the size of the external cache on the machine. Valid options for time are:numberโ a decimal number representing clock cycles.L1L2L3mainโ the compiler contains estimates of the number of clock cycles for "typical" EV4 & EV5 hardware for the Level 1, 2 & 3 caches (also called Dcache, Scache, and Bcache), as well as to main memory. Note thatL3is only valid for EV5.
๐ eBPF Options ๐
-mframe-limit=bytesโ this specifies the hard limit for frame sizes, in bytes. Currently, the value that can be specified should be less than or equal to32767. It defaults to whatever limit is imposed by the version of the Linux kernel targeted.-mkernel=versionโ this specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to determine which instructions to use, what kernel helpers to allow, etc. Currently, version can be one of4.0,4.1,4.2,4.3,4.4,4.5,4.6,4.7,4.8,4.9,4.10,4.11,4.12,4.13,4.14,4.15,4.16,4.17,4.18,4.19,4.20,5.0,5.1,5.2,latestandnative. ๐-mbig-endianโ bestie, this one makes the compiler generate code for a big-endian target ๐-mlittle-endianโ and this one generates code for a little-endian target. This is literally the default, no cap โจ-mjmpextโ turns on generation of the extra conditional-branch instructions. It's already enabled for CPU v2 and above, so slay ๐-mjmp32โ enables 32-bit jump instructions. On by default for CPU v3 and above ๐-malu32โ enables 32-bit ALU instructions. Also on by default for CPU v3 and above ๐- *
-mcpu=version* โ this picks which version of the eBPF ISA you're targeting, fr fr. Newer versions might not be supported by every kernel out there ๐ญ and the default isv3.
Here's the tea on the supported values for version:
v1โ the first stable eBPF ISA, with no special features or extensions. The og, the blueprint ๐ฆv2โ supports the jump extensions, just like-mjmpext.v3โ everything inv2, plus:- 32-bit jump operations, like in
-mjmp32 - 32-bit ALU operations, like in
-malu32
- 32-bit jump operations, like in
-mco-reโ enables BPF Compile Once - Run Everywhere (CO-RE) support. It requires-gbtfand is also implied by it, iykyk ๐ธ-mno-co-reโ disables BPF Compile Once - Run Everywhere (CO-RE) support. And listen: BPF CO-RE support is enabled by default whenever you're generating BTF debug information for the BPF target ๐-mxbpfโ generates code for an expanded version of BPF that relaxes some of the restrictions the BPF architecture usually imposes ๐ Specifically:- it saves and restores callee-saved registers at function entry and exit, respectively.
๐ FR30 Options ๐
These options are defined specifically for the FR30 port, bestie ๐
-msmall-modelโ uses the small address space model. It can produce smaller code, but it does assume that all symbolic values and addresses fit into a 20-bit range โญ-mno-lsimโ assumes runtime support has already been provided, so there's no need to include the simulator library (libsim.a) on the linker command line ๐
๐ฆ FT32 Options ๐ฆ
These options are defined specifically for the FT32 port, periodt โจ
-msimโ says the program is gonna run on the simulator. This makes an alternate runtime startup and library get linked in. You must not use this option when you're generating programs that will run on real hardware โ you've gotta provide your own runtime library for whatever I/O functions you need ๐ซถ-mlraโ enables Local Register Allocation. Ngl this is still experimental for FT32, so by default the compiler uses standard reload ๐-mnodivโ don't usedivandmodinstructions.-mft32bโ enables use of the extended instructions of the FT32B processor ๐ฅ-mcompressโ compresses all code using the Ft32B code compression scheme.-mnopmโ don't generate code that reads program memory.
๐ FRV Options ๐
-mgpr-32โ only use the first 32 general-purpose registers.-mgpr-64โ use all 64 general-purpose registers ๐-mfpr-32โ use only the first 32 floating-point registers.-mfpr-64โ use all 64 floating-point registers โจ-mhard-floatโ use hardware instructions for floating-point operations.-msoft-floatโ use library routines for floating-point operations.-malloc-ccโ dynamically allocate condition code registers.-mfixed-ccโ don't try to dynamically allocate condition code registers, only use"icc0"and"fcc0".-mdwordโ change ABI to use double word insns.-mno-dwordโ do not use double word instructions.-mdoubleโ use floating-point double instructions.-mno-doubleโ do not use floating-point double instructions.-mmediaโ use media instructions.-mno-mediaโ do not use media instructions.-mmuladdโ use multiply and add/subtract instructions.-mno-muladdโ do not use multiply and add/subtract instructions.-mfdpicโ selects the FDPIC ABI, which uses function descriptors to represent pointers to functions. Without any PIC/PIE-related options, it implies-fPIE. With-fpicor-fpie, it assumes GOT entries and small data are within a 12-bit range from the GOT base address; with-fPICor-fPIE, GOT offsets are computed with 32 bits. And with a bfin-elf target, this option implies-msim๐-minline-pltโ enables inlining of PLT entries in function calls to functions that aren't known to bind locally. It has no effect without-mfdpic, fr fr. It's enabled by default if you're optimizing for speed and compiling for shared libraries (i.e.-fPICor-fpic), or when an optimization option like-O3or above is present in the command line ๐ฅ-mTLSโ assume a large TLS segment when generating thread-local code.-mtlsโ do not assume a large TLS segment when generating thread-local code.-mgprel-roโ enables the use of"GPREL"relocations in the FDPIC ABI for data that's known to be in read-only sections. It's enabled by default, except for-fpicor-fpie: even though it may help make the global offset table smaller, it trades 1 instruction for 4 ๐ญ With-fPICor-fPIE, it trades 3 instructions for 4, one of which may be shared by multiple symbols, and it avoids the need for a GOT entry for the referenced symbol, so it's more likely to be a win. If it isn't,-mno-gprel-rocan be used to disable it ๐-multilib-library-picโ link with the (library, not FD) pic libraries. It's implied by-mlibrary-pic, as well as by-fPICand-fpicwithout-mfdpic. You should never have to use it explicitly ๐-mlinked-fpโ follows the EABI requirement of always creating a frame pointer whenever a stack frame is allocated. This option is enabled by default and can be disabled with-mno-linked-fpโจ-mlong-callsโ use indirect addressing to call functions outside the current compilation unit. This lets the functions be placed anywhere within the 32-bit address space ๐-malign-labelsโ try to align labels to an 8-byte boundary by inserting NOPs into the previous packet. This option only does anything when VLIW packing is enabled. It doesn't create new packets; it merely adds NOPs to existing ones ๐-mlibrary-picโ generate position-independent EABI code.-macc-4โ use only the first four media accumulator registers.-macc-8โ use all eight media accumulator registers ๐-mpackโ pack VLIW instructions.-mno-packโ do not pack VLIW instructions.-mno-eflagsโ do not mark ABI switches ine_flags.-mcond-moveโ enable the use of conditional-move instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-cond-moveโ disable the use of conditional-move instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-msccโ enable the use of conditional set instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-sccโ disable the use of conditional set instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mcond-execโ enable the use of conditional execution (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-cond-execโ disable the use of conditional execution.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mvliw-branchโ run a pass to pack branches into VLIW instructions (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-vliw-branchโ do not run a pass to pack branches into VLIW instructions.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mmulti-cond-execโ enable optimization of"&&"and"||"in conditional execution (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-multi-cond-execโ disable optimization of"&&"and"||"in conditional execution.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mnested-cond-execโ enable nested conditional execution optimizations (default).
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-mno-nested-cond-execโ disable nested conditional execution optimizations.
This switch is mainly for debugging the compiler and will likely be removed in a future version ๐
-moptimize-membarโ this switch removes redundant"membar"instructions from the compiler-generated code. It's enabled by default โจ-mno-optimize-membarโ this switch disables the automatic removal of redundant"membar"instructions from the generated code.-mtomcat-statsโ causes gas to print out tomcat statistics ๐ฑ- *
-mcpu=cpu* โ select the processor type to generate code for. Possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple๐
๐ง GNU/Linux Options ๐ง
These -m options are defined for GNU/Linux targets, bestie:
-mglibcโ use the GNU C library. This is the default except on*-*-linux-*uclibc*,*-*-linux-*musl*and*-*-linux-*android*targets ๐-muclibcโ use uClibc C library. This is the default on*-*-linux-*uclibc*targets.-mmuslโ use the musl C library. This is the default on*-*-linux-*musl*targets.-mbionicโ use Bionic C library. This is the default on*-*-linux-*android*targets ๐ค-mandroidโ compile code compatible with the Android platform. This is the default on*-*-linux-*android*targets.
When compiling, this option enables -mbionic, -fPIC, -fno-exceptions and -fno-rtti by default. When linking, this option makes the GCC driver pass Android-specific options to the linker. And finally, this option causes the preprocessor macro "__ANDROID__" to be defined ๐ฅ
-tno-android-ccโ disables the compilation effects of-mandroid, i.e. it does not enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default.-tno-android-ldโ disables the linking effects of-mandroid, i.e. it passes standard Linux linking options to the linker.
๐ธ H8/300 Options ๐ธ
These -m options are defined for the H8/300 implementations:
-mrelaxโ shortens some address references at link time, when possible; it uses the linker option-relax๐ซถ-mhโ bestie, this one generates code for the H8/300H ๐-msโ and this one generates code for the H8S ๐ธ-mnโ generates code for the H8S and the H8/300H, but in the normal mode. Heads up tho: you literally must use this switch with either-mhor-ms, no solo runs allowed ๐-ms2600โ generates code for the H8S/2600. And again, this switch must be used with-msโ they're a package deal fr fr ๐-mexrโ extended registers get stored on the stack before execution of a function with the monitor attribute. The default option is-mexr. This one is valid only for H8S targets ๐-mno-exrโ extended registers are not stored on the stack before execution of a function with the monitor attribute. The default option is-mno-exr. Also valid only for H8S targets โจ-mint32โ makes"int"data 32 bits by default. that's it, that's the whole vibe ๐-malign-300โ on the H8/300H and H8S, this makes GCC use the same alignment rules as for the H8/300. The default for H8/300H and H8S is to align longs and floats on 4-byte boundaries, but-malign-300causes them to be aligned on 2-byte boundaries instead. And ngl, this option has no effect on the H8/300 ๐ฆ
โจ HPPA Options โจ
These -m options are defined for the HPPA family of computers, and there are a lot of them, so buckle up bestie ๐ญ
-march=architecture-type โ generates code for the specified architecture. The choices for architecture-type are1.0for PA 1.0,1.1for PA 1.1, and2.0for PA 2.0 processors. You can refer to/usr/lib/sched.modelson an HP-UX system to figure out the proper architecture option for your machine ๐. Also: code compiled for lower-numbered architectures runs on higher-numbered architectures, but not the other way around. the way that's one-directional... ๐-mpa-risc-1-0-mpa-risc-1-1-mpa-risc-2-0โ these are just synonyms for-march=1.0,-march=1.1, and-march=2.0respectively. cute lil aliases ๐-mcaller-copiesโ the caller copies function arguments passed by hidden reference. Use this one with care, bestie, because it is not compatible with the default 32-bit runtime ๐ซถ. However (and this is the slay part), only aggregates larger than eight bytes are passed by hidden reference, and the option provides better compatibility with OpenMP โจ-mjump-in-delayโ this option is ignored and provided for compatibility purposes only. it's giving decorative ๐-mdisable-fpregsโ prevents floating-point registers from being used in any manner. This is necessary for compiling kernels that perform lazy context switching of floating-point registers. And listen: if you use this option and then try to do floating-point operations, the compiler aborts ๐ญ no cap-mdisable-indexingโ stops the compiler from using indexing address modes. This avoids some rather obscure problems when compiling MIG generated code under MACH ๐ฆ-mno-space-regsโ generates code that assumes the target has no space registers. This lets GCC generate faster indirect calls and use unscaled index address modes โจ. Such code is suitable for level 0 PA systems and kernels ๐-mfast-indirect-callsโ generates code that assumes calls never cross space boundaries. This lets GCC emit code that performs faster indirect calls ๐ฅ. Heads up tho: this option does not work in the presence of shared libraries or nested functions ๐-mfixed-range=register-range โ generates code treating the given register range as fixed registers. A fixed register is one that the register allocator cannot use. This is useful when compiling kernel code ๐ง. A register range is specified as two registers separated by a dash. Multiple register ranges can be specified separated by a comma ๐-mlong-load-storeโ generates 3-instruction load and store sequences as sometimes required by the HP-UX 10 linker. This is equivalent to the+koption to the HP compilers โญ-mportable-runtimeโ uses the portable calling conventions proposed by HP for ELF systems ๐ธ-mgasโ enables the use of assembler directives only GAS understands ๐-mschedule=cpu-type โ schedules code according to the constraints for the machine type cpu-type. The choices for cpu-type are700,7100,7100LC,7200,7300and8000. Refer to/usr/lib/sched.modelson an HP-UX system to figure out the proper scheduling option for your machine. The default scheduling is8000โจ-mlinker-optโ enables the optimization pass in the HP-UX linker. Note that this makes symbolic debugging impossible ๐ญ. It also triggers a bug in the HP-UX 8 and HP-UX 9 linkers in which they give bogus error messages when linking some programs ๐-msoft-floatโ generates output containing library calls for floating point.
Warning: the requisite libraries are not available for all HPPA targets ๐. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation, bestie, no shortcuts.
Also -msoft-float changes the calling convention in the output file. Therefore, it is only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a โ the library that comes with GCC โ with -msoft-float in order for this to work ๐
-msioโ generates the predefine,"_SIO", for server IO. The default is-mwsio. This generates the predefines,"__hp9000s700","__hp9000s700__"and"_WSIO", for workstation IO. These options are available under HP-UX and HI-UX ๐-mgnu-ldโ uses options specific to GNU ld. This passes-sharedto ld when building a shared library. It is the default when GCC is configured, explicitly or implicitly, with the GNU linker. This option does not affect which ld is called; it only changes what parameters are passed to that ld ๐. The ld that is called is determined by the--with-ldconfigure option, GCC's program search path, and finally by the user'sPATH. The linker used by GCC can be printed usinggcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*๐-mhp-ldโ uses options specific to HP ld. This passes-bto ld when building a shared library and passes+Accept TypeMismatchto ld on all links. It is the default when GCC is configured, explicitly or implicitly, with the HP linker. This option does not affect which ld is called; it only changes what parameters are passed to that ld ๐ฆ. The ld that is called is determined by the--with-ldconfigure option, GCC's program search path, and finally by the user'sPATH. The linker used by GCC can be printed usinggcc -print-prog-name=ld. This option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*๐ธ-mlong-callsโ generates code that uses long call sequences. This ensures that a call is always able to reach linker generated stubs โญ. The default is to generate long calls only when the distance from the call site to the beginning of the function or translation unit, as the case may be, exceeds a predefined limit set by the branch type being used. The limits for normal calls are7,600,000and240,000bytes, respectively for the PA 2.0 and PA 1.X architectures. Sibcalls are always limited at240,000bytes.
Distances are measured from the beginning of functions when using the -ffunction-sections option, or when using the -mgas and -mno-portable-runtime options together under HP-UX with the SOM linker ๐ง.
It is normally not desirable to use this option as it degrades performance ๐ญ. However, it may be useful in large applications, particularly when partial linking is used to build the application.
The types of long calls used depends on the capabilities of the assembler and linker, and the type of code being generated. The impact on systems that support long absolute calls, and long pic symbol-difference or pc-relative calls should be relatively small โจ. However, an indirect call is used on 32-bit ELF systems in pic code and it is quite long ๐
-munix=unix-std โ generates compiler predefines and selects a startfile for the specified UNIX standard. The choices for unix-std are93,95and98.93is supported on all HP-UX versions.95is available on HP-UX 10.10 and later.98is available on HP-UX 11.11 and later. The default values are93for HP-UX 10.00,95for HP-UX 10.10 through to 11.00, and98for HP-UX 11.11 and later ๐
-munix=93 provides the same predefines as GCC 3.3 and 3.4. -munix=95 provides additional predefines for "XOPEN_UNIX" and "_XOPEN_SOURCE_EXTENDED", and the startfile unix95.o. -munix=98 provides additional predefines for "_XOPEN_UNIX", "_XOPEN_SOURCE_EXTENDED", "_INCLUDE__STDC_A1_SOURCE" and "_INCLUDE_XOPEN_SOURCE_500", and the startfile unix98.o ๐
It is important to note that this option changes the interfaces for various library routines. It also affects the operational behavior of the C library. Thus, extreme care is needed in using this option ๐ญ
Library code that is intended to operate with more than one UNIX standard must test, set and restore the variable "__xpg4_extended_mask" as appropriate. Most GNU software doesn't provide this capability ๐ซถ
-nolibdldโ suppresses the generation of link options to searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later ๐ธ-staticโ the HP-UX implementation ofsetlocalein libc has a dependency onlibdld.sl. There isn't an archive version oflibdld.sl. Thus, when the-staticoption is specified, special link options are needed to resolve this dependency ๐ง.
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl when the -static option is specified. This causes the resulting binary to be dynamic ๐. On the 64-bit port, the linkers generate dynamic binaries by default in any case. The -nolibdld option can be used to prevent the GCC driver from adding these link options ๐
-threadsโ adds support for multithreading with the dce thread library under HP-UX. This option sets flags for both the preprocessor and linker โจ
โจ IA-64 Options โจ
These are the -m options defined for the Intel IA-64 architecture ๐
-mbig-endianโ generates code for a big-endian target. This is the default for HP-UX ๐-mlittle-endianโ generates code for a little-endian target. This is the default for AIX5 and GNU/Linux ๐-mgnu-as-mno-gnu-asโ generate (or don't) code for the GNU assembler. This is the default โจ-mgnu-ld-mno-gnu-ldโ generate (or don't) code for the GNU linker. This is the default ๐-mno-picโ Generate code that does not use a global pointer register. The result is not position independent code, and it violates the IA-64 ABI. ๐จ-mvolatile-asm-stop,-mno-volatile-asm-stopโ Generate (or don't) a stop bit immediately before and after volatile asm statements. โจ-mregister-names,-mno-register-namesโ Generate (or don't)in,loc, andoutregister names for the stacked registers. This may make assembler output more readable. ๐-mno-sdata,-msdataโ Disable (or enable) optimizations that use the small data section. This may be useful for working around optimizer bugs. ๐-mconstant-gpโ Generate code that uses a single constant global pointer value. This is useful when compiling kernel code. ๐ง-mauto-picโ Generate code that is self-relocatable. This implies-mconstant-gp. This is useful when compiling firmware code. ๐-minline-float-divide-min-latencyโ Generate code for inline divides of floating-point values using the minimum latency algorithm. โก-minline-float-divide-max-throughputโ Generate code for inline divides of floating-point values using the maximum throughput algorithm. ๐ฅ-mno-inline-float-divideโ Do not generate inline code for divides of floating-point values. ๐ซ-minline-int-divide-min-latencyโ Generate code for inline divides of integer values using the minimum latency algorithm. โก-minline-int-divide-max-throughputโ Generate code for inline divides of integer values using the maximum throughput algorithm. ๐ฅ-mno-inline-int-divideโ Do not generate inline code for divides of integer values. ๐ซ-minline-sqrt-min-latencyโ Generate code for inline square roots using the minimum latency algorithm. โก-minline-sqrt-max-throughputโ Generate code for inline square roots using the maximum throughput algorithm. ๐ฅ-mno-inline-sqrtโ Do not generate inline code forsqrt. ๐ซ-mfused-madd,-mno-fused-maddโ Do (don't) generate code that uses the fused multiply/add or multiply/subtract instructions. The default is to use these instructions. โจ-mno-dwarf2-asm,-mdwarf2-asmโ Don't (or do) generate assembler code for the DWARF line number debugging info. This may be useful when not using the GNU assembler. ๐ ๏ธ-mearly-stop-bits,-mno-early-stop-bitsโ Allow stop bits to be placed earlier than immediately preceding the instruction that triggered the stop bit. This can improve instruction scheduling, but does not always do so. ๐-mfixed-range=register-rangeโ Generate code treating the given register range as fixed registers. A fixed register is one that the register allocator cannot use. This is useful when compiling kernel code. A register range is specified as two registers separated by a dash. Multiple register ranges can be specified separated by a comma. ๐ง-mtls-size=tls-sizeโ Specify bit size of immediate TLS offsets. Valid values are14,22, and64. โจ-mtune=cpu-typeโ Tune the instruction scheduling for a particular CPU, Valid values areitanium,itanium1,merced,itanium2, andmckinley. ๐-milp32,-mlp64โ Generate code for a 32-bit or 64-bit environment. The 32-bit environment setsint,longand pointer to 32 bits. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. These are HP-UX specific flags. ๐-mno-sched-br-data-spec,-msched-br-data-specโ Disable or enable data speculative scheduling before reload. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is disabled. ๐ซ-msched-ar-data-spec,-mno-sched-ar-data-specโ Enable or disable data speculative scheduling after reload. This results in generation ofld.ainstructions and the corresponding check instructions (ld.c/chk.a). The default setting is enabled. โ-mno-sched-control-spec,-msched-control-specโ Disable or enable control speculative scheduling. This feature is available only during region scheduling (i.e. before reload). This results in generation of theld.sinstructions and the corresponding check instructionschk.s. The default setting is disabled. ๐ซ-msched-br-in-data-spec,-mno-sched-br-in-data-specโ Enable or disable speculative scheduling of the instructions that are dependent on the data speculative loads before reload. This is effective only with-msched-br-data-specenabled. The default setting is enabled. โ-msched-ar-in-data-spec,-mno-sched-ar-in-data-specโ Enable or disable speculative scheduling of the instructions that are dependent on the data speculative loads after reload. This is effective only with-msched-ar-data-specenabled. The default setting is enabled. โ-msched-in-control-spec,-mno-sched-in-control-specโ Enable or disable speculative scheduling of the instructions that are dependent on the control speculative loads. This is effective only with-msched-control-specenabled. The default setting is enabled. โ-mno-sched-prefer-non-data-spec-insns,-msched-prefer-non-data-spec-insnsโ If enabled, data-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the data speculation much more conservative. The default setting is disabled. ๐ซ-mno-sched-prefer-non-control-spec-insns,-msched-prefer-non-control-spec-insnsโ If enabled, control-speculative instructions are chosen for schedule only if there are no other choices at the moment. This makes the use of the control speculation much more conservative. The default setting is disabled. ๐ซ-mno-sched-count-spec-in-critical-path,-msched-count-spec-in-critical-pathโ If enabled, speculative dependencies are considered during computation of the instructions priorities. This makes the use of the speculation a bit more conservative. The default setting is disabled. ๐ซ-msched-spec-ldcโ Use a simple data speculation check. This option is on by default. โ-msched-control-spec-ldcโ Use a simple check for control speculation. This option is on by default. โ-msched-stop-bits-after-every-cycleโ Place a stop bit after every cycle when scheduling. This option is on by default. โ-msched-fp-mem-deps-zero-costโ Assume that floating-point stores and loads are not likely to cause a conflict when placed into the same instruction group. This option is disabled by default. ๐ซ-msel-sched-dont-check-control-specโ Generate checks for control speculation in selective scheduling. This flag is disabled by default. ๐ซ-msched-max-memory-insns=max-insnsโ Limit on the number of memory insns per instruction group, giving lower priority to subsequent memory insns attempting to schedule in the same instruction group. Frequently useful to prevent cache bank conflicts. The default value is1. โจ-msched-max-memory-insns-hard-limitโ Makes the limit specified bymsched-max-memory-insnsa hard limit, disallowing more than that number in an instruction group. Otherwise, the limit is soft, meaning that non-memory operations are preferred when the limit is reached, but memory operations may still be scheduled. ๐
๐ธ LM32 Options ๐ธ
These -m options are defined for the LatticeMico32 architecture: ๐ฆ
-mbarrel-shift-enabledโ Enable barrel-shift instructions. ๐-mdivide-enabledโ Enable divide and modulus instructions. โจ-mmultiply-enabledโ Enable multiply instructions. ๐ฅ-msign-extend-enabledโ Enable sign extend instructions. ๐ธ-muser-enabledโ Enable user-defined instructions. ๐
๐ง LoongArch Options ๐ง
These command-line options are defined for LoongArch targets: ๐
-march=cpu-typeโ Generate instructions for the machine type cpu-type. In contrast to-mtune=cpu-type, which merely tunes the generated code for the specified cpu-type,-march=cpu-typeallows GCC to generate code that may not run at all on processors other than the one indicated. Specifying-march=cpu-typeimplies-mtune=cpu-type, except where noted otherwise. ๐
The choices for cpu-type are:
nativeโ This selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines). Using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set. ๐ฆloongarch64โ A generic CPU with 64-bit extensions. โจla464โ LoongArch LA464 CPU with LBT, LSX, LASX, LVZ. ๐
-mtune=cpu-typeโ Optimize the output for the given processor, specified by microarchitecture name. ๐-mabi=base-abi-typeโ Generate code for the specified calling convention. base-abi-type can be one of: ๐lp64dโ Uses 64-bit general purpose registers and 32/64-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits. ๐lp64fโ Uses 64-bit general purpose registers and 32-bit floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits. ๐ธlp64sโ Uses 64-bit general purpose registers and no floating-point registers for parameter passing. Data model is LP64, whereintis 32 bits, whilelong intand pointers are 64 bits. โจ
-mfpu=fpu-typeโ Generate code for the specified FPU type, which can be one of: ๐64โ Allow the use of hardware floating-point instructions for 32-bit and 64-bit operations. ๐ฅ32โ Allow the use of hardware floating-point instructions for 32-bit operations. ๐none,0โ Prevent the use of hardware floating-point instructions. ๐ซ
-msoft-floatโ Force-mfpu=noneand prevents the use of floating-point registers for parameter passing. This option may change the target ABI. ๐-msingle-floatโ Force-mfpu=32and allow the use of 32-bit floating-point registers for parameter passing. This option may change the target ABI. โจ-mdouble-floatโ Force-mfpu=64and allow the use of 32/64-bit floating-point registers for parameter passing. This option may change the target ABI. ๐-mbranch-cost=nโ tells the compiler that a branch costs roughly n instructions, so it knows how much it should โจhateโจ branching.-mcheck-zero-division,-mno-check-zero-divisonโ trap (or, like, do NOT trap) when someone divides an integer by zero. Default is-mcheck-zero-divisionwhen you're at-O0or-Og, and-mno-check-zero-divisionat every other optimization level. ๐-mcond-move-int,-mno-cond-move-intโ turns conditional moves for integral data in general-purpose registers on (or off). Default is-mcond-move-int, bestie.-mcond-move-float,-mno-cond-move-floatโ same vibe but for floating-point registers. Enabled / disabled. Default is-mcond-move-float. โจ-mmemcpy,-mno-memcpyโ force (or don't force) usingmemcpyfor non-trivial block moves. Default is-mno-memcpy, which lets GCC inline most constant-sized copies. Setting the optimization level to-Osalso forces the use ofmemcpy, but-mno-memcpymay override that behavior if you explicitly say it โ regardless of the order these options appear on the command line. No cap. ๐ซถ-mstrict-align,-mno-strict-alignโ avoid (or allow) generating memory accesses that might not be aligned on a natural object boundary the way the architecture spec describes. Default is-mno-strict-align.-msmall-data-limit=numberโ shove global and static data smaller than number bytes into a special section (on some targets, okay?). The default value is0.-mmax-inline-memcpy-size=nโ inline every block move (think calls tomemcpyor struct copies) that's less than or equal to n bytes. The default for n is1024. ๐-mcmodel=code-modelโ sets the code model. It's giving choices, and the options are:tiny-static- local symbol and global strong symbol: the data section must be within +/-2MiB addressing space. The text section must be within +/-128MiB addressing space.
- global weak symbol: the got table must be within +/-2GiB addressing space.
tiny- local symbol: the data section must be within +/-2MiB addressing space. The text section must be within +/-128MiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
normal- local symbol: the data section must be within +/-2GiB addressing space. The text section must be within +/-128MiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
large- local symbol: the data section must be within +/-2GiB addressing space. The text section must be within +/-128GiB addressing space.
- global symbol: the got table must be within +/-2GiB addressing space.
extreme(Not implemented yet)- local symbol: the data and text section must be within +/-8EiB addressing space.
- global symbol: the data got table must be within +/-8EiB addressing space.
The default code model is normal. Periodt.
-mrelax,-mno-relaxโ take (or do not take) advantage of linker relaxations. If-mpass-mrelax-to-asis enabled, this option is also passed to the assembler. The default gets decided during GCC build-time by detecting the corresponding assembler support:-mrelaxif the assembler supports both the-mrelaxoption and the conditional branch relaxation (it's required โ otherwise the.aligndirectives and conditional branch instructions in the assembly code outputted by GCC may be rejected by the assembler because of a relocation overflow), and-mno-relaxotherwise. ๐ญ-mpass-mrelax-to-as,-mno-pass-mrelax-to-asโ pass (or do not pass) the-mrelaxor-mno-relaxoption to the assembler. The default is decided during GCC build-time by detecting corresponding assembler support:-mpass-mrelax-to-asif the assembler supports the-mrelaxoption,-mno-pass-mrelax-to-asotherwise. This one's mostly useful for debugging, or for interop with assemblers that aren't the build-time one. ๐ฆ
M32C Options ๐
-mcpu=nameโ pick the CPU you're generating code for. name can ber8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series.-msimโ says the program is gonna run on the simulator. This makes an alternate runtime library get linked in that supports stuff like file I/O. โ ๏ธ You must NOT use this option when generating programs that will run on real hardware; you have to provide your own runtime library for whatever I/O functions you need.-memregs=numberโ says how many memory-based pseudo-registers GCC uses during code generation. These pseudo-registers get used like real registers, so there's a tradeoff between GCC's ability to fit the code into available registers and the performance penalty of using memory instead of registers. Heads up: all modules in a program must be compiled with the same value for this option. Because of that, you must not use this option with GCC's default runtime libraries. ๐
M32R/D Options ๐
These -m options are defined for Renesas M32R/D architectures:
-m32r2โ generate code for the M32R/2.-m32rxโ generate code for the M32R/X.-m32rโ generate code for the M32R. This is the default, bestie.-mmodel=smallโ assume all objects live in the lower 16MB of memory (so their addresses can be loaded with theld24instruction), and assume all subroutines are reachable with theblinstruction. This is the default.
The addressability of a particular object can be set with the model attribute.
-mmodel=mediumโ assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume all subroutines are reachable with theblinstruction.-mmodel=largeโ assume objects may be anywhere in the 32-bit address space (the compiler generatesseth/add3instructions to load their addresses), and assume subroutines may not be reachable with theblinstruction (the compiler generates the much slowerseth/add3/jlinstruction sequence). ๐-msdata=noneโ disable use of the small data area. Variables go into one of.data,.bss, or.rodata(unless thesectionattribute has been specified). This is the default.
The small data area consists of sections .sdata and .sbss. Objects may be explicitly put in the small data area with the section attribute using one of these sections.
-msdata=sdataโ put small global and static data in the small data area, but don't generate special code to reference them.-msdata=useโ put small global and static data in the small data area, and DO generate special instructions to reference them. Slay.-G numโ put global and static objects less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS sections. The default value of num is8. The-msdataoption must be set to one ofsdataorusefor this option to have any effect.
All modules should be compiled with the same -G num value. Compiling with different values of num may or may not work; if it doesn't, the linker gives an error message โ incorrect code is not generated.
-mdebugโ makes the M32R-specific code in the compiler display some statistics that might help when debugging programs.-malign-loopsโ align all loops to a 32-byte boundary.-mno-align-loopsโ don't enforce a 32-byte alignment for loops. This is the default.-missue-rate=numberโ issue number instructions per cycle. number can only be1or2.-mbranch-cost=numberโ number can only be1or2. If it's1then branches are preferred over conditional code; if it's2, then the opposite applies.-mflush-trap=numberโ specifies the trap number to use to flush the cache. The default is12. Valid numbers are between0and15inclusive.-mno-flush-trapโ specifies that the cache cannot be flushed by using a trap.-mflush-func=nameโ specifies the name of the operating system function to call to flush the cache. The default is_flush_cache, but a function call is only used if a trap is not available.-mno-flush-funcโ indicates that there is no OS function for flushing the cache.
M680x0 Options ๐ธ
These are the -m options defined for M680x0 and ColdFire processors. The default settings depend on which architecture was selected when the compiler was configured; the defaults for the most common choices are given below.
-march=archโ generate code for a specific M680x0 or ColdFire instruction set architecture. Permissible values of arch for M680x0 architectures are:68000,68010,68020,68030,68040,68060andcpu32. ColdFire architectures are selected according to Freescale's ISA classification and the permissible values are:isaa,isaaplus,isabandisac.
GCC defines a macro __mcfarch__ whenever it is generating code for a ColdFire target. The arch in this macro is one of the -march arguments given above.
When used together, -march and -mtune select code that runs on a family of similar processors but that is optimized for a particular microarchitecture.
-mcpu=cpuโ generate code for a specific M680x0 or ColdFire processor. The M680x0 cpus are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire cpus are given by the table below, which also classifies the CPUs into families:
Family : -mcpu arguments
51 : 51 51ac 51ag 51cn 51em 51je 51jf 51jg 51jm 51mm 51qe 51qm
5206 : 5202 5204 5206
5206e : 5206e
5208 : 5207 5208
5211a : 5210a 5211a
5213 : 5211 5212 5213
5216 : 5214 5216
52235 : 52230 52231 52232 52233 52234 52235
5225 : 5224 5225
52259 : 52252 52254 52255 52256 52258 52259
5235 : 5232 5233 5234 5235 523x
5249 : 5249
5250 : 5250
5271 : 5270 5271
5272 : 5272
5275 : 5274 5275
5282 : 5280 5281 5282 528x
53017 : 53011 53012 53013 53014 53015 53016 53017
5307 : 5307
5329 : 5327 5328 5329 532x
5373 : 5372 5373 537x
5407 : 5407
5475 : 5470 5471 5472 5473 5474 5475 547x 5480 5481 5482 5483 5484
5485
-mcpu=cpu overrides-march=arch if arch is compatible with cpu. Any other combination of-mcpuand-march? Rejected. Not up for discussion. ๐ โโ๏ธ
GCC defines the macro __mcf_cpu_cpu when a ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is whatever that table above says. ๐
-mtune=tune โ tune the code for one specific microarchitecture, but like... inside the constraints that-marchand-mcpualready set. The M680x0 microarchitectures are:68000,68010,68020,68030,68040,68060andcpu32. The ColdFire microarchitectures are:cfv1,cfv2,cfv3,cfv4andcfv4e.
You can also flex -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is the same energy but it includes 68060 targets too. Both of these select the exact same tuning decisions as -m68020-40 and -m68020-60 respectively. no cap. โจ
GCC defines the macros __mcarch and __mcarch__ when tuning for 680x0 architecture arch. It also defines mcarch unless either -ansi or a non-GNU -std option is used. And if GCC is tuning for a whole range of architectures โ like the ones you get from -mtune=68020-40 or -mtune=68020-60 โ it defines the macros for every architecture in the range. So generous. ๐ซถ
GCC also defines the macro __muarch__ when tuning for ColdFire microarchitecture uarch, where uarch is one of the arguments given above.
-m68000-mc68000โ generate output for a 68000. This is the default when the compiler is configured for 68000-based systems. It's equivalent to-march=68000.
Use this one for microcontrollers with a 68000 or EC000 core, including the 68008, 68302, 68306, 68307, 68322, 68328 and 68356. ๐
-m68010โ generate output for a 68010. This is the default when the compiler is configured for 68010-based systems. It's equivalent to-march=68010.-m68020-mc68020โ generate output for a 68020. This is the default when the compiler is configured for 68020-based systems. It's equivalent to-march=68020.-m68030โ generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It's equivalent to-march=68030.-m68040โ generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It's equivalent to-march=68040.
This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use it if your 68040 does not have code to emulate those instructions. ๐ญ
-m68060โ generate output for a 68060. This is the default when the compiler is configured for 68060-based systems. It's equivalent to-march=68060.
This option inhibits the use of 68020 and 68881/68882 instructions that have to be emulated by software on the 68060. Use it if your 68060 does not have code to emulate those instructions. ๐ญ
-mcpu32โ generate output for a CPU32. This is the default when the compiler is configured for CPU32-based systems. It's equivalent to-march=cpu32.
Use this one for microcontrollers with a CPU32 or CPU32+ core, including the 68330, 68331, 68332, 68333, 68334, 68336, 68340, 68341, 68349 and 68360. ๐
-m5200โ generate output for a 520X ColdFire CPU. This is the default when the compiler is configured for 520X-based systems. It's equivalent to-mcpu=5206, and is now deprecated in favor of that option.
Use this one for microcontroller with a 5200 core, including the MCF5202, MCF5203, MCF5204 and MCF5206.
-m5206eโ generate output for a 5206e ColdFire CPU. The option is now deprecated in favor of the equivalent-mcpu=5206e.-m528xโ generate output for a member of the ColdFire 528X family. The option is now deprecated in favor of the equivalent-mcpu=528x.-m5307โ generate output for a ColdFire 5307 CPU. The option is now deprecated in favor of the equivalent-mcpu=5307.-m5407โ generate output for a ColdFire 5407 CPU. The option is now deprecated in favor of the equivalent-mcpu=5407.-mcfv4eโ generate output for a ColdFire V4e family CPU (e.g.547x/548x). This includes use of hardware floating-point instructions. The option is equivalent to-mcpu=547x, and is now deprecated in favor of that option.-m68020-40โ generate output for a 68040, but without using any of the new instructions. This results in code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68040.
The option is equivalent to -march=68020 -mtune=68020-40. ๐
-m68020-60โ generate output for a 68060, but without using any of the new instructions. This results in code that can run relatively efficiently on either a 68020/68881 or a 68030 or a 68040. The generated code does use the 68881 instructions that are emulated on the 68060.
The option is equivalent to -march=68020 -mtune=68020-60. ๐
-mhard-float-m68881โ generate floating-point instructions. This is the default for 68020 and above, and for ColdFire devices that have an FPU. It defines the macro__HAVE_68881__on M680x0 targets and__mcffpu__on ColdFire targets. ๐ธ-msoft-floatโ do not generate floating-point instructions; use library calls instead. This is the default for 68000, 68010, and 68832 targets. It's also the default for ColdFire devices that have no FPU.-mdiv-mno-divโ generate (do not generate) ColdFire hardware divide and remainder instructions. If-marchis used without-mcpu, the default isonfor ColdFire architectures andofffor M680x0 architectures. Otherwise the default is taken from the target CPU (either the default CPU, or the one specified by-mcpu). For example, the default isofffor-mcpu=5206andonfor-mcpu=5206e.
GCC defines the macro __mcfhwdiv__ when this option is enabled.
-mshortโ consider typeintto be 16 bits wide, likeshort int. Additionally, parameters passed on the stack are also aligned to a 16-bit boundary even on targets whose API mandates promotion to 32-bit.-mno-shortโ do not consider typeintto be 16 bits wide. This is the default.-mnobitfield-mno-bitfieldโ do not use the bit-field instructions. The-m68000,-mcpu32and-m5200options imply-mnobitfield.-mbitfieldโ do use the bit-field instructions. The-m68020option implies-mbitfield. This is the default if you use a configuration designed for a 68020.-mrtdโ use a different function-calling convention, in which functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. This saves one instruction in the caller since there's no need to pop the arguments there. cute, right?
This calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler. ๐จ
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. not optional, bestie.
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.) ๐
The rtd instruction is supported by the 68010, 68020, 68030, 68040, 68060 and CPU32 processors, but not by the 68000 or 5200.
The default is -mno-rtd.
-malign-int-mno-align-intโ control whether GCC alignsint,long,long long,float,double, andlong doublevariables on a 32-bit boundary (-malign-int) or a 16-bit boundary (-mno-align-int). Aligning variables on 32-bit boundaries produces code that runs somewhat faster on processors with 32-bit busses, at the expense of more memory.
Warning: if you use the -malign-int switch, GCC aligns structures containing the above types differently than most published application binary interface specifications for the m68k. ๐ฌ
Use the pc-relative addressing mode of the 68000 directly, instead of using a global offset table. At present, this option implies -fpic, allowing at most a 16-bit offset for pc-relative addressing. -fPIC is not presently supported with -mpcrel, though this could be supported for 68020 and higher processors.
-mno-strict-align-mstrict-alignโ do not (do) assume that unaligned memory references are handled by the system.-msep-dataโ generate code that allows the data segment to be located in a different area of memory from the text segment. This allows for execute-in-place in an environment without virtual memory management. This option implies-fPIC. โจ-mno-sep-dataโ generate code that assumes the data segment follows the text segment. This is the default.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. This allows for execute-in-place and shared libraries in an environment without virtual memory management. This option implies-fPIC. ๐ฆ-mno-id-shared-libraryโ generate code that doesn't assume ID-based shared libraries are being used. This is the default.-mshared-library-id=n โ specifies the identification number of the ID-based shared library being compiled. Specifying a value of0generates more compact code; specifying other values forces the allocation of that number to the current library, but is no more space- or time-efficient than omitting this option. ๐คทโโ๏ธ-mxgot-mno-xgotโ when generating position-independent code for ColdFire, generate code that works if the GOT has more than 8192 entries. This code is larger and slower than code generated without this option. On M680x0 processors, this option is not needed;-fPICsuffices.
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
๐ญ the linker said what it said.
okay so if this happens, you should recompile your code with-mxgot. it should then work with very large GOTs. but bestie, plot twist ๐ญ: code generated with-mxgotis less efficient, since it takes 4 instructions to fetch the value of a global symbol. it's giving tradeoff โจ
ngl, note that some linkers, including newer versions of the GNU linker, can create multiple GOTs and sort GOT entries. if you have such a linker, you should only need to use -mxgot when compiling a single object file that accesses more than 8192 GOT entries. very few do. like, barely anybody fr fr.
these options have no effect unless GCC is generating position-independent code. periodt ๐
-mlong-jump-table-offsetsโ use 32-bit offsets inswitchtables. the default is to use 16-bit offsets.
๐ MCore Options ๐
these are the -m options defined for the Motorola M*Core processors ๐
-mhardlit,-mno-hardlitโ inline constants into the code stream if it can be done in two instructions or less.-mdiv,-mno-divโ use the divide instruction. (Enabled by default).-mrelax-immediate,-mno-relax-immediateโ allow arbitrary-sized immediates in bit operations.-mwide-bitfields,-mno-wide-bitfieldsโ always treat bit-fields asint-sized.-m4byte-functions,-mno-4byte-functionsโ force all functions to be aligned to a 4-byte boundary.-mcallgraph-data,-mno-callgraph-dataโ emit callgraph information.-mslow-bytes,-mno-slow-bytesโ prefer word access when reading byte quantities.-mlittle-endian,-mbig-endianโ generate code for a little-endian target.-m210,-m340โ generate code for the 210 processor.-mno-lsimโ assume that runtime support has been provided and so omit the simulator library (libsim.a) from the linker command line.-mstack-increment=sizeโ set the maximum amount for a single stack increment operation. large values can increase the speed of programs that contain functions that need a large amount of stack space, but they can also trigger a segmentation fault if the stack is extended too much ๐ญ. the default value is0x1000.
๐ฆ MeP Options ๐ฆ
-mabsdiffโ enables theabsinstruction, which is the absolute difference between two registers.-mall-optsโ enables all the optional instructions---average, multiply, divide, bit operations, leading zero, absolute difference, min/max, clip, and saturation. like, all of them. the whole buffet ๐-maverageโ enables theaveinstruction, which computes the average of two registers.-mbased=nโ variables of size n bytes or smaller are placed in the.basedsection by default. based variables use the$tpregister as a base register, and there is a 128-byte limit to the.basedsection.-mbitopsโ enables the bit operation instructions---bit test (btstm), set (bsetm), clear (bclrm), invert (bnotm), and test-and-set (tas).-mc=nameโ selects which section constant data is placed in. name may betiny,near, orfar.-mclipโ enables theclipinstruction. note that-mclipis not useful unless you also provide-mminmax.-mconfig=nameโ selects one of the built-in core configurations. each MeP chip has one or more modules in it; each module has a core CPU and a variety of coprocessors, optional instructions, and peripherals. theMeP-Integratortool, not part of GCC, provides these configurations through this option; using this option is the same as using all the corresponding command-line options. the default configuration isdefault.-mcopโ enables the coprocessor instructions. by default, this is a 32-bit coprocessor. note that the coprocessor is normally enabled via the-mconfig=option.-mcop32โ enables the 32-bit coprocessor's instructions.-mcop64โ enables the 64-bit coprocessor's instructions.-mivc2โ enables IVC2 scheduling. IVC2 is a 64-bit VLIW coprocessor.-mdcโ causes constant variables to be placed in the.nearsection.-mdivโ enables thedivanddivuinstructions.-mebโ generate big-endian code.-melโ generate little-endian code.-mio-volatileโ tells the compiler that any variable marked with theioattribute is to be considered volatile.-mlโ causes variables to be assigned to the.farsection by default.-mleadzโ enables theleadz(leading zero) instruction.-mmโ causes variables to be assigned to the.nearsection by default.-mminmaxโ enables theminandmaxinstructions.-mmultโ enables the multiplication and multiply-accumulate instructions.-mno-optsโ disables all the optional instructions enabled by-mall-opts.-mrepeatโ enables therepeatanderepeatinstructions, used for low-overhead looping.-msโ causes all variables to default to the.tinysection. note that there is a 65536-byte limit to this section. accesses to these variables use the%gpbase register.-msaturโ enables the saturation instructions. note that the compiler does not currently generate these itself, but this option is included for compatibility with other tools, likeas.-msdramโ link the SDRAM-based runtime instead of the default ROM-based runtime.-msimโ link the simulator run-time libraries.-msimnovecโ link the simulator runtime libraries, excluding built-in support for reset and exception vectors and tables.-mtfโ causes all functions to default to the.farsection. without this option, functions default to the.nearsection.-mtiny=nโ variables that are n bytes or smaller are allocated to the.tinysection. these variables use the$gpbase register. the default for this option is4, but note that there's a 65536-byte limit to the.tinysection.
โจ MicroBlaze Options โจ
-msoft-floatโ use software emulation for floating point (default).-mhard-floatโ use hardware floating-point instructions.-mmemcpyโ do not optimize block moves, usememcpy.-mno-clearbssโ this option is deprecated. use-fno-zero-initialized-in-bssinstead.-mcpu=cpu-typeโ use features of, and schedule code for, the given CPU. supported values are in the formatvX.YY.Z, where X is a major version, YY is the minor version, and Z is compatibility code. example values arev3.00.a,v4.00.b,v5.00.a,v5.00.b,v6.00.a.-mxl-soft-mulโ use software multiply emulation (default).-mxl-soft-divโ use software emulation for divides (default).-mxl-barrel-shiftโ use the hardware barrel shifter.-mxl-pattern-compareโ use pattern compare instructions.-msmall-dividesโ use table lookup optimization for small signed integer divisions.-mxl-stack-checkโ this option is deprecated. use-fstack-checkinstead.-mxl-gp-optโ use GP-relative.sdata/.sbsssections.-mxl-multiply-highโ use multiply high instructions for high part of 32x32 multiply.-mxl-float-convertโ use hardware floating-point conversion instructions.-mxl-float-sqrtโ use hardware floating-point square root instruction.-mbig-endianโ generate code for a big-endian target.-mlittle-endianโ generate code for a little-endian target.-mxl-reorderโ use reorder instructions (swap and byte reversed load/store).-mxl-mode-app-modelโ select application model app-model. valid models areexecutableโ normal executable (default), uses startup codecrt0.o.xmdstubโ for use with Xilinx Microprocessor Debugger (XMD) based software intrusive debug agent called xmdstub. this uses startup filecrt1.oand sets the start address of the program to0x800.bootstrapโ for applications that are loaded using a bootloader. this model uses startup filecrt2.owhich does not contain a processor reset vector handler. this is suitable for transferring control on a processor reset to the bootloader rather than the application.novectorsโ for applications that do not require any of the MicroBlaze vectors. this option may be useful for applications running within a monitoring application. this model usescrt3.oas a startup file.
option -xl-mode-app-model is a deprecated alias for -mxl-mode-app-model.
-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. this allows data to be referenced by offset from start of text address instead of GOT since PC-relative addressing is not supported.
๐ MIPS Options ๐
-EBโ generate big-endian code.-ELโ generate little-endian code. this is the default formips*el-*-*configurations.-march=archโ generate code that runs on arch, which can be the name of a generic MIPS ISA, or the name of a particular processor. the ISA names are:mips1,mips2,mips3,mips4,mips32,mips32r2,mips32r3,mips32r5,mips32r6,mips64,mips64r2,mips64r3,mips64r5andmips64r6. the processor names are:4kc,4km,4kp,4ksc,4kec,4kem,4kep,4ksd,5kc,5kf,20kc,24kc,24kf2_1,24kf1_1,24kec,24kef2_1,24kef1_1,34kc,34kf2_1,34kf1_1,34kn,74kc,74kf2_1,74kf1_1,74kf3_2,1004kc,1004kf2_1,1004kf1_1,i6400,i6500,interaptiv,loongson2e,loongson2f,loongson3a,gs464,gs464e,gs264e,m4k,m14k,m14kc,m14ke,m14kec,m5100,m5101,octeon,octeon+,octeon2,octeon3,orion,p5600,p6600,r2000,r3000,r3900,r4000,r4400,r4600,r4650,r4700,r5900,r6000,r8000,rm7000,rm9000,r10000,r12000,r14000,r16000,sb1,sr71000,vr4100,vr4111,vr4120,vr4130,vr4300,vr5000,vr5400,vr5500,xlrandxlp. the special valuefrom-abiselects the most compatible architecture for the selected ABI (that is,mips1for 32-bit ABIs andmips3for 64-bit ABIs).
the native Linux/GNU toolchain also supports the value native, which selects the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
in processor names, a final 000 can be abbreviated as k (for example, -march=r2k). prefixes are optional, and vr may be written r.
Names of the form nf2_1 = processors with FPUs clocked at half the rate of the core, names of the form nf1_1 = processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 = processors with FPUs clocked at a ratio of 3:2 with respect to the core. And for compatibility reasons bestie, nf is accepted as a synonym for nf2_1 while nx and bfx are accepted as synonyms for nf1_1. ๐
GCC defines two macros based on the value of this option. The first is _MIPS_ARCH, which gives the name of the target architecture, as a string. The second has the form _MIPS_ARCH_foo, where foo is the capitalized value of _MIPS_ARCH. So like, for example, -march=r2000 sets _MIPS_ARCH to r2000 and defines the macro _MIPS_ARCH_R2000. โจ
Note that the _MIPS_ARCH macro uses the processor names given above. In other words, it has the full prefix and does not abbreviate 000 as k. In the case of from-abi, the macro names the resolved architecture (either mips1 or mips3). It names the default architecture when no -march option is given.
-mtune=archโ Optimize for arch. Among other things, this option controls the way instructions are scheduled, and the perceived cost of arithmetic operations. The list of arch values is the same as for-march.
When this option is not used, GCC optimizes for the processor specified by -march. By using -march and -mtune together, it is possible to generate code that runs on a family of processors, but optimize the code for one particular member of that family. ๐
-mtune defines the macros _MIPS_TUNE and _MIPS_TUNE_foo, which work in the same way as the -march ones described above.
-mips1โ Equivalent to-march=mips1.-mips2โ Equivalent to-march=mips2.-mips3โ Equivalent to-march=mips3.-mips4โ Equivalent to-march=mips4.-mips32โ Equivalent to-march=mips32.-mips32r3โ Equivalent to-march=mips32r3.-mips32r5โ Equivalent to-march=mips32r5.-mips32r6โ Equivalent to-march=mips32r6.-mips64โ Equivalent to-march=mips64.-mips64r2โ Equivalent to-march=mips64r2.-mips64r3โ Equivalent to-march=mips64r3.-mips64r5โ Equivalent to-march=mips64r5.-mips64r6โ Equivalent to-march=mips64r6.-mips16,-mno-mips16โ Generate (do not generate) MIPS16 code. If GCC is targeting a MIPS32 or MIPS64 architecture, it makes use of the MIPS16e ASE. ๐ง
MIPS16 code generation can also be controlled on a per-function basis by means of mips16 and nomips16 attributes.
-mflip-mips16โ Generate MIPS16 code on alternating functions. This option is provided for regression testing of mixed MIPS16/non-MIPS16 code generation, and is not intended for ordinary use in compiling user code. (Like, it's giving "testing only", bestie, don't ship it. ๐)-minterlink-compressed,-mno-interlink-compressedโ Require (do not require) that code using the standard (uncompressed) MIPS ISA be link-compatible with MIPS16 and microMIPS code, and vice versa.
For example, code using the standard ISA encoding cannot jump directly to MIPS16 or microMIPS code; it must either use a call or an indirect jump. -minterlink-compressed therefore disables direct jumps unless GCC knows that the target of the jump is not compressed.
-minterlink-mips16,-mno-interlink-mips16โ Aliases of-minterlink-compressedand-mno-interlink-compressed. These options predate the microMIPS ASE and are retained for backwards compatibility.-mabi=32,-mabi=o64,-mabi=n32,-mabi=64,-mabi=eabiโ Generate code for the given ABI.
Note that the EABI has a 32-bit and a 64-bit variant. GCC normally generates 64-bit code when you select a 64-bit architecture, but you can use -mgp32 to get 32-bit code instead.
For information about the O64 ABI, see https://gcc.gnu.org/projects/mipso64-abi.html.
GCC supports a variant of the o32 ABI in which floating-point registers are 64 rather than 32 bits wide. You can select this combination with -mabi=32 -mfp64. This ABI relies on the mthc1 and mfhc1 instructions and is therefore only supported for MIPS32R2, MIPS32R3 and MIPS32R5 processors. ๐ธ
The register assignments for arguments and return values remain the same, but each scalar value is passed in a single 64-bit register rather than a pair of 32-bit registers. For example, scalar floating-point values are returned in $f0 only, not a $f0/$f1 pair. The set of call-saved registers also remains the same in that the even-numbered double-precision registers are saved.
Two additional variants of the o32 ABI are supported to enable a transition from 32-bit to 64-bit registers. These are FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg). The FPXX extension mandates that all code must execute correctly when run using 32-bit or 64-bit registers. The code can be interlinked with either FP32 or FP64, but not both. The FP64A extension is similar to the FP64 extension but forbids the use of odd-numbered single-precision registers. This can be used in conjunction with the FRE mode of FPUs in MIPS32R5 processors and allows both FP32 and FP64A code to interlink and run in the same process without changing FPU modes.
-mabicalls,-mno-abicallsโ Generate (do not generate) code that is suitable for SVR4-style dynamic objects.-mabicallsis the default for SVR4-based systems.-mshared,-mno-sharedโ Generate (do not generate) code that is fully position-independent, and that can therefore be linked into shared libraries. This option only affects-mabicalls.
All -mabicalls code has traditionally been position-independent, regardless of options like -fPIC and -fpic. However, as an extension, the GNU toolchain allows executables to use absolute accesses for locally-binding symbols. It can also use shorter GP initialization sequences and generate direct calls to locally-defined functions. This mode is selected by -mno-shared.
-mno-shared depends on binutils 2.16 or higher and generates objects that can only be linked by the GNU linker. However, the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. Using -mno-shared generally makes executables both smaller and quicker. ๐ฅ
-mshared is the default.
-mplt,-mno-pltโ Assume (do not assume) that the static and dynamic linkers support PLTs and copy relocations. This option only affects-mno-shared -mabicalls. For the n64 ABI, this option has no effect without-msym32.
You can make -mplt the default by configuring GCC with --with-mips-plt. The default is -mno-plt otherwise.
-mxgot,-mno-xgotโ Lift (do not lift) the usual restrictions on the size of the global offset table.
GCC normally uses a single instruction to load values from the GOT. While this is relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger causes the linker to report an error such as:
relocation truncated to fit: R_MIPS_GOT16 foobar
If this happens, you should recompile your code with -mxgot. This works with very large GOTs, although the code is also less efficient, since it takes three instructions to fetch the value of a global symbol.
Note that some linkers can create multiple GOTs. If you have such a linker, you should only need to use -mxgot when a single object file accesses more than 64k's worth of GOT entries. Very few do.
These options have no effect unless GCC is generating position independent code.
-mgp32โ Assume that general-purpose registers are 32 bits wide.-mgp64โ Assume that general-purpose registers are 64 bits wide.-mfp32โ Assume that floating-point registers are 32 bits wide.-mfp64โ Assume that floating-point registers are 64 bits wide.-mfpxxโ Do not assume the width of floating-point registers.-mhard-floatโ Use floating-point coprocessor instructions.-msoft-floatโ Do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead.-mno-floatโ Equivalent to-msoft-float, but additionally asserts that the program being compiled does not perform any floating-point operations. This option is presently supported only by some bare-metal MIPS configurations, where it may select a special set of libraries that lack all floating-point support (including, for example, the floating-pointprintfformats). If code compiled with-mno-floataccidentally contains floating-point operations, it is likely to suffer a link-time or run-time failure. ๐ญ-msingle-floatโ Assume that the floating-point coprocessor only supports single-precision operations.-mdouble-floatโ Assume that the floating-point coprocessor supports double-precision operations. This is the default.-modd-spreg,-mno-odd-spregโ Enable the use of odd-numbered single-precision floating-point registers for the o32 ABI. This is the default for processors that are known to support these registers. When using the o32 FPXX ABI,-mno-odd-spregis set by default.-mabs=2008,-mabs=legacyโ These options control the treatment of the special not-a-number (NaN) IEEE 754 floating-point data with theabs.fmtandneg.fmtmachine instructions.
By default or when -mabs=legacy is used the legacy treatment is selected. In this case these instructions are considered arithmetic and avoided where correct operation is required and the input operand might be a NaN. A longer sequence of instructions that manipulate the sign bit of floating-point datum manually is used instead unless the -ffinite-math-only option has also been specified.
The -mabs=2008 option selects the IEEE 754-2008 treatment. In this case these instructions are considered non-arithmetic and therefore operating correctly in all cases, including in particular where the input operand is a NaN. These instructions are therefore always used for the respective operations.
-mnan=2008,-mnan=legacyโ These options control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data. ๐ฆ
Okay so -mnan=legacy picks the legacy NaN encoding, and bestie, here's the tea โ: quiet NaNs (qNaNs) are the ones where the first bit of their trailing significand field is 0, while signaling NaNs (sNaNs) are the ones where that first bit is 1. ๐
-mnan=2008 picks the IEEE 754-2008 encoding instead, and it literally flips everything ๐ โ now qNaNs are the ones where the first bit of their trailing significand field is 1, and sNaNs are the ones where it's 0. โจ
The default is -mnan=legacy unless GCC has been configured with --with-nan=2008. No cap. ๐ซถ
-mllsc,-mno-llscโ use (do not use)ll,sc, andsyncinstructions to implement atomic memory built-in functions. When you don't specify either one, GCC just uses the instructions if the target architecture supports them. ๐คทโโ๏ธ
-mllsc is your girl when the runtime environment can emulate those instructions, and -mno-llsc comes in clutch when you're compiling for nonstandard ISAs. You can make either one the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations โ peep the installation documentation for details. ๐
-mdsp,-mno-dspโ use (do not use) revision 1 of the MIPS DSP ASE. This option defines the preprocessor macro__mips_dsp. It also defines__mips_dsp_revto1. โจ-mdspr2,-mno-dspr2โ use (do not use) revision 2 of the MIPS DSP ASE. This option defines the preprocessor macros__mips_dspand__mips_dspr2. It also defines__mips_dsp_revto2. ๐-msmartmips,-mno-smartmipsโ use (do not use) the MIPS SmartMIPS ASE. ๐ง-mpaired-single,-mno-paired-singleโ use (do not use) paired-single floating-point instructions. Heads up: this option requires hardware floating-point support to be enabled. ๐จ-mdmx,-mno-mdmxโ use (do not use) MIPS Digital Media Extension instructions. This option can only be used when generating 64-bit code and requires hardware floating-point support to be enabled. Two conditions, bestie, don't skip either one. ๐-mips3d,-mno-mips3dโ use (do not use) the MIPS-3D ASE. The option-mips3dimplies-mpaired-single. It's giving "package deal" ๐-mmicromips,-mno-micromipsโ generate (do not generate) microMIPS code.
MicroMIPS code generation can also be controlled on a per-function basis by means of micromips and nomicromips attributes. โจ
-mmt,-mno-mtโ use (do not use) MT Multithreading instructions. ๐งต-mmcu,-mno-mcuโ use (do not use) the MIPS MCU ASE instructions. ๐๏ธ-meva,-mno-evaโ use (do not use) the MIPS Enhanced Virtual Addressing instructions. ๐ซ-mvirt,-mno-virtโ use (do not use) the MIPS Virtualization (VZ) instructions. ๐-mxpa,-mno-xpaโ use (do not use) the MIPS eXtended Physical Address (XPA) instructions. ๐-mcrc,-mno-crcโ use (do not use) the MIPS Cyclic Redundancy Check (CRC) instructions. ๐-mginv,-mno-ginvโ use (do not use) the MIPS Global INValidate (GINV) instructions. ๐ซ-mloongson-mmi,-mno-loongson-mmiโ use (do not use) the MIPS Loongson MultiMedia extensions Instructions (MMI). ๐ฎ-mloongson-ext,-mno-loongson-extโ use (do not use) the MIPS Loongson EXTensions (EXT) instructions. โญ-mloongson-ext2,-mno-loongson-ext2โ use (do not use) the MIPS Loongson EXTensions r2 (EXT2) instructions. ๐-mlong64โ forcelongtypes to be 64 bits wide. See-mlong32for an explanation of the default and the way that the pointer size is determined. ๐-mlong32โ forcelong,int, and pointer types to be 32 bits wide.
The default size of ints, longs and pointers depends on the ABI. All the supported ABIs use 32-bit ints. The n64 ABI uses 64-bit longs, as does the 64-bit EABI; the others use 32-bit longs. Pointers are the same size as longs, or the same size as integer registers, whichever is smaller. Fr fr, that "whichever is smaller" is doing so much work. ๐ญ
-msym32,-mno-sym32โ assume (do not assume) that all symbols have 32-bit values, regardless of the selected ABI. This option is useful in combination with-mabi=64and-mno-abicallsbecause it allows GCC to generate shorter and faster references to symbolic addresses. Short and fast, we love to see it. ๐-Gnum โ put definitions of externally-visible data in a small data section if that data is no bigger than num bytes. GCC can then generate more efficient accesses to the data; see-mgpoptfor details. ๐
The default -G option depends on the configuration.
-mlocal-sdata,-mno-local-sdataโ extend (do not extend) the-Gbehavior to local data too, such as to static variables in C.-mlocal-sdatais the default for all configurations. ๐
If the linker complains that an application is using too much small data, you might want to try rebuilding the less performance-critical parts with -mno-local-sdata. You might also want to build large libraries with -mno-local-sdata, so that the libraries leave more room for the main program. Sharing is caring, bestie. ๐ซถ
-mextern-sdata,-mno-extern-sdataโ assume (do not assume) that externally-defined data is in a small data section if the size of that data is within the-Glimit.-mextern-sdatais the default for all configurations. โจ
If you compile a module Mod with -mextern-sdata -G num -mgpopt, and Mod references a variable Var that is no bigger than num bytes, you must make sure that Var is placed in a small data section. If Var is defined by another module, you must either compile that module with a high-enough -G setting or attach a section attribute to Var's definition. If Var is common, you must link the application with a high-enough -G setting. ๐จ
The easiest way of satisfying these restrictions is to compile and link every module with the same -G option. However, you may wish to build a library that supports several different small data limits. You can do this by compiling the library with the highest supported -G setting and additionally using -mno-extern-sdata to stop the library from making assumptions about externally-defined data. Iconic problem-solving behavior, honestly. ๐
-mgpopt,-mno-gpoptโ use (do not use) GP-relative accesses for symbols that are known to be in a small data section; see-G,-mlocal-sdataand-mextern-sdata.-mgpoptis the default for all configurations. ๐
-mno-gpopt is useful for cases where the $gp register might not hold the value of _gp. For example, if the code is part of a library that might be used in a boot monitor, programs that call boot monitor routines pass an unknown value in $gp. (In such situations, the boot monitor itself is usually compiled with -G0.) ๐ตโ๐ซ
-mno-gpopt implies -mno-local-sdata and -mno-extern-sdata.
-membedded-data,-mno-embedded-dataโ allocate variables to the read-only data section first if possible, then next in the small data section if possible, otherwise in data. This gives slightly slower code than the default, but reduces the amount of RAM required when executing, and thus may be preferred for some embedded systems. Trade-offs, bestie, it's always trade-offs. โ๏ธ-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ put uninitializedconstvariables in the read-only data section. This option is only meaningful in conjunction with-membedded-data. โจ-mcode-readable=setting โ specify whether GCC may generate code that reads from executable sections. There are three possible settings:-mcode-readable=yesโ instructions may freely access executable sections. This is the default setting. ๐-mcode-readable=pcrelโ MIPS16 PC-relative load instructions can access executable sections, but other instructions must not do so. This option is useful on 4KSc and 4KSd processors when the code TLBs have the Read Inhibit bit set. It is also useful on processors that can be configured to have a dual instruction/data SRAM interface and that, like the M4K, automatically redirect PC-relative loads to the instruction RAM. ๐ง-mcode-readable=noโ instructions must not access executable sections. This option can be useful on targets that are configured to have a dual instruction/data SRAM interface but that (unlike the M4K) do not automatically redirect PC-relative loads to the instruction RAM. ๐ซ
-msplit-addresses,-mno-split-addressesโ enable (disable) use of the%hi()and%lo()assembler relocation operators. This option has been superseded by-mexplicit-relocsbut is retained for backwards compatibility. It's giving legacy, but we respect the elders. ๐-mexplicit-relocs,-mno-explicit-relocsโ use (do not use) assembler relocation operators when dealing with symbolic addresses. The alternative, selected by-mno-explicit-relocs, is to use assembler macros instead.
-mexplicit-relocs is the default if GCC was configured to use an assembler that supports relocation operators. ๐
-mcheck-zero-division,-mno-check-zero-divisionโ trap (do not trap) on integer division by zero.
The default is -mcheck-zero-division. โ ๏ธ
-mdivide-traps,-mdivide-breaksโ MIPS systems check for division by zero by generating either a conditional trap or a break instruction. Using traps results in smaller code, but is only supported on MIPS II and later. Also, some versions of the Linux kernel have a bug that prevents trap from generating the proper signal (SIGFPE). Use-mdivide-trapsto allow conditional traps on architectures that support them and-mdivide-breaksto force the use of breaks. ๐
The default is usually -mdivide-traps, but this can be overridden at configure time using --with-divide=breaks. Divide-by-zero checks can be completely disabled using -mno-check-zero-division. ๐
-mload-store-pairs,-mno-load-store-pairsโ enable (disable) an optimization that pairs consecutive load or store instructions to enable load/store bonding. This option is enabled by default but only takes effect when the selected architecture is known to support bonding. ๐ค-munaligned-access,-mno-unaligned-accessโ enable (disable) direct unaligned access for MIPS Release 6. MIPSr6 requires load/store unaligned-access support, by hardware or trap&emulate. So-mno-unaligned-accessmay be needed by kernel. ๐ง-mmemcpy,-mno-memcpyโ force (do not force) the use ofmemcpyfor non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. โจ-mlong-calls/-mno-long-callsโ so this is literally "should we use thejalinstruction or not".-mlong-callsdisables it,-mno-long-callsun-disables it (bestie the double negative is giving me a headache but here we are ๐). Usingjalto call functions is more efficient but it needs the caller AND the callee chillin' in the same 256 megabyte segment. No shared segment, nojal.
Real talk: this option does absolutely nothing to abicalls code. And the default? -mno-long-calls. periodt.
-mmad/-mno-madโ turns themad,maduandmulinstructions on (-mmad) or off (-mno-mad), as provided by the R4650 ISA. iykyk.-mimadd/-mno-imaddโ enable (-mimadd) or disable (-mno-imadd) themaddandmsubinteger instructions. Default is-mimaddon architectures that supportmaddandmsubโ EXCEPT on the 74k architecture, where they found out it generates slower code. 74k said no thank u ๐.-mfused-madd/-mno-fused-maddโ enable/disable the floating-point multiply-accumulate instructions, whenever they're available. Default is-mfused-maddโจ.
Okay heads up on the R8000 CPU: when multiply-accumulate instructions are used, the intermediate product gets calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. Which may be undesirable in some circumstances, no cap. On other processors the result is numerically identical to doing it with separate multiply, add, subtract and negate instructions. so it's giving R8000-specific chaos ๐
-nocppโ tells the MIPS assembler to not run its preprocessor over user assembler files (the ones with a.ssuffix) when assembling them.-mfix-24k/-mno-fix-24kโ works around the 24K E48 errata (lost data on stores during refill, iconic behavior ๐ญ). The workarounds are implemented by the assembler, not by GCC.-mfix-r4000/-mno-fix-r4000โ works around certain R4000 CPU errata:- A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
- A double-word or a variable shift may give an incorrect result if executed while an integer multiplication is in progress.
- An integer division may give an incorrect result if started in a delay slot of a taken branch or a jump.
-mfix-r4400/-mno-fix-r4400โ works around certain R4400 CPU errata:- A double-word or a variable shift may give an incorrect result if executed immediately after starting an integer division.
-mfix-r10000/-mno-fix-r10000โ works around certain R10000 errata:ll/scsequences may not behave atomically on revisions prior to 3.0. They may deadlock on revisions 2.6 and earlier. ๐
This option can only be used if the target architecture supports branch-likely instructions. -mfix-r10000 is the default when -march=r10000 is used; -mno-fix-r10000 is the default otherwise.
-mfix-r5900/-mno-fix-r5900โ do not attempt to schedule the preceding instruction into the delay slot of a branch instruction placed at the end of a short loop of six instructions or fewer, and always schedule anopinstruction there instead. The short loop bug under certain conditions causes loops to execute only once or twice, due to a hardware bug in the R5900 chip (rude honestly). The workaround is implemented by the assembler rather than by GCC.-mfix-rm7000/-mno-fix-rm7000โ works around the RM7000dmult/dmultuerrata. Again, the workarounds live in the assembler, not in GCC.-mfix-vr4120/-mno-fix-vr4120โ works around certain VR4120 errata:dmultudoes not always produce the correct result.divandddivdo not always produce the correct result if one of the operands is negative.
The workarounds for the division errata rely on special functions in libgcc.a. At present, these functions are only provided by the mips64vr*-elf configurations.
Other VR4120 errata require a NOP to be inserted between certain pairs of instructions. Those errata are handled by the assembler, not by GCC itself.
-mfix-vr4130โ works around the VR4130mflo/mfhierrata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids usingmfloandmfhiif the VR4130macc,macchi,dmaccanddmacchiinstructions are available instead. (not me noticing this one has no-mno-twin, we love a solo icon ๐)-mfix-sb1/-mno-fix-sb1โ works around certain SB-1 CPU core errata. Right now this flag works around the SB-1 revision 2F1andF2floating-point errata. the range, bestie โจ-mr10k-cache-barrier=settingโ specifies whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors. buckle up, this one's a whole story ๐ซถ
In common with many processors, the R10K tries to predict the outcome of a conditional branch and speculatively executes instructions from the "taken" branch. It later aborts these instructions if the predicted outcome is wrong. However, on the R10K, even aborted instructions can have side effects.
This problem only affects kernel stores and, depending on the system, kernel loads. As an example, a speculatively-executed store may load the target memory into cache and mark the cache line as dirty, even if the store itself is later aborted. If a DMA operation writes to the same area of memory before the "dirty" line is flushed, the cached data overwrites the DMA-ed data. See the R10K processor manual for a full description, including other potential problems.
One workaround is to insert cache barrier instructions before every memory access that might be speculatively executed and that might have side effects even if aborted. -mr10k-cache-barrier=setting controls GCC's implementation of this workaround. It assumes that aborted accesses to any byte in the following regions does not have side effects:
- the memory occupied by the current function's stack frame;
- the memory occupied by an incoming stack argument;
- the memory occupied by an object with a link-time-constant address.
It is the kernel's responsibility to ensure that speculative accesses to these regions are indeed safe. not GCC's, not yours. the kernel's.
If the input program contains a function declaration such as:
void foo (void);
then the implementation of foo must allow j foo and jal foo to be executed speculatively. GCC honors this restriction for functions it compiles itself. It expects non-GCC functions (such as hand-written assembly code) to do the same.
The option has three forms:
-mr10k-cache-barrier=load-storeโ insert a cache barrier before a load or store that might be speculatively executed and that might have side effects even if aborted.-mr10k-cache-barrier=storeโ insert a cache barrier before a store that might be speculatively executed and that might have side effects even if aborted.-mr10k-cache-barrier=noneโ disable the insertion of cache barriers. This is the default setting.
-mflush-func=func/-mno-flush-funcโ specifies the function to call to flush the I and D caches, or to not call any such function at all. If called, the function must take the same arguments as the common_flush_func, that is, the address of the memory range for which the cache is being flushed, the size of the memory range, and the number3(to flush both caches). The default depends on the target GCC was configured for, but commonly it's either_flush_funcor__cpu_flush. pick your fighter ๐mbranch-cost=numโ set the cost of branches to roughly num "simple" instructions. (yes bestie, no leading dash in the original, I don't make the rules ๐) This cost is only a heuristic and is not guaranteed to produce consistent results across releases. A zero cost redundantly selects the default, which is based on the-mtunesetting.-mbranch-likely/-mno-branch-likelyโ enable or disable use of Branch Likely instructions, regardless of the default for the selected architecture. By default, Branch Likely instructions may be generated if they are supported by the selected architecture. One exception though: for the MIPS32 and MIPS64 architectures and processors that implement those architectures, Branch Likely instructions are not generated by default, because the MIPS32 and MIPS64 architectures specifically deprecate their use. they said no thank u ๐-mcompact-branches=never/-mcompact-branches=optimal/-mcompact-branches=alwaysโ these options control which form of branches will be generated. The default is-mcompact-branches=optimal.
The -mcompact-branches=never option ensures that compact branch instructions will never be generated.
The -mcompact-branches=always option ensures that a compact branch instruction will be generated if available. If a compact branch instruction is not available, a delay slot form of the branch will be used instead.
This option is supported from MIPS Release 6 onwards. ๐
The -mcompact-branches=optimal option will cause a delay slot branch to be used if one is available in the current ISA and the delay slot is successfully filled. If the delay slot is not filled, a compact branch will be chosen if one is available.
-mfp-exceptions/-mno-fp-exceptionsโ specifies whether FP exceptions are enabled. This affects how FP instructions are scheduled for some processors. The default is that FP exceptions are enabled.
For instance, on the SB-1, if FP exceptions are disabled, and we are emitting 64-bit code, then we can use both FP pipes. Otherwise, we can only use one FP pipe. two pipes > one pipe fr fr
-mvr4130-align/-mno-vr4130-alignโ the VR4130 pipeline is two-way superscalar, but it can only issue two instructions together if the first one is 8-byte aligned. When this option is enabled, GCC aligns pairs of instructions that it thinks should execute in parallel. main character scheduling energy โจ
This option only has an effect when optimizing for the VR4130. It normally makes code faster, but at the expense of making it bigger. It is enabled by default at optimization level -O3.
-msynci/-mno-synciโ enable (-msynci) or disable (-mno-synci) generation ofsynciinstructions on architectures that support it. Thesynciinstructions (if enabled) are generated when__builtin___clear_cacheis compiled.
This option defaults to -mno-synci, but the default can be overridden by configuring GCC with --with-synci.
When compiling code for single processor systems, it is generally safe to use synci. However, on many multi-core (SMP) systems, it does not invalidate the instruction caches on all cores and may lead to undefined behavior. bestie please be careful ๐ญ
-mrelax-pic-calls,-mno-relax-pic-callsโ bestie, this one tries to turn PIC calls that normally get dispatched through register$25into direct calls ๐ฅ. That's only possible if the linker can resolve the destination at link time and the destination is within range for a direct call.
-mrelax-pic-calls is the default if GCC was configured to use an assembler and a linker that support the ".reloc" assembly directive and -mexplicit-relocs is in effect. With -mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone, no compiler help needed ๐
.
-mmcount-ra-address,-mno-mcount-ra-addressโ emit (or don't emit) code that lets"_mcount"modify the calling function's return address. When it's enabled, this option extends the usual"_mcount"interface with a new ra-address parameter, which has type"intptr_t *"and is passed in register$12. Then"_mcount"can change the return address by doing both of these:- Returning the new address in register
$31. - Storing the new address in
"*ra-address", if ra-address is nonnull.
- Returning the new address in register
The default is -mno-mcount-ra-address.
-mframe-header-opt,-mno-frame-header-optโ enable (disable) frame header optimization in the o32 ABI ๐. When you're using the o32 ABI, calling functions allocate 16 bytes on the stack for the called function to write out register arguments. When this is enabled, the optimization suppresses the allocation of the frame header if it can be determined that it's unused.
This optimization is off by default at all optimization levels. fr fr.
-mlxc1-sxc1,-mno-lxc1-sxc1โ when applicable, enable (disable) generation of"lwxc1","swxc1","ldxc1","sdxc1"instructions. Enabled by default โจ.-mmadd4,-mno-madd4โ when applicable, enable (disable) generation of 4-operand"madd.s","madd.d"and related instructions. Enabled by default ๐.
๐ MMIX Options ๐
These options are defined for the MMIX:
-mlibfuncs,-mno-libfuncsโ specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size ๐.-mepsilon,-mno-epsilonโ generate floating-point comparison instructions that compare with respect to the"rE"epsilon register.-mabi=mmixware,-mabi=gnuโ generate code that passes function parameters and return values that (inside the called function) are seen as registers$0and up, as opposed to the GNU ABI which uses global registers$231and up ๐ฆ.-mzero-extend,-mno-zero-extendโ when reading data from memory in sizes shorter than 64 bits, use (do not use) zero-extending load instructions by default, rather than sign-extending ones.-mknuthdiv,-mno-knuthdivโ make the result of a division that yields a remainder have the same sign as the divisor. With the default,-mno-knuthdiv, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, and the latter is almost exclusively used ๐ .-mtoplevel-symbols,-mno-toplevel-symbolsโ prepend (do not prepend) a:to all global symbols, so the assembly code can be used with the"PREFIX"assembly directive.-melfโ generate an executable in the ELF format, instead of the default mmo format that the mmix simulator uses.-mbranch-predict,-mno-branch-predictโ use (do not use) the probable-branch instructions when static branch prediction indicates a probable branch ๐ธ.-mbase-addresses,-mno-base-addressesโ generate (do not generate) code that uses base addresses. Using a base address automatically generates a request (handled by the assembler and the linker) for a constant to be set up in a global register. That register gets used for one or more base address requests within the range 0 to 255 from the value held in the register. This generally leads to short and fast code, but the number of different data items that can be addressed is limited ๐ญ. Which means a program that uses lots of static data may need-mno-base-addresses.-msingle-exit,-mno-single-exitโ force (do not force) generated code to have a single exit point in each function.
๐ MN10300 Options ๐
These -m options are defined for Matsushita MN10300 architectures:
-mmult-bugโ generate code to avoid bugs in the multiply instructions for MN10300 processors. This is the default.-mno-mult-bugโ do not generate code to avoid bugs in the multiply instructions for MN10300 processors.-mam33โ generate code using features specific to the AM33 processor.-mno-am33โ do not generate code using features specific to the AM33 processor. This is the default.-mam33-2โ generate code using features specific to the AM33/2.0 processor.-mam34โ generate code using features specific to the AM34 processor.-mtune=cpu-type โ use the timing characteristics of the indicated CPU type when scheduling instructions. This does **not change the targeted processor type. The CPU type must be one ofmn10300,am33,am33-2oram34.-mreturn-pointer-on-d0โ when generating a function that returns a pointer, return the pointer in both"a0"and"d0". Otherwise the pointer is returned only in"a0", and attempts to call such functions without a prototype result in errors ๐. Note that this option is on by default; use-mno-return-pointer-on-d0to disable it.-mno-crt0โ do not link in the C run-time initialization object file.-mrelaxโ tell the linker it should perform a relaxation optimization pass to shorten branches, calls and absolute memory addresses. This option only has an effect when used on the command line for the final link step.
This option makes symbolic debugging impossible. ๐
-mliwโ allow the compiler to generate Long Instruction Word instructions if the target is the AM33 or later. This is the default. This option defines the preprocessor macro"__LIW__".-mno-liwโ do not allow the compiler to generate Long Instruction Word instructions. This option defines the preprocessor macro"__NO_LIW__".-msetlbโ allow the compiler to generate the SETLB and Lcc instructions if the target is the AM33 or later. This is the default. This option defines the preprocessor macro"__SETLB__".-mno-setlbโ do not allow the compiler to generate SETLB or Lcc instructions. This option defines the preprocessor macro"__NO_SETLB__".
๐ฆ Moxie Options ๐ฆ
-mebโ generate big-endian code. This is the default formoxie-*-*configurations.-melโ generate little-endian code.-mmul.xโ generatemul.xandumul.xinstructions. This is the default formoxiebox-*-*configurations.-mno-crt0โ do not link in the C run-time initialization object file.
๐ MSP430 Options ๐
These options are defined for the MSP430:
-masm-hexโ force assembly output to always use hex constants. Normally such constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes โจ.-mmcu=โ select the MCU to target. This is used to create a C preprocessor symbol based on the MCU name, converted to upper case and pre- and post-fixed with__. That symbol in turn is used by themsp430.hheader file to pick an MCU-specific supplementary header file.
The option also sets the ISA to use. If the MCU name is one known to only support the 430 ISA, then that one is selected; otherwise the 430X ISA is selected. A generic MCU name of msp430 can also be used to select the 430 ISA. Similarly, the generic msp430x MCU name selects the 430X ISA.
On top of that, an MCU-specific linker script is added to the linker command line. The script's name is the name of the MCU with .ld appended. So specifying -mmcu=xxx on the gcc command line defines the C preprocessor symbol "__XXX__" and causes the linker to search for a script called xxx.ld ๐
The ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. However, an external devices.csv file can be used to extend device support beyond the ones that have been hard-coded ๐.
GCC searches for the devices.csv file using the following methods in the given precedence order, where the first method takes precedence over the second, which takes precedence over the third:
- Include path specified with
"-I"and"-L"โdevices.csvwill be searched for in each of the directories specified by include paths and linker library search paths. - Path specified by the environment variable
MSP430_GCC_INCLUDE_DIRโ define the value of the global environment variableMSP430_GCC_INCLUDE_DIRto the full path to the directory containingdevices.csv, and GCC will search this directory fordevices.csv. Ifdevices.csvis found, this directory will also be registered as an include path and linker library path. Header files and linker scripts in this directory can therefore be used without manually specifying"-I"and"-L"on the command line. - The
msp430-elf{,bare}/include/devicesdirectory โ finally, GCC will examinemsp430-elf{,bare}/include/devicesfrom the toolchain root directory. This directory does not exist in a default installation, but if the user has created it and copieddevices.csvthere, then the MCU data will be read. As above, this directory will also be registered as an include path and linker library path.
If none of the above search methods find devices.csv, then the hard-coded MCU data is used ๐
.
-mwarn-mcu,-mno-warn-mcuโ this option enables or disables warnings about conflicts between the MCU name specified by the-mmcuoption and the ISA set by the-mcpuoption and/or the hardware multiply support set by the-mhwmultoption. It also toggles warnings about unrecognized MCU names. This option is on by default ๐.-mcpu=โ specifies the ISA to use. Accepted values aremsp430,msp430xandmsp430xv2. This option is deprecated. The-mmcu=option should be used to select the ISA ๐ซถ.-msimโ link to the simulator runtime libraries and linker script. Overrides any scripts that would be selected by the-mmcu=option.-mlargeโ use large-model addressing (20-bit pointers, 20-bit"size_t").-msmallโ okay so this one says use small-model addressing, which is literally 16-bit pointers and a 16-bitsize_t. tiny pointer energy ๐-mrelaxโ this gets passed straight to the assembler and the linker, and it lets the linker do certain optimizations that literally cannot happen until the final link. no cap โจmhwmult=โ bestie, this one describes the type of hardware multiply your target supports. Accepted values arenone(no hardware multiply at all),16bit(the original 16-bit-only multiply that early MCUs had),32bit(the 16/32-bit multiply that later MCUs support), andf5series(the 16/32-bit multiply that F5-series MCUs support). You can also passauto, which tells GCC to deduce the hardware multiply support based on the MCU name you gave with the-mmcuoption. If you didn't specify-mmcu, or if the MCU name isn't recognized, then no hardware multiply support is assumed."auto"is the default setting. deduction queen ๐ง
Hardware multiplies are normally performed by calling a library routine. That saves space in the generated code. But when you compile at -O3 or higher, the hardware multiplier is invoked inline. That makes for bigger, but faster code. speed vs size, the eternal vibe ๐
The hardware multiply routines disable interrupts whilst running and restore the previous interrupt state when they finish. This makes them safe to use inside interrupt handlers as well as in normal code. safe in interrupts, periodt ๐ซถ
-minrtโ enable the use of a minimum runtime environment โ no static initializers or constructors. This is intended for memory-constrained devices. The compiler includes special symbols in some objects that tell the linker and runtime which code fragments are required. memory-constrained besties rise up ๐-mtiny-printfโ enable reduced code sizeprintfandputslibrary functions. The tiny implementations of these functions are not reentrant, so must be used with caution in multi-threaded applications. caution bestie ๐ญ
Support for streams has been removed and the string to be printed will always be sent to stdout via the write syscall. The string is not buffered before it is sent to write. no buffering, straight to write โจ
This option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io. configure flag realness
-mmax-inline-shift=โ this option takes an integer between0and64inclusive, and sets the maximum number of inline shift instructions which should be emitted to perform a shift operation by a constant amount. When this value needs to be exceeded, anmspabihelper function is used instead. The default value is4. default 4, noted ๐
This only affects cases where a shift by multiple positions cannot be completed with a single instruction (e.g. all shifts >1 on the 430 ISA). 430 ISA drama
Shifts of a 32-bit value are at least twice as costly, so the value passed for this option is divided by 2 and the resulting value used instead. math is math ๐ฅ
-mcode-region=,-mdata-region=โ these options tell the compiler where to place functions and data that do not have one of the"lower","upper","either"or"section"attributes. Possible values are"lower","upper","either"or"any". The first three behave like the corresponding attribute. The fourth possible value โ"any"โ is the default. It leaves placement entirely up to the linker script and how it assigns the standard sections (.text,.data, etc) to the memory regions. linker script said what it said ๐-msilicon-errata=โ this option passes on a request to assembler to enable the fixes for the named silicon errata. silicon errata? we fix โจ-msilicon-errata-warn=โ this option passes on a request to the assembler to enable warning messages when a silicon errata might need to be applied. warnings on, bestie-mwarn-devices-csv,-mno-warn-devices-csvโ warn ifdevices.csvis not found or there are problem parsing it (default: on). default on, fr fr
โจ NDS32 Options โจ
These options are defined for NDS32 implementations: NDS32 girlies, this is for you ๐
-mbig-endianโ generate code in big-endian mode. big-endian energy-mlittle-endianโ generate code in little-endian mode. little-endian energy-mreduced-regsโ use reduced-set registers for register allocation. reduced set, reduced stress-mfull-regsโ use full-set registers for register allocation. full set, full vibe-mcmovโ generate conditional move instructions. cmov go brr-mno-cmovโ do not generate conditional move instructions. no cmov, no problem-mext-perfโ generate performance extension instructions. performance extension slay-mno-ext-perfโ do not generate performance extension instructions. no performance extension-mext-perf2โ generate performance extension 2 instructions. performance extension 2 electric boogaloo-mno-ext-perf2โ do not generate performance extension 2 instructions. no ext-perf2-mext-stringโ generate string extension instructions. string extension, string theory-mno-ext-stringโ do not generate string extension instructions. no string extension-mv3pushโ generate v3 push25/pop25 instructions. v3 push25/pop25-mno-v3pushโ do not generate v3 push25/pop25 instructions. no v3 push-m16-bitโ generate 16-bit instructions. 16-bit era-mno-16-bitโ do not generate 16-bit instructions. no 16-bit-misr-vector-size=numโ specify the size of each interrupt vector, which must be4or16. 4 or 16, pick one-mcache-block-size=numโ specify the size of each cache block, which must be a power of 2 between4and512. cache block math-march=archโ specify the name of the target architecture. arch name drop-mcmodel=code-modelโ set the code model to one of:smallโ all the data and read-only data segments must be within 512KB addressing space. The text segment must be within 16MB addressing space. small model, small address spacemediumโ the data segment must be within 512KB while the read-only data segment can be within 4GB addressing space. The text segment should be still within 16MB addressing space. medium model, medium vibeslargeโ all the text and data segments can be within 4GB addressing space. large model, large energy
-mctor-dtorโ enable constructor/destructor feature. ctors and dtors, iconic-mrelaxโ guide linker to relax instructions. relax, take it easy
โจ Nios II Options โจ
These are the options defined for the Altera Nios II processor. Altera Nios II besties, assemble ๐ฆ
-G numโ put global and static objects less than or equal tonumbytes into the small data or BSS sections instead of the normal data or BSS sections. The default value ofnumis8. default 8, periodt-mgpopt=option,-mgpopt,-mno-gpoptโ generate (do not generate) GP-relative accesses. The following option names are recognized: GP-relative access, let's gononeโ do not generate GP-relative accesses. none, zero, nadalocalโ generate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also use GP-relative addressing for objects that have been explicitly placed in a small data section via a"section"attribute. local only, bestieglobalโ as forlocal, but also generate GP-relative accesses for small data objects that are external, weak, or common. If you use this option, you must ensure that all parts of your program (including libraries) are compiled with the same-Gsetting. global, but same -G everywheredataโ generate GP-relative accesses for all data objects in the program. If you use this option, the entire data and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. 64K limit, linker script requiredallโ generate GP-relative addresses for function pointers as well as data pointers. If you use this option, the entire text, data, and BSS segments of your program must fit in 64K of memory and you must use an appropriate linker script to allocate them within the addressable range of the global pointer. all the things, 64K limit
-mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none. equivalences, noted
The default is -mgpopt except when -fpic or -fPIC is specified to generate position-independent code. Note that the Nios II ABI does not permit GP-relative accesses from shared libraries. PIC changes the default
You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In this case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section. sometimes you gotta say no to gpopt
-mgprel-sec=regexpโ this option specifies additional section names that can be accessed via GP-relative addressing. It is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. Theregexpis a POSIX Extended Regular Expression. regexp realness
This option does not affect the behavior of the -G option, and the specified sections are in addition to the standard .sdata and .sbss small-data sections that are recognized by -mgpopt. additional sections, not replacing
-mr0rel-sec=regexpโ this option specifies names of sections that can be accessed via a 16-bit offset from"r0"; that is, in the low 32K or high 32K of the 32-bit address space. It is most useful in conjunction with"section"attributes on variable declarations and a custom linker script. Theregexpis a POSIX Extended Regular Expression. r0-relative, low/high 32K
In contrast to the use of GP-relative addressing for small data, zero-based addressing is never generated by default and there are no conventional section names used in standard linker scripts for sections in the low or high areas of memory. zero-based, never default
-mel,-mebโ generate little-endian (default) or big-endian (experimental) code, respectively. little default, big experimental-march=archโ this specifies the name of the target Nios II architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. Permissible names are:r1,r2. r1 or r2, pick your fighter
The preprocessor macro "__nios2_arch__" is available to programs, with value 1 or 2, indicating the targeted ISA level. macro says 1 or 2
-mbypass-cache,-mno-bypass-cacheโ force all load and store instructions to always bypass cache by using I/O variants of the instructions. The default is not to bypass the cache. cache bypass, or don't-mno-cache-volatile,-mcache-volatileโ volatile memory access bypass the cache using the I/O variants of the load and store instructions. The default is not to bypass the cache. volatile and cache, careful-mno-fast-sw-div,-mfast-sw-divโ do not use table-based fast divide for small numbers. The default is to use the fast divide at-O3and above. fast divide at -O3+-mno-hw-mul,-mhw-mul,-mno-hw-mulx,-mhw-mulx,-mno-hw-div,-mhw-divโ enable or disable emittingmul,mulxanddivfamily of instructions by the compiler. The default is to emitmuland not emitdivandmulx. mul on, div and mulx off by default-mbmx,-mno-bmx,-mcdx,-mno-cdxโ turn generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions on or off. Bestie, if you want these you also need-march=r2โ they literally will not show up otherwise. And because they're optional extensions bolted onto the R2 architecture, the default is not to emit them. No cap. โจ-mcustom-insn=N,-mno-custom-insnโ every-mcustom-insn=Noption lets you use a custom instruction with encoding N whenever the compiler generates code that uses insn. So like,-mcustom-fadds=253generates custom instruction 253 for single-precision floating-point add operations instead of the default behavior of using a library call. Iconic, honestly. ๐
These are the values of insn that are supported. Unless it says otherwise, floating-point operations are expected to be implemented with normal IEEE 754 semantics and correspond directly to the C operators or the equivalent GCC built-in functions.
๐ Single-precision floating point
fadds,fsubs,fdivs,fmulsโ Binary arithmetic operations.fnegsโ Unary negation.fabssโ Unary absolute value.fcmpeqs,fcmpges,fcmpgts,fcmples,fcmplts,fcmpnesโ Comparison operations.fmins,fmaxsโ Floating-point minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified. ๐fsqrtsโ Unary square root operation.fcoss,fsins,ftans,fatans,fexps,flogsโ Floating-point trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified.
๐ Double-precision floating point
faddd,fsubd,fdivd,fmuldโ Binary arithmetic operations.fnegdโ Unary negation.fabsdโ Unary absolute value.fcmpeqd,fcmpged,fcmpgtd,fcmpled,fcmpltd,fcmpnedโ Comparison operations.fmind,fmaxdโ Double-precision minimum and maximum. These instructions are only generated if-ffinite-math-onlyis specified.fsqrtdโ Unary square root operation.fcosd,fsind,ftand,fatand,fexpd,flogdโ Double-precision trigonometric and exponential functions. These instructions are only generated if-funsafe-math-optimizationsis also specified.
๐ Conversions
fextsdโ Conversion from single precision to double precision.ftruncdsโ Conversion from double precision to single precision.fixsi,fixsu,fixdi,fixduโ Conversion from floating point to signed or unsigned integer types, with truncation towards zero.roundโ Conversion from single-precision floating point to signed integer, rounding to the nearest integer and ties away from zero. This corresponds to the__builtin_lroundffunction when-fno-math-errnois used.floatis,floatus,floatid,floatudโ Conversion from signed or unsigned integer types to floating-point types.
And okay, this next bit matters a LOT: all of the following transfer instructions for internal registers X and Y must be provided to use any of the double-precision floating-point instructions. Custom instructions taking two double-precision source operands expect the first operand in the 64-bit register X. The other operand (or only operand of a unary operation) is given to the custom arithmetic instruction with the least significant half in source register src1 and the most significant half in src2. A custom instruction that returns a double-precision result returns the most significant 32 bits in the destination register and the other half in 32-bit register Y. GCC automatically generates the necessary code sequences to write register X and/or read register Y when double-precision floating-point instructions are used. She's doing all the work for you, periodt. ๐
fwrxโ Write src1 into the least significant half of X and src2 into the most significant half of X.fwryโ Write src1 into Y.frdxhi,frdxloโ Read the most or least (respectively) significant half of X and store it in dest.frdyโ Read the value of Y and store it into dest.
Heads up bestie: you can gain more local control over generation of Nios II custom instructions by using thetarget("custom-insn=N")andtarget("no-custom-insn")function attributes or pragmas. ๐ซถ
-mcustom-fpu-cfg=nameโ this one enables a predefined, named set of custom instruction encodings (see-mcustom-insnabove). Right now, these sets are defined:-mcustom-fpu-cfg=60-1is equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
-mcustom-fpu-cfg=60-2is equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
-mcustom-fpu-cfg=72-3is equivalent to:
-mcustom-floatus=243 -mcustom-fixsi=244 -mcustom-floatis=245 -mcustom-fcmpgts=246
-mcustom-fcmples=249 -mcustom-fcmpeqs=250 -mcustom-fcmpnes=251
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254
-mcustom-fdivs=255 -fsingle-precision-constant
-mcustom-fpu-cfg=fph2is equivalent to:
-mcustom-fabss=224 -mcustom-fnegs=225 -mcustom-fcmpnes=226 -mcustom-fcmpeqs=227
-mcustom-fcmpges=228 -mcustom-fcmpgts=229 -mcustom-fcmples=230 -mcustom-fcmplts=231
-mcustom-fmaxs=232 -mcustom-fmins=233 -mcustom-round=248 -mcustom-fixsi=249
-mcustom-floatis=250 -mcustom-fsqrts=251 -mcustom-fmuls=252 -mcustom-fadds=253
-mcustom-fsubs=254 -mcustom-fdivs=255
Custom instruction assignments given by individual -mcustom-insn= options override those given by -mcustom-fpu-cfg=, regardless of the order of the options on the command line. So the individual one always wins, no matter what. ๐ฅ
And yes, you can gain more local control over selection of a FPU configuration by using the target("custom-fpu-cfg=name") function attribute or pragma.
The name fph2 is an abbreviation for Nios II Floating Point Hardware 2 Component. Please note that the custom instructions enabled by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. The custom instruction enabled by -mcustom-round=248 is only generated if -fno-math-errno is specified. And in contrast to the other configurations, -fsingle-precision-constant is not set. The way that one little detail flips the whole vibe, I can't. ๐ญ
These additional -m options are available for the Altera Nios II ELF (bare-metal) target:
-mhalโ Link with HAL BSP. This suppresses linking with the GCC-provided C runtime startup and termination code, and is typically used in conjunction with-msys-crt0=to specify the location of the alternate startup code provided by the HAL BSP.-msmallcโ Link with a limited version of the C library,-lsmallc, rather than Newlib.-msys-crt0=startfileโ startfile is the file name of the startfile (crt0) to use when linking. This option is only useful in conjunction with-mhal.-msys-lib=systemlibโ systemlib is the library name of the library that provides low-level system calls required by the C library, e.g."read"and"write". This option is typically used to link with a library provided by a HAL BSP.
๐ฆ Nvidia PTX Options
These options are defined for Nvidia PTX:
-m64โ Ignored, but preserved for backward compatibility. Only 64-bit ABI is supported. So it just sits there, being decorative. ๐-march=architecture-stringโ Generate code for the specified PTX ISA target architecture (e.g.sm_35). Valid architecture strings aresm_30,sm_35,sm_53,sm_70,sm_75andsm_80. The default target architecture issm_30.
This option sets the value of the preprocessor macro __PTX_SM__; for instance, for sm_35, it has the value 350. โญ
-misa=architecture-stringโ Alias of-march=.-march-map=architecture-stringโ Select the closest available-march=value that is not more capable. For instance, for-march-map=sm_50select-march=sm_35, and for-march-map=sm_53select-march=sm_53.-mptx=version-stringโ Generate code for the specified PTX ISA version (e.g.7.0). Valid version strings include3.1,6.0,6.3, and7.0. The default PTX ISA version is6.0, unless a higher version is required for specified PTX ISA target architecture via option-march=.
This option sets the values of the preprocessor macros __PTX_ISA_VERSION_MAJOR__ and __PTX_ISA_VERSION_MINOR__; for instance, for 3.1 the macros have the values 3 and 1, respectively.
-mmainkernelโ Link in code for a__mainkernel. This is for stand-alone instead of offloading execution.-moptimizeโ Apply partitioned execution optimizations. This is the default when any level of optimization is selected. She's on by default, as she should be. ๐-msoft-stackโ Generate code that does not use".local"memory directly for stack storage. Instead, a per-warp stack pointer is maintained explicitly. This enables variable-length stack allocation (with variable-length arrays or"alloca"), and when global memory is used for underlying storage, makes it possible to access automatic variables from other threads, or with atomic instructions. This code generation variant is used for OpenMP offloading, but the option is exposed on its own for the purpose of testing the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option-mgomp.-muniform-simtโ Switch to code generation variant that allows to execute all threads in each warp, while maintaining memory state and side effects as if only one thread in each warp was active outside of OpenMP SIMD regions. All atomic operations and calls to runtime (malloc,free,vprintf) are conditionally executed (iff current lane index equals the master lane index), and the register being assigned is copied via a shuffle instruction from the master lane. Outside of SIMD regions lane 0 is the master; inside, each thread sees itself as the master. Shared memory arrayint __nvptx_uni[]stores all-zeros or all-ones bitmasks for each warp, indicating current mode (0 outside of SIMD regions). Each thread can bitwise-and the bitmask at positiontid.ywith current lane index to compute the master lane index. That's a whole main character arc right there. ๐ธ-mgompโ Generate code for use in OpenMP offloading: enables-msoft-stackand-muniform-simtoptions, and selects corresponding multilib variant.
๐ง OpenRISC Options
These options are defined for OpenRISC:
-mboard=nameโ sets up a board-specific runtime, and this gets handed off to the linker so it can link against the right newlib board library. Default is"or1ksim"๐-mnewlibโ bestie, this one is literally ignored, it's only hanging around for compatibility reasons. Back in the day it used to pick linker and preprocessor options for use with newlib, but now it's just vibing ๐ซถ-msoft-div/-mhard-divโ picks software or hardware divide instructions (l.div,l.divu). The default is hardware divide โจ-msoft-mul/-mhard-mulโ picks software or hardware multiply instructions (l.mul,l.muli). The default is hardware multiply ๐ฅ-msoft-float/-mhard-floatโ selects software or hardware for floating point operations. The default is software ๐-mdouble-floatโ when-mhard-floatis selected, this turns on generation of double-precision floating point instructions. By default, functions fromlibgccdo the double-precision floating point work instead ๐-munordered-floatโ when-mhard-floatis selected, this enables generation of unordered floating point compare and set flag (lf.sfun*) instructions. By default, functions fromlibgcchandle unordered floating point compare and set flag operations ๐ธ-mcmovโ turns on generation of conditional move (l.cmov) instructions. By default the equivalent gets generated using set and branch ๐ฆ-mrorโ enables generation of rotate right (l.ror) instructions. By default, functions fromlibgccdo the rotate right operations ๐-mroriโ enables generation of rotate right with immediate (l.rori) instructions. By default, functions fromlibgccdo the rotate right with immediate operations โจ-msextโ enables generation of sign extension (l.ext*) instructions. By default, memory loads handle sign extension ๐-msfimmโ enables generation of compare and set flag with immediate (l.sf*i) instructions. By default, extra instructions get generated to store the immediate to a register first ๐-mshftimmโ enables generation of shift with immediate (l.srai,l.srli,l.slli) instructions. By default, extra instructions get generated to store the immediate to a register first ๐ซ-mcmodel=smallโ generates OpenRISC code for the small model: the GOT is limited to 64k. This is the default model ๐-mcmodel=largeโ generates OpenRISC code for the large model: the GOT may grow up to 4G in size. She's big, she's bold, she contains multitudes ๐
๐ฅ๏ธ PDP-11 Options ๐ฅ๏ธ
These options are defined for the PDP-11, bestie:
-mfpuโ use hardware FPP floating point. This is the default. (FIS floating point on the PDP-11/40 is not supported, so don't even try it ๐ญ) Implies-m45.-msoft-floatโ do not use hardware floating point.-mac0โ return floating-point results inac0(fr0in Unix assembler syntax).-mno-ac0โ return floating-point results in memory. This is the default.-m40โ generate code for a PDP-11/40. Implies-msoft-float -mno-split.-m45โ generate code for a PDP-11/45. This is the default.-m10โ generate code for a PDP-11/10. Implies-msoft-float -mno-split.-mint16/-mno-int32โ use 16-bitint. This is the default.-mint32/-mno-int16โ use 32-bitint.-msplitโ target has split instruction and data space. Implies-m45.-munix-asmโ use Unix assembler syntax.-mdec-asmโ use DEC assembler syntax.-mgnu-asmโ use GNU assembler syntax. This is the default.-mlraโ use the new LRA register allocator. By default, the oldreloadallocator is used ๐
๐ picoChip Options ๐
These -m options are defined for picoChip implementations:
-mae=ae_typeโ set the instruction set, register set, and instruction scheduling parameters for array element type ae_type. Supported values for ae_type areANY,MUL, andMAC.-mae=ANYselects a completely generic AE type. Code generated with this option runs on any of the other AE types. The code is not as efficient as it would be if compiled for a specific AE type, and some types of operation (e.g., multiplication) do not work properly on all types of AE ๐ฌ-mae=MULselects a MUL AE type. This is the most useful AE type for compiled code, and is the default โจ-mae=MACselects a DSP-style MAC AE. Code compiled with this option may suffer from poor performance of byte (char) manipulation, since the DSP AE does not provide hardware support for byte load/stores ๐
-msymbol-as-addressโ lets the compiler directly use a symbol name as an address in a load/store instruction, without first loading it into a register. Typically, using this option generates larger programs that run faster than when the option isn't used. However, results vary from program to program, so it's left as a user option rather than being permanently enabled ๐-mno-inefficient-warningsโ disables warnings about the generation of inefficient code. These warnings can pop up, for example, when compiling code that does byte-level memory operations on the MAC AE type. The MAC AE has no hardware support for byte-level memory operations, so all byte load/stores must be synthesized from word load/store operations. This is inefficient, and a warning gets generated to tell you that you should rewrite the code to avoid byte operations, or target an AE type that has the necessary hardware support. This option turns those warnings off ๐
๐ PowerPC Options ๐
These are listed under
๐ง PRU Options ๐ง
These command-line options are defined for the PRU target:
-minrtโ link with a minimum runtime environment, with no support for static initializers and constructors. Using this option can significantly reduce the size of the final ELF binary. Beware: the compiler could still generate code with static initializers and constructors. It is up to the programmer to ensure that the source program will not use those features โ ๏ธ-mmcu=mcuโ specify the PRU MCU variant to use. Check Newlib for the exact list of supported MCUs ๐-mno-relaxโ makes GCC pass the--no-relaxcommand-line option to the linker instead of the--relaxoption.-mloopโ allow (or do not allow) GCC to use theLOOPinstruction ๐-mabi=variantโ specify the ABI variant to output code for.-mabi=tiselects the unmodified TI ABI, while-mabi=gnuselects a GNU variant that copes more naturally with certain GCC assumptions. Here's the tea on the differences:
Function Pointer Size : TI ABI specifies that function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers.
Optional Return Value Pointer : Function return values larger than 64 bits are passed by using a hidden pointer as the first argument of the function. TI ABI, though, mandates that the pointer can be NULL in case the caller is not using the returned value. GNU always passes and expects a valid return value pointer.
The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected. As a consequence, the standard C library cannot be built and it is omitted when linking with -mabi=ti ๐ญ
Relaxation is a GNU feature and for safety reasons is disabled when using -mabi=ti. The TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions ๐
๐ RISC-V Options ๐
These command-line options are defined for RISC-V targets:
-mbranch-cost=nโ set the cost of branches to roughly n instructions.-mplt/-mno-pltโ when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC. The default is-mpltโจ-mabi=ABI-stringโ specify integer and floating-point calling convention. ABI-string contains two parts: the size of integer types and the registers used for floating-point types. For example,-march=rv64ifd -mabi=lp64dmeans that long and pointers are 64-bit (implicitly definingintto be 32-bit), and that floating-point values up to 64 bits wide are passed in F registers. Contrast this with-march=rv64ifd -mabi=lp64f, which still allows the compiler to generate code that uses the F and D extensions but only allows floating-point values up to 32 bits long to be passed in registers; or-march=rv64ifd -mabi=lp64, in which no floating-point arguments will be passed in registers ๐
The default for this argument is system dependent โ users who want a specific calling convention should specify one explicitly. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Some calling conventions are impossible to implement on some ISAs: for example, -march=rv32if -mabi=ilp32d is invalid because the ABI requires 64-bit values be passed in F registers, but F registers are only 32 bits wide. There is also the ilp32e ABI that can only be used with the rv32e architecture. This ABI is not well specified at present, and is subject to change ๐
-mfdiv/-mno-fdivโ do or don't use hardware floating-point divide and square root instructions. This requires the F or D extensions for floating-point registers. The default is to use them if the specified architecture has these instructions ๐-mdiv/-mno-divโ do or don't use hardware instructions for integer division. This requires the M extension. The default is to use them if the specified architecture has these instructions โ-misa-spec=ISA-spec-stringโ specify the version of the RISC-V Unprivileged (formerly User-Level) ISA specification to produce code conforming to. The possibilities for ISA-spec-string are:2.2โ produce code conforming to version 2.2.20190608โ produce code conforming to version 20190608.20191213โ produce code conforming to version 20191213.
The default is -misa-spec=20191213 unless GCC has been configured with --with-isa-spec= specifying a different default version ๐
-march=ISA-stringโ generate code for the given RISC-V ISA (e.g.rv64im). ISA strings must be lower-case. Examples includerv64i,rv32g,rv32e, andrv32imafโจ
When -march= is not specified, use the setting from -mcpu ๐
- If both
-marchand-mcpu=are not specified, the default for this argument is system dependent, users who want a specific architecture extensions should specify one explicitly. -mcpu=processor-stringโ use the architecture of and optimize the output for the given processor, specified by particular CPU name. Permissible values for this option are:sifive-e20,sifive-e21,sifive-e24,sifive-e31,sifive-e34,sifive-e76,sifive-s21,sifive-s51,sifive-s54,sifive-s76,sifive-u54, andsifive-u74.-mtune=processor-stringโ optimize the output for the given processor, specified by microarchitecture or particular CPU name. Permissible values for this option are:rocket,sifive-3-series,sifive-5-series,sifive-7-series,size, and all valid options for-mcpu=.
When -mtune= is not specified, use the setting from -mcpu, the default is rocket if both are not specified.
The size choice is not intended for use by end-users. This is used when -Os is specified. It overrides the instruction cost info provided by -mtune=, but does not override the pipeline info. This helps reduce code size while still giving good performance.
-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a 2 raised tonumbyte boundary. If-mpreferred-stack-boundaryis not specified, the default is 4 (16 bytes or 128-bits).
Warning: if you use this switch, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. No exceptions bestie, this is the whole vibe check. ๐
-msmall-data-limit=nโ put global and static data smaller thannbytes into a special section (on some targets).-msave-restore-mno-save-restoreโ do or don't use smaller but slower prologue and epilogue code that uses library function calls. The default is to use fast inline prologues and epilogues.-mshorten-memrefs-mno-shorten-memrefsโ do or do not attempt to make more use of compressed load/store instructions by replacing a load/store of 'base register + large offset' with a new load/store of 'new base + small offset'. If the new base gets stored in a compressed register, then the new load/store can be compressed. Currently targets 32-bit integer load/stores only.-mstrict-align-mno-strict-alignโ do not or do generate unaligned memory accesses. The default is set depending on whether the processor we are optimizing for supports fast unaligned access or not.-mcmodel=medlowโ generate code for the medium-low code model. The program and its statically defined symbols must lie within a single 2 GiB address range and must lie between absolute addresses -2 GiB and +2 GiB. Programs can be statically or dynamically linked. This is the default code model. โจ-mcmodel=medanyโ generate code for the medium-any code model. The program and its statically defined symbols must be within any single 2 GiB address range. Programs can be statically or dynamically linked.
The code generated by the medium-any code model is position-independent, but is not guaranteed to function correctly when linked into position-independent executables or libraries.
-mexplicit-relocs-mno-exlicit-relocsโ use or do not use assembler relocation operators when dealing with symbolic addresses. The alternative is to use assembler macros instead, which may limit optimization.-mrelax-mno-relaxโ take advantage of linker relaxations to reduce the number of instructions required to materialize symbol addresses. The default is to take advantage of linker relaxations.-memit-attribute-mno-emit-attributeโ emit (do not emit) RISC-V attribute to record extra information into ELF objects. This feature requires at least binutils 2.32.-malign-data=typeโ control how GCC aligns variables and constants of array, structure, or union types. Supported values fortypearexlenwhich uses x register width as the alignment value, andnaturalwhich uses natural alignment.xlenis the default.-mbig-endianโ generate big-endian code. This is the default when GCC is configured for ariscv64be-*-*orriscv32be-*-*target.-mlittle-endianโ generate little-endian code. This is the default when GCC is configured for ariscv64-*-*orriscv32-*-*but not ariscv64be-*-*orriscv32be-*-*target.-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offsetโ generate stack protection code using canary atguard. Supported locations areglobalfor a global canary ortlsfor per-thread canary in the TLS block.
With the latter choice the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which register to use as base register for reading the canary, and from what offset from that base register. There is no default register or offset as this is entirely for use within the Linux kernel. ๐ง
๐ธ RL78 Options ๐ธ
-msimโ links in additional target libraries to support operation within a simulator.-mmul=none-mmul=g10-mmul=g13-mmul=g14-mmul=rl78โ specifies the type of hardware multiplication and division support to be used. The simplest is "none", which uses software for both multiplication and division. This is the default. The "g13" value is for the hardware multiply/divide peripheral found on the RL78/G13 (S2 core) targets. The "g14" value selects the use of the multiplication and division instructions supported by the RL78/G14 (S3 core) parts. The value "rl78" is an alias for "g14" and the value "mg10" is an alias for "none".
In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are: __RL78_MUL_NONE__, __RL78_MUL_G13__ or __RL78_MUL_G14__.
-mcpu=g10-mcpu=g13-mcpu=g14-mcpu=rl78โ specifies the RL78 core to target. The default is the G14 core, also known as an S3 core or just RL78. The G13 or S2 core does not have multiply or divide instructions, instead it uses a hardware peripheral for these operations. The G10 or S1 core does not have register banks, so it uses a different calling convention.
If this option is set it also selects the type of hardware multiply support to use, unless this is overridden by an explicit -mmul=none option on the command line. Thus specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral and specifying -mcpu=g10 disables the use of hardware multiplications altogether.
Note, although the RL78/G14 core is the default target, specifying -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain since it also enables G14 hardware multiply support. If these options are not specified on the command line then software multiplication routines will be used even though the code targets the RL78 core. This is for backwards compatibility with older toolchains which did not have hardware multiply and divide support.
In addition a C preprocessor macro is defined, based upon the setting of this option. Possible values are: __RL78_G10__, __RL78_G13__ or __RL78_G14__.
-mg10-mg13-mg14-mrl78โ these are aliases for the corresponding-mcpu=option. They are provided for backwards compatibility. ๐ซถ-mallregsโ allow the compiler to use all of the available registers. By default registersr24..r31are reserved for use in interrupt handlers. With this option enabled these registers can be used in ordinary functions as well.-m64bit-doubles-m32bit-doublesโ make thedoubledata type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles.-msave-mduc-in-interrupts-mno-save-mduc-in-interruptsโ specifies that interrupt handler functions should preserve the MDUC registers. This is only necessary if normal code might use the MDUC registers, for example because it performs multiplication and division operations. The default is to ignore the MDUC registers as this makes the interrupt handlers faster. The target option-mg13needs to be passed for this to work as this feature is only available on the G13 target (S2 core). The MDUC registers will only be saved if the interrupt handler performs a multiplication or division operation or it calls another function.
๐ IBM RS/6000 and PowerPC Options ๐
These -m options are defined for the IBM RS/6000 and PowerPC:
-mpowerpc-gpopt-mno-powerpc-gpopt-mpowerpc-gfxopt-mno-powerpc-gfxopt-mpowerpc64-mno-powerpc64-mmfcrf-mno-mfcrf-mpopcntb-mno-popcntb-mpopcntd-mno-popcntd-mfprnd-mno-fprnd-mcmpb-mno-cmpb-mhard-dfp-mno-hard-dfpโ you use these options to specify which instructions are available on the processor you are using. The default value of these options is determined when configuring GCC. Specifying the-mcpu=cpu_typeoverrides the specification of these options. We recommend you use the-mcpu=cpu_typeoption rather than the options listed above.
Specifying -mpowerpc-gpopt allows GCC to use the optional PowerPC architecture instructions in the General Purpose group, including floating-point square root. Specifying -mpowerpc-gfxopt allows GCC to use the optional PowerPC architecture instructions in the Graphics group, including floating-point select.
-mmfcrfโ lets GCC generate the move from condition register field instruction, the one implemented on the POWER4 processor and other processors that support the PowerPC V2.01 architecture. โจ-mpopcntbโ lets GCC generate the popcount and double-precision FP reciprocal estimate instruction implemented on the POWER5 processor and other processors that support the PowerPC V2.02 architecture.-mpopcntdโ lets GCC generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture.-mfprndโ lets GCC generate the FP round to integer instructions implemented on the POWER5+ processor and other processors that support the PowerPC V2.03 architecture.-mcmpbโ lets GCC generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture.-mhard-dfpโ lets GCC generate the decimal floating-point instructions implemented on some POWER processors.-mpowerpc64โ lets GCC generate the extra 64-bit instructions found in the full PowerPC64 architecture, and treats GPRs as 64-bit, doubleword quantities. GCC defaults to-mno-powerpc64. ๐ซถ
๐ง -mcpu=cpu_type
-mcpu=cpu_typeโ sets the architecture type, register usage, and instruction scheduling parameters for machine type cpu_type. Slay. ๐
Supported values for cpu_type are: 401, 403, 405, 405fp, 440, 440fp, 464, 464fp, 476, 476fp, 505, 601, 602, 603, 603e, 604, 604e, 620, 630, 740, 7400, 7450, 750, 801, 821, 823, 860, 970, 8540, a2, e300c2, e300c3, e500mc, e500mc64, e5500, e6500, ec603e, G3, G4, G5, titan, power3, power4, power5, power5+, power6, power6x, power7, power8, power9, power10, powerpc, powerpc64, powerpc64le, rs64, and native.
-mcpu=powerpc,-mcpu=powerpc64, and-mcpu=powerpc64lespecify pure 32-bit PowerPC (either endian), 64-bit big endian PowerPC, and 64-bit little endian PowerPC architecture machine types, with an appropriate, generic processor model assumed for scheduling purposes.- Specifying
nativeas cpu type detects and selects the architecture option that corresponds to the host processor of the system performing the compilation.-mcpu=nativehas no effect if GCC does not recognize the processor. ๐ญ - The other options specify a specific processor. Code generated under those options runs best on that processor, and may not run at all on others. Bestie, that's the whole vibe check right there.
- The
-mcpuoptions automatically enable or disable the following options:
-maltivec -mfprnd -mhard-float -mmfcrf -mmultiple -mpopcntb
-mpopcntd -mpowerpc64 -mpowerpc-gpopt -mpowerpc-gfxopt -mmulhw
-mdlmzb -mmfpgpr -mvsx -mcrypto -mhtm -mpower8-fusion
-mpower8-vector -mquad-memory -mquad-memory-atomic -mfloat128
-mfloat128-hardware -mprefixed -mpcrel -mmma -mrop-protect
- The particular options set for any particular CPU varies between compiler versions, depending on what setting seems to produce optimal code for that CPU; it doesn't necessarily reflect the actual hardware's capabilities. If you wish to set an individual option to a particular value, you may specify it after the
-mcpuoption, like-mcpu=970 -mno-altivec. ๐ - On AIX, the
-maltivecand-mpowerpc64options are not enabled or disabled by the-mcpuoption at present, because AIX does not have full support for these options. You may still enable or disable them individually if you're sure it'll work in your environment. ๐
-mtune=cpu_typeโ sets the instruction scheduling parameters for machine type cpu_type, but does not set the architecture type or register usage, unlike-mcpu=cpu_typedoes. Same values for cpu_type apply to-mtuneas to-mcpu. If both are specified, the code generated uses the architecture and registers set by-mcpu, but the scheduling parameters set by-mtune. โจ-mcmodel=smallโ generate PowerPC64 code for the small model: the TOC is limited to64k.-mcmodel=mediumโ generate PowerPC64 code for the medium model: the TOC and other static data may be up to a total of4Gin size. This is the default for 64-bit Linux.-mcmodel=largeโ generate PowerPC64 code for the large model: the TOC may be up to4Gin size. Other data and code is only limited by the 64-bit address space. ๐-maltivec,-mno-altivecโ generate code that uses (does not use) AltiVec instructions, and also enable the use of built-in functions that allow more direct access to the AltiVec instruction set. You may also need to set-mabi=altivecto adjust the current ABI with AltiVec ABI enhancements.
When -maltivec is used, the element order for AltiVec intrinsics such as vec_splat, vec_extract, and vec_insert match array element order corresponding to the endianness of the target. That is, element zero identifies the leftmost element in a vector register when targeting a big-endian platform, and identifies the rightmost element in a vector register when targeting a little-endian platform. ๐ฆ
-mvrsave,-mno-vrsaveโ generate VRSAVE instructions when generating AltiVec code.-msecure-pltโ generate code that allowsldandld.soto build executables and shared libraries with non-executable.pltand.gotsections. This is a PowerPC 32-bit SYSV ABI option.-mbss-pltโ generate code that uses a BSS.pltsection thatld.sofills in, and requires.pltand.gotsections that are both writable and executable. This is a PowerPC 32-bit SYSV ABI option. ๐-misel,-mno-iselโ this switch enables or disables the generation of ISEL instructions.-mvsx,-mno-vsxโ generate code that uses (does not use) vector/scalar (VSX) instructions, and also enable the use of built-in functions that allow more direct access to the VSX instruction set.-mcrypto,-mno-cryptoโ enable the use (disable) of the built-in functions that allow direct access to the cryptographic instructions that were added in version 2.07 of the PowerPC ISA. ๐-mhtm,-mno-htmโ enable (disable) the use of the built-in functions that allow direct access to the Hardware Transactional Memory (HTM) instructions that were added in version 2.07 of the PowerPC ISA.-mpower8-fusion,-mno-power8-fusionโ generate code that keeps (does not keeps) some integer operations adjacent so that the instructions can be fused together on power8 and later processors.-mpower8-vector,-mno-power8-vectorโ generate code that uses (does not use) the vector and scalar instructions that were added in version 2.07 of the PowerPC ISA. Also enable the use of built-in functions that allow more direct access to the vector instructions. โจ-mquad-memory,-mno-quad-memoryโ generate code that uses (does not use) the non-atomic quad word memory instructions. The-mquad-memoryoption requires use of 64-bit mode.-mquad-memory-atomic,-mno-quad-memory-atomicโ generate code that uses (does not use) the atomic quad word memory instructions. The-mquad-memory-atomicoption requires use of 64-bit mode.-mfloat128,-mno-float128โ enable/disable the__float128keyword for IEEE 128-bit floating point, and use either software emulation for IEEE 128-bit floating point or hardware instructions.
The VSX instruction set (-mvsx) must be enabled to use the IEEE 128-bit floating point support. The IEEE 128-bit floating point is only supported on Linux.
The default for -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled on other systems.
If you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9) on a 64-bit system, the IEEE 128-bit floating point support will also enable the generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise, if you do not specify to generate ISA 3.0 instructions or you are targeting a 32-bit big endian system, IEEE 128-bit floating point will be done with software emulation. ๐
-mfloat128-hardware,-mno-float128-hardwareโ enable/disable using ISA 3.0 hardware instructions to support the__float128data type.
The default for -mfloat128-hardware is enabled on PowerPC Linux systems using the ISA 3.0 instruction set, and disabled on other systems.
-m32,-m64โ generate code for 32-bit or 64-bit environments of Darwin and SVR4 targets (including GNU/Linux). The 32-bit environment setsint,longand pointer to 32 bits, and generates code that runs on any PowerPC variant. The 64-bit environment setsintto 32 bits andlongand pointer to 64 bits, and generates code for PowerPC64, as for-mpowerpc64. ๐ซถ
๐ TOC options (yes, Table Of Contents, not the other TOC)
-mfull-toc,-mno-fp-in-toc,-mno-sum-in-toc,-mminimal-tocโ modify generation of the TOC (Table Of Contents), which is created for every executable file. The-mfull-tocoption is selected by default. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program. GCC also places floating-point constants in the TOC. However, only16,384entries are available in the TOC. ๐
If you receive a linker error message that saying you have overflowed the available TOC space, you can reduce the amount of TOC space used with the -mno-fp-in-toc and -mno-sum-in-toc options. -mno-fp-in-toc prevents GCC from putting floating-point constants in the TOC and -mno-sum-in-toc forces GCC to generate code to calculate the sum of an address and a constant at run time instead of putting that sum into the TOC. You may specify one or both of these options. Each causes GCC to produce very slightly slower and larger code at the expense of conserving TOC space.
If you still run out of space in the TOC even when you specify both of these options, specify -mminimal-toc instead. This option causes GCC to make only one TOC entry for every file. When you specify this option, GCC produces code that is slower and larger but which uses extremely little TOC space. You may wish to use this option only on files that contain less frequently-executed code. ๐
ngl bestie, if the linker is screaming about TOC overflow, that's your sign to start stacking these flags. it's giving "we have no more room at the inn" energy. ๐ญ
-maix64,-maix32โ flips on the 64-bit AIX ABI and calling convention: 64-bit pointers, a 64-bitlongtype, and all the little infrastructure bits needed to actually support them. Saying-maix64implies-mpowerpc64, bestie, and-maix32does the reverse โ it disables the 64-bit ABI and implies-mno-powerpc64. GCC defaults to-maix32. iconic.-mxl-compat,-mno-xl-compatโ makes your code behave way more like the IBM XL compiler's semantics when you're rocking an AIX-compatible ABI. Specifically: it passes floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack, in addition to the argument FPRs. It does not assume that the most significant double inside a 128-bitlong doublevalue is properly rounded when comparing values and converting todouble. And it uses XL symbol names forlong doublesupport routines.
okay so here's the lore ๐ซถ: the AIX calling convention got extended, but wasn't initially documented, to handle an obscure K&R C case โ calling a function that takes the address of its arguments, with fewer arguments than declared. IBM XL compilers reach for floating-point arguments that don't fit in the RSA from the stack when a subroutine is compiled without optimization. And since always storing floating-point arguments on the stack is inefficient and rarely needed, this option is not enabled by default โ it's only necessary when you're calling subroutines compiled by IBM XL compilers without optimization.
-mpeโ supports the IBM RS/6000 SP Parallel Environment (PE). It links an application written to use message passing with special startup code so the app can actually run. The system must have PE installed in the standard location (/usr/lpp/ppe.poe/), or the specs file must be overridden with the-specs=option to point at the right directory location. ๐จ PE does not support threads, so-mpeand-pthreadare incompatible โ pick a lane, bestie.-malign-natural,-malign-powerโ on AIX, 32-bit Darwin, and 64-bit PowerPC GNU/Linux,-malign-naturaloverrides the ABI-defined alignment of larger types โ like floating-point doubles โ onto their natural size-based boundary.-malign-powertells GCC to follow the ABI-specified alignment rules instead. GCC defaults to the standard alignment defined in the ABI. โจ
On 64-bit Darwin, natural alignment is the default, and -malign-power is not supported. ๐
-msoft-float,-mhard-floatโ generates code that does not use (or does use) the floating-point register set. Software floating-point emulation is provided if you use-msoft-float, and you gotta pass the option to GCC when linking too. ๐ง-mmultiple,-mno-multipleโ generates code that uses (or doesn't use) the load multiple word instructions and the store multiple word instructions. These get generated by default on POWER systems, and not generated on PowerPC systems. Do not use-mmultipleon little-endian PowerPC systems, since those instructions don't work when the processor is in little-endian mode. The exceptions arePPC740andPPC750, which permit these instructions in little-endian mode. ๐-mupdate,-mno-updateโ generates code that uses (or doesn't use) the load or store instructions that update the base register to the address of the calculated memory location. These instructions are generated by default. But heads up โ ๏ธ โ if you use-mno-update, there's a small window between when the stack pointer is updated and when the address of the previous frame is stored, which means code that walks the stack frame across interrupts or signals may get corrupted data.-mavoid-indexed-addresses,-mno-avoid-indexed-addressesโ generates code that tries to avoid (or not avoid) the use of indexed load or store instructions. These instructions can incur a performance penalty on Power6 processors in certain situations โ like when stepping through large arrays that cross a 16M boundary. This option is enabled by default when targeting Power6 and disabled otherwise. ๐-mfused-madd,-mno-fused-maddโ generates code that uses (or doesn't use) the floating-point multiply and accumulate instructions. These are generated by default if hardware floating point is used. Also, the machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off. โจ-mmulhw,-mno-mulhwโ generates code that uses (or doesn't use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These are generated by default when targeting those processors. ๐-mdlmzb,-mno-dlmzbโ generates code that uses (or doesn't use) the string-searchdlmzbinstruction on the IBM 405, 440, 464 and 476 processors. This instruction is generated by default when targeting those processors. ๐ฆ-mno-bit-align,-mbit-alignโ on System V.4 and embedded PowerPC systems, does not (or does) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.
for example ๐ธ: by default, a structure containing nothing but 8 unsigned bit-fields of length 1 is aligned to a 4-byte boundary and has a size of 4 bytes. By using -mno-bit-align, the structure is aligned to a 1-byte boundary and is 1 byte in size. tiny! ๐
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems, does not (or does) assume that unaligned memory references are handled by the system.-mrelocatable,-mno-relocatableโ generates code that allows (or does not allow) a static executable to be relocated to a different address at run time. A simple embedded PowerPC system loader should relocate the entire contents of.got2and the 4-byte locations listed in the.fixupsection โ a table of 32-bit addresses generated by this option. For this to work, all objects linked together must be compiled with-mrelocatableor-mrelocatable-lib. Also-mrelocatablecode aligns the stack to an 8-byte boundary. ๐-mrelocatable-lib,-mno-relocatable-libโ like-mrelocatable,-mrelocatable-libgenerates a.fixupsection to allow static executables to be relocated at run time, but-mrelocatable-libdoes not use the smaller stack alignment of-mrelocatable. Objects compiled with-mrelocatable-libmay be linked with objects compiled with any combination of the-mrelocatableoptions. ๐ซถ-mno-toc,-mtocโ on System V.4 and embedded PowerPC systems, does not (or does) assume that register 2 contains a pointer to a global area pointing to the addresses used in the program.-mlittle,-mlittle-endianโ on System V.4 and embedded PowerPC systems, compiles code for the processor in little-endian mode.-mlittle-endianis the same as-mlittle. โจ-mbig,-mbig-endianโ on System V.4 and embedded PowerPC systems, compiles code for the processor in big-endian mode.-mbig-endianis the same as-mbig. โจ-mdynamic-no-picโ on Darwin and Mac OS X systems, compiles code so that it is not relocatable, but its external references are relocatable. The resulting code is suitable for applications, but not shared libraries. ๐-msingle-pic-baseโ treats the register used for PIC addressing as read-only, rather than loading it in the prologue for each function. The runtime system is responsible for initializing this register with an appropriate value before execution begins. ๐-mprioritize-restricted-insns=priorityโ controls the priority that gets assigned to dispatch-slot restricted instructions during the second scheduling pass. The argument priority takes the value0,1, or2to assign no, highest, or second-highest (respectively) priority to dispatch-slot restricted instructions. ๐ฏ-msched-costly-dep=dependence_typeโ controls which dependences are considered costly by the target during instruction scheduling. The argument dependence_type takes one of these values:noโ no dependence is costly.allโ all dependences are costly.true_store_to_loadโ a true dependence from store to load is costly.store_to_loadโ any dependence from store to load is costly.- number โ any dependence for which the latency is greater than or equal to number is costly.
-minsert-sched-nops=schemeโ controls which NOP insertion scheme is used during the second scheduling pass. The argument scheme takes one of these values:noโ don't insert NOPs.padโ pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's grouping.regroup_exactโ insert NOPs to force costly dependent insns into separate groups. Insert exactly as many NOPs as needed to force an insn to a new group, according to the estimated processor grouping.- number โ insert NOPs to force costly dependent insns into separate groups. Insert number NOPs to force an insn to a new group.
-mcall-sysvโ on System V.4 and embedded PowerPC systems, compiles code using calling conventions that adhere to the March 1995 draft of the System V Application Binary Interface, PowerPC processor supplement. This is the default unless you configured GCC usingpowerpc-*-eabiaix. ๐-mcall-sysv-eabi,-mcall-eabiโ specifies both-mcall-sysvand-meabioptions. two for one, slay. โจ-mcall-sysv-noeabiโ specifies both-mcall-sysvand-mno-eabioptions.-mcall-aixdescโ on System V.4 and embedded PowerPC systems, compiles code for the AIX operating system. ๐-mcall-linuxโ on System V.4 and embedded PowerPC systems, compiles code for the Linux-based GNU system. ๐ง-mcall-freebsdโ on System V.4 and embedded PowerPC systems, compiles code for the FreeBSD operating system. ๐ฅ-mcall-netbsdโ on System V.4 and embedded PowerPC systems, compiles code for the NetBSD operating system. ๐-mcall-openbsdโ on System V.4 and embedded PowerPC systems, compiles code for the OpenBSD operating system. ๐ก-mtraceback=traceback_typeโ selects the type of traceback table. Valid values for traceback_type arefull,part, andno. ๐-maix-struct-returnโ returns all structures in memory (as specified by the AIX ABI). ๐พ-msvr4-struct-returnโ returns structures smaller than 8 bytes in registers (as specified by the SVR4 ABI). โญ-mabi=abi-typeโ bestie, this one extends the current ABI with a specific extension, or yeets one out. Valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default.-mabi=ibmlongdoubleโ switches the current ABI over to IBM extended-precisionlong double. Heads up though: this is not likely to work if your system defaults to IEEE extended-precisionlong double. If you change thelong doubletype away from IEEE extended-precision, the compiler will throw a warning unless you use-Wno-psabi. Requires-mlong-double-128to be enabled. ๐-mabi=ieeelongdoubleโ switches the current ABI to IEEE extended-precisionlong double. Same vibe check as above: not likely to work if your system defaults to IBM extended-precisionlong double. Change thelong doubletype away from IBM extended-precision and the compiler warns unless you use-Wno-psabi. Requires-mlong-double-128to be enabled.-mabi=elfv1โ switches the current ABI to the ELFv1 ABI. This is the default ABI for big-endian PowerPC 64-bit Linux. Overriding the default ABI requires special system support and is likely to fail in spectacular ways. like, truly iconic levels of chaos ๐ญ-mabi=elfv2โ switches the current ABI to the ELFv2 ABI. This is the default ABI for little-endian PowerPC 64-bit Linux. And again: overriding the default ABI requires special system support and is likely to fail in spectacular ways. ๐-mgnu-attribute,-mno-gnu-attributeโ emit.gnu_attributeassembly directives to set tag/value pairs in a.gnu.attributessection that specify ABI variations in function parameters or return values. cute little metadata moment โจ-mprototype,-mno-prototypeโ on System V.4 and embedded PowerPC systems, assume all calls to variable argument functions are properly prototyped. Otherwise, the compiler has to insert an instruction before every non-prototyped call to set or clear bit 6 of the condition code register ("CR") to indicate whether floating-point values are passed in the floating-point registers, in case the function takes variable arguments. With-mprototype, only calls to prototyped variable argument functions set or clear the bit.-msimโ on embedded PowerPC systems, assume the startup module is calledsim-crt0.oand that the standard C libraries arelibsim.aandlibc.a. This is the default forpowerpc-*-eabisimconfigurations.-mmvmeโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibmvme.aandlibc.a.-madsโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.a.-myellowknifeโ on embedded PowerPC systems, assume the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a. (yellowknife is such a name, honestly ๐)-mvxworksโ on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system.-membโ on embedded PowerPC systems, set the"PPC_EMB"bit in the ELF flags header to indicate that eabi extended relocations are used.-meabi,-mno-eabiโ on System V.4 and embedded PowerPC systems, do (or do not) adhere to the Embedded Applications Binary Interface (EABI), which is a set of modifications to the System V.4 specifications. Picking-meabimeans the stack is aligned to an 8-byte boundary, a function"__eabi"is called from"main"to set up the EABI environment, and the-msdataoption can use both"r2"and"r13"to point to two separate small data areas. Picking-mno-eabimeans the stack is aligned to a 16-byte boundary, no EABI initialization function is called from"main", and the-msdataoption only uses"r13"to point to a single small data area. The-meabioption is on by default if you configured GCC using one of thepowerpc*-*-eabi*options.-msdata=eabiโ on System V.4 and embedded PowerPC systems, put small initialized"const"global and static data in the.sdata2section, which is pointed to by register"r2". Put small initialized non-"const"global and static data in the.sdatasection, pointed to by register"r13". Put small uninitialized global and static data in the.sbsssection, which sits adjacent to the.sdatasection. Warning bestie:-msdata=eabiis incompatible with-mrelocatable. Also,-msdata=eabisets the-memboption.-msdata=sysvโ on System V.4 and embedded PowerPC systems, put small global and static data in the.sdatasection, pointed to by register"r13". Put small uninitialized global and static data in the.sbsssection, adjacent to.sdata. And yeah,-msdata=sysvis incompatible with-mrelocatable. ๐-msdata=default,-msdataโ on System V.4 and embedded PowerPC systems, if-meabiis used, compile code the same as-msdata=eabi, otherwise compile code the same as-msdata=sysv.-msdata=dataโ on System V.4 and embedded PowerPC systems, put small global data in the.sdatasection. Put small uninitialized global data in the.sbsssection. Do not use register"r13"to address small data though. This is the default behavior unless other-msdataoptions are used.-msdata=none,-mno-sdataโ on embedded PowerPC systems, put all initialized global and static data in the.datasection, and all uninitialized data in the.bsssection.-mreadonly-in-sdataโ put read-only objects in the.sdatasection too. This is the default. ๐-mblock-move-inline-limit=numโ inline all block moves (think calls to"memcpy"or structure copies) that are less than or equal to num bytes. The minimum value for num is 32 bytes on 32-bit targets and 64 bytes on 64-bit targets. The default value is target-specific.-mblock-compare-inline-limit=numโ generate non-looping inline code for all block compares (like calls to"memcmp"or structure compares) that are less than or equal to num bytes. If num is 0, all inline expansion (non-loop and loop) of block compare is disabled. The default value is target-specific.-mblock-compare-inline-loop-limit=numโ generate an inline expansion using loop code for all block compares that are less than or equal to num bytes, but greater than the limit for non-loop inline block compare expansion. If the block length isn't constant, at most num bytes will be compared before"memcmp"is called to compare the remainder of the block. The default value is target-specific.-mstring-compare-inline-limit=numโ compare at most num string bytes with inline code. If the difference or end of string isn't found at the end of the inline compare, a call to"strcmp"or"strncmp"takes care of the rest of the comparison. The default is 64 bytes.-G numโ on embedded PowerPC systems, put global and static items less than or equal to num bytes into the small data or BSS sections instead of the normal data or BSS section. By default, num is 8. The-G numswitch also gets passed to the linker. Real talk: all modules should be compiled with the same-G numvalue.-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, do (or do not) emit register names in the assembly language output using symbolic forms.-mlongcall,-mno-longcallโ by default, assume all calls are far away, so a longer and more expensive calling sequence is required. This is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call is generated if the compiler knows the call can't be that far away. This setting can be overridden by the"shortcall"function attribute, or by#pragma longcall(0).
Some linkers can detect out-of-range calls and generate glue code on the fly. On these systems, long calls are unnecessary and generate slower code. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. It's planned to add this feature to the GNU linker for 32-bit PowerPC systems as well. ๐
On PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, GCC can generate long calls using an inline PLT call sequence (see -mpltseq). PowerPC with -mbss-plt and PowerPC64 ELFv1 (big-endian) do not support inline PLT calls.
On Darwin/PPC systems, "#pragma longcall" generates "jbsr callee, L42", plus a branch island (glue code). The two target addresses represent the callee and the branch island. The Darwin/PPC linker prefers the first address and generates a "bl callee" if the PPC "bl" instruction reaches the callee directly; otherwise, the linker generates "bl L42" to call the branch island. The branch island is appended to the body of the calling function; it computes the full 32-bit address of the callee and jumps to it.
On Mach-O (Darwin) systems, this option directs the compiler to emit the glue for every direct call, and the Darwin linker decides whether to use or discard it.
In the future, GCC may ignore all longcall specifications when the linker is known to generate glue. ๐ฎ
-mpltseq,-mno-pltseqโ implement (or do not implement)-fno-pltand long calls using an inline PLT call sequence that supports lazy linking and long calls to functions indlopen'd shared libraries. Inline PLT calls are only supported on PowerPC64 ELFv2 and 32-bit PowerPC systems with newer GNU linkers, and are enabled by default if the support is detected when configuring GCC, and, in the case of 32-bit PowerPC, if GCC is configured with--enable-secureplt. Careful:-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together.-mtls-markers,-mno-tls-markersโ mark (or do not mark) calls to"__tls_get_addr"with a relocation specifying the function argument. The relocation lets the linker reliably associate function call with argument setup instructions for TLS optimization, which in turn lets GCC better schedule the sequence. slay โจ-mrecip/-mno-recipโ okay so this one turns on the reciprocal estimate and reciprocal square root estimate instructions, paired with extra Newton-Raphson steps to bump up the precision, instead of actually doing a divide (or a square root + divide) for floating-point args. Bestie, use-ffast-mathwhen you're using-mrecipโ or at the very least-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math. And heads up: yeah the throughput of the sequence is generally higher than the non-reciprocal instruction's, but the precision can drop by up to 2 ulp ๐ญ โ like, the inverse of1.0comes out as0.99999994for reciprocal square roots. So, vibe check before you ship it.-mrecip=optโ this is the picker, it controls which reciprocal estimate instructions are allowed.optis a comma-separated list of options, and any of them can be preceded by a"!"to invert it:allโ Enable all estimate instructions. โจdefaultโ Enable the default instructions, equivalent to-mrecip.noneโ Disable all estimate instructions, equivalent to-mno-recip.divโ Enable the reciprocal approximation instructions for both single and double precision.divfโ Enable the single-precision reciprocal approximation instructions.divdโ Enable the double-precision reciprocal approximation instructions.rsqrtโ Enable the reciprocal square root approximation instructions for both single and double precision.rsqrtfโ Enable the single-precision reciprocal square root approximation instructions.rsqrtdโ Enable the double-precision reciprocal square root approximation instructions.
So like, for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions except for the FRSQRTE, XSRSQRTEDP, and XVRSQRTEDP instructions โ you know, the ones handling the double-precision reciprocal square root calculations. Slay. ๐
-mrecip-precision/-mno-recip-precisionโ assume (or don't assume) that the reciprocal estimate instructions hand you higher-precision estimates than the PowerPC ABI actually mandates. Picking-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precisionfor you. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they don't give an estimate that converges after three steps. It's giving "trust issues but make it floating point."-mveclibabi=typeโ tells GCC which ABI type to use for vectorizing intrinsics with an external library. The onlytypesupported at present ismass, which means "use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using external libraries." When generating code for power7, GCC currently emits calls toacosd2,acosf4,acoshd2,acoshf4,asind2,asinf4,asinhd2,asinhf4,atan2d2,atan2f4,atand2,atanf4,atanhd2,atanhf4,cbrtd2,cbrtf4,cosd2,cosf4,coshd2,coshf4,erfcd2,erfcf4,erfd2,erff4,exp2d2,exp2f4,expd2,expf4,expm1d2,expm1f4,hypotd2,hypotf4,lgammad2,lgammaf4,log10d2,log10f4,log1pd2,log1pf4,log2d2,log2f4,logd2,logf4,powd2,powf4,sind2,sinf4,sinhd2,sinhf4,sqrtd2,sqrtf4,tand2,tanf4,tanhd2, andtanhf4. (Yeah. All of them. We don't do things halfway here. ๐ซถ) Both-ftree-vectorizeand-funsafe-math-optimizationsmust also be enabled, and the MASS libraries must be specified at link time.-mfriz/-mno-frizโ generate (or don't generate) thefrizinstruction when-funsafe-math-optimizationsis used to optimize rounding of floating-point values to 64-bit integer and back to floating point. But ngl, thefrizinstruction does not return the same value if the floating-point number is too large to fit in an integer. So. Noted. ๐-mpointers-to-nested-functions/-mno-pointers-to-nested-functionsโ generate (or don't) code to load up the static chain register (r11) when calling through a pointer on AIX and 64-bit Linux systems, where a function pointer points to a 3-word descriptor giving the function address, the TOC value to be loaded in registerr2, and the static chain value to be loaded in registerr11.-mpointers-to-nested-functionsis on by default. And fr fr, you cannot call through pointers to nested functions, or pointers to functions compiled in other languages that use the static chain, if you use-mno-pointers-to-nested-functions. ๐-msave-toc-indirect/-mno-save-toc-indirectโ generate (or don't) code to save the TOC value in the reserved stack location in the function prologue if the function calls through a pointer on AIX and 64-bit Linux systems. If the TOC value isn't saved in the prologue, it gets saved just before the call through the pointer instead. The-mno-save-toc-indirectoption is the default.-mcompat-align-parm/-mno-compat-align-parmโ generate (or don't) code to pass structure parameters with a maximum alignment of 64 bits, for compatibility with older versions of GCC. Older versions of GCC (prior to 4.9.0) incorrectly did not align a structure parameter on a 128-bit boundary when that structure contained a member requiring 128-bit alignment. That's fixed in more recent versions. This option is here so you can generate code that's compatible with functions compiled with those older GCC versions. the way that legacy code haunts usโฆ The-mno-compat-align-parmoption is the default.-mstack-protector-guard=guard,-mstack-protector-guard-reg=reg,-mstack-protector-guard-offset=offset,-mstack-protector-guard-symbol=symbolโ generate stack protection code using a canary atguard. Supported locations areglobalfor a global canary, ortlsfor a per-thread canary in the TLS block (that's the default with GNU libc version 2.4 or later). With that second choice, the options-mstack-protector-guard-reg=regand-mstack-protector-guard-offset=offsetalso specify which register to use as the base register for reading the canary, and from what offset from that base register. The defaults for those are as specified in the relevant ABI. And-mstack-protector-guard-symbol=symboloverrides the offset with a symbol reference to a canary in the TLS block. ๐-mpcrel/-mno-pcrelโ generate (or don't) pc-relative addressing. The-mpcreloption requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled. No shortcuts bestie.-mprefixed/-mno-prefixedโ generate (or don't) addressing modes using prefixed load and store instructions. The-mprefixedoption requires that the option-mcpu=power10(or later) is enabled.-mmma/-mno-mmaโ generate (or don't) the MMA instructions. The-mmaoption requires that the option-mcpu=power10(or later) is enabled.-mrop-protect/-mno-rop-protectโ generate (or don't) ROP protection instructions when the target processor supports them. Currently this option disables the shrink-wrap optimization (-fshrink-wrap). ๐ฅ-mprivileged/-mno-privilegedโ generate (or don't) code that will run in privileged state. Main character energy, but make it ring 0. ๐-mblock-ops-unaligned-vsx/-mno-block-ops-unaligned-vsxโ generate (or don't) unaligned vsx loads and stores for inline expansion ofmemcpyandmemmove.
๐ RX Options ๐
These command-line options are defined for RX targets, and they're kinda their own little world:
-m64bit-doubles/-m32bit-doublesโ make thedoubledata type be 64 bits (-m64bit-doubles) or 32 bits (-m32bit-doubles) in size. The default is-m32bit-doubles. Note that RX floating-point hardware only works on 32-bit values, which is, like, exactly why the default is-m32bit-doubles. ๐-fpu/-nofpuโ enables (-fpu) or disables (-nofpu) the use of RX floating-point hardware. The default is enabled for the RX600 series and disabled for the RX200 series. Floating-point instructions are only generated for 32-bit floating-point values though, so the FPU hardware is not used for doubles if you go with-m64bit-doubles. ๐ฆ
Note: if the-fpuoption is enabled, then-funsafe-math-optimizationsis also enabled automatically โ because the RX FPU instructions are themselves unsafe. It said what it said.
-mcpu=nameโ selects the type of RX CPU to target. Currently three types are supported: the generic RX600 and RX200 series hardware, and the specific RX610 CPU. The default is RX600. The only difference between RX600 and RX610 is that the RX610 does not support theMVTIPLinstruction. The RX200 series doesn't have a hardware floating-point unit, so-nofpuis enabled by default when this type is selected.-mbig-endian-data/-mlittle-endian-dataโ store data (but not code) in big-endian format. The default is-mlittle-endian-data, i.e. store data in the little-endian format. โจ-msmall-data-limit=Nโ specifies the maximum size in bytes of global and static variables that can be placed into the small data area. Using the small data area can lead to smaller and faster code, but the size of the area is limited, and it's up to the programmer to make sure the area doesn't overflow. Also, when the small data area is used, one of the RX's registers (usuallyr13) is reserved for use pointing to this area, so it's no longer available for the compiler to use. That could actually result in slower and/or larger code if variables get pushed onto the stack instead of being held in this register. ๐ญ
Note: common variables (variables that have not been initialized) and constants are not placed into the small data area, as they are assigned to other sections in the output executable.
The default value is zero, which disables this feature. Note that this feature is not enabled by default with higher optimization levels (-O2 etc) because of the potentially detrimental effects of reserving a register. It's up to the programmer to experiment and discover whether this feature benefits their program. See the description of the -mpid option for a description of how the actual register to hold the small data area pointer is chosen.
-msim/-mno-simโ use the simulator runtime. The default is to use the libgloss board-specific runtime. ๐ธ-mas100-syntax,-mno-as100-syntaxโ okay so when you're generating assembler output, this makes it use a syntax that's compatible with Renesas's AS100 assembler. This syntax can also be handled by the GAS assembler, but it's got some restrictions, so it's not generated by default. ๐ periodt.-mmax-constant-size=Nโ sets the max size, in bytes, of a constant that can be used as an operand in an RX instruction. The way that RX instructions do allow constants up to 4 bytes long, but a longer value means a longer instruction, so lowkey sometimes it's beneficial to restrict the size of constants used in instructions. Constants that are too big get placed into a constant pool instead and referenced via register indirection. The value N can be between 0 and 4. A value of 0 (the default) or 4 means constants of any size are allowed. โจ-mrelaxโ enables linker relaxation. Linker relaxation is a process where the linker tries to reduce a program's size by finding shorter versions of various instructions. Disabled by default. it's giving shrink era ๐ฆ-mint-register=Nโ says how many registers to reserve for fast interrupt handler functions. N can be between 0 and 4. A value of 1 means registerr13is reserved for the exclusive use of fast interrupt handlers. 2 reservesr13andr12. 3 reservesr13,r12andr11. 4 reservesr13throughr10. A value of 0, the default, reserves no registers. ๐-msave-acc-in-interruptsโ says interrupt handler functions should preserve the accumulator register. This is only necessary if normal code might use the accumulator register, for example because it performs 64-bit multiplications. The default is to ignore the accumulator because that makes the interrupt handlers faster. ๐ธ-mpid,-mno-pidโ enables the generation of position independent data. When enabled, any access to constant data is done via an offset from a base address held in a register. This allows the location of constant data to be determined at run time without requiring the executable to be relocated, which is a benefit to embedded applications with tight memory constraints. Data that can be modified is not affected by this option.
Note: using this feature reserves a register, usually r13, for the constant data base address. This can result in slower and/or larger code, especially in complicated functions. ๐ญ not the slower code era
The actual register chosen to hold the constant data base address depends upon whether the -msmall-data-limit and/or the -mint-register command-line options are enabled. Starting with register r13 and proceeding downwards, registers are allocated first to satisfy the requirements of -mint-register, then -mpid and finally -msmall-data-limit. Thus it is possible for the small data area register to be r8 if both -mint-register=4 and -mpid are specified on the command line.
By default this feature is not enabled. The default can be restored via the -mno-pid command-line option. ๐
-mno-warn-multiple-fast-interrupts,-mwarn-multiple-fast-interruptsโ prevents GCC from issuing a warning message if it finds more than one fast interrupt handler when it is compiling a file. The default is to issue a warning for each extra fast interrupt handler found, as the RX only supports one such interrupt. ๐-mallow-string-insns,-mno-allow-string-insnsโ enables or disables the use of the string manipulation instructionsSMOVF,SCMPU,SMOVB,SMOVU,SUNTILSWHILEand also theRMPAinstruction. These instructions may prefetch data, which is not safe to do if accessing an I/O register. (See section 12.2.7 of the RX62N Group User's Manual for more information).
The default is to allow these instructions, but it is not possible for GCC to reliably detect all circumstances where a string instruction might be used to access an I/O register, so their use cannot be disabled automatically. Instead it is reliant upon the programmer to use the -mno-allow-string-insns option if their program accesses I/O space.
When the instructions are enabled GCC defines the C preprocessor symbol __RX_ALLOW_STRING_INSNS__, otherwise it defines the symbol __RX_DISALLOW_STRING_INSNS__. ๐ซถ
-mjsr,-mno-jsrโ use only (or not only)JSRinstructions to access functions. This option can be used when code size exceeds the range ofBSRinstructions. Note that-mno-jsrdoes not mean to not useJSRbut instead means that any type of branch may be used. ๐
Note: The generic GCC command-line option-ffixed-reghas special significance to the RX port when used with theinterruptfunction attribute. This attribute indicates a function intended to process fast interrupts. GCC ensures that it only uses the registersr10,r11,r12and/orr13and only provided that the normal use of the corresponding registers have been restricted via the-ffixed-regor-mint-registercommand-line options. ๐
๐ S/390 and zSeries Options ๐
These are the -m options defined for the S/390 and zSeries architecture. vibe check: it's giving mainframe energy ๐
-mhard-float,-msoft-floatโ use (do not use) the hardware floating-point instructions and registers for floating-point operations. When-msoft-floatis specified, functions inlibgcc.aare used to perform floating-point operations. When-mhard-floatis specified, the compiler generates IEEE floating-point instructions. This is the default. โจ-mhard-dfp,-mno-hard-dfpโ use (do not use) the hardware decimal-floating-point instructions for decimal-floating-point operations. When-mno-hard-dfpis specified, functions inlibgcc.aare used to perform decimal-floating-point operations. When-mhard-dfpis specified, the compiler generates decimal-floating-point hardware instructions. This is the default for-march=z9-ecor higher. ๐-mlong-double-64,-mlong-double-128โ these switches control the size of thelong doubletype. A size of 64 bits makes thelong doubletype equivalent to thedoubletype. This is the default. ๐-mbackchain,-mno-backchainโ store (do not store) the address of the caller's frame as backchain pointer into the callee's stack frame. A backchain may be needed to allow debugging using tools that do not understand DWARF call frame information. When-mno-packed-stackis in effect, the backchain pointer is stored at the bottom of the stack frame; when-mpacked-stackis in effect, the backchain is placed into the topmost word of the 96/160 byte register save area.
In general, code compiled with -mbackchain is call-compatible with code compiled with -mno-backchain; however, use of the backchain for debugging purposes usually requires that the whole binary is built with -mbackchain. Note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float.
The default is to not maintain the backchain. ๐ธ
-mpacked-stack,-mno-packed-stackโ use (do not use) the packed stack layout. When-mno-packed-stackis specified, the compiler uses the all fields of the 96/160 byte register save area only for their default purpose; unused fields still take up stack space. When-mpacked-stackis specified, register save slots are densely packed at the top of the register save area; unused space is reused for other purposes, allowing for more efficient use of the available stack space. However, when-mbackchainis also in effect, the topmost word of the save area is always used to store the backchain, and the return address register is always saved two words below the backchain.
As long as the stack frame backchain is not used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Note that some non-FSF releases of GCC 2.95 for S/390 or zSeries generated code that uses the stack frame backchain at run time, not just for debugging purposes. Such code is not call-compatible with code compiled with -mpacked-stack. Also, note that the combination of -mbackchain, -mpacked-stack and -mhard-float is not supported. In order to build a linux kernel use -msoft-float.
The default is to not use the packed stack layout. ๐
-msmall-exec,-mno-small-execโ generate (or do not generate) code using thebrasinstruction to do subroutine calls. This only works reliably if the total executable size does not exceed 64k. The default is to use thebasrinstruction instead, which does not have this limitation. ๐ฅ-m64,-m31โ when-m31is specified, generate code compliant to the GNU/Linux for S/390 ABI. When-m64is specified, generate code compliant to the GNU/Linux for zSeries ABI. This allows GCC in particular to generate 64-bit instructions. For the s390 targets, the default is-m31, while the s390x targets default to-m64. ๐-mzarch,-mesaโ when-mzarchis specified, generate code using the instructions available on z/Architecture. When-mesais specified, generate code using the instructions available on ESA/390. Note that-mesais not possible with-m64. When generating code compliant to the GNU/Linux for S/390 ABI, the default is-mesa. When generating code compliant to the GNU/Linux for zSeries ABI, the default is-mzarch. ๐-mhtm,-mno-htmโ the-mhtmoption enables a set of builtins making use of instructions available with the transactional execution facility introduced with the IBM zEnterprise EC12 machine generation S/390 System z Built-in Functions.-mhtmis enabled by default when using-march=zEC12. โจ-mvx,-mno-vxโ when-mvxis specified, generate code using the instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option changes the ABI for some vector type values with regard to alignment and calling conventions. In case vector type values are being used in an ABI-relevant context a GAS.gnu_attributecommand will be added to mark the resulting binary with the ABI used.-mvxis enabled by default when using-march=z13. ๐-mzvector,-mno-zvectorโ okay bestie this one is giving vector energy ๐ .-mzvectorturns on vector language extensions and builtins that use the instructions from the vector extension facility that showed up with the IBM z13 machine generation. It also adds support forvectoras a keyword so you can define vector type variables and arguments. Tiny catch:vectoris only available when GNU extensions are enabled, so it will not be expanded if you're demanding strict standard compliance, like with-std=c99. On top of the GCC low-level builtins,-mzvectorenables a whole set of builtins added for compatibility with AltiVec-style implementations like Power and Cell โ and to actually use those you need to include the header filevecintrin.h.-mzvectoris disabled by default. โจ-mmvcle,-mno-mvcleโ generate (or don't generate) code that uses the"mvcle"instruction to do block moves. When you pass-mno-mvcle, it uses an"mvc"loop instead. That's the default unless you're optimizing for size.-mdebug,-mno-debugโ print (or don't print) extra debug info while compiling. Default vibe is: no debug info. ๐-march=cpu-typeโ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. The possible values for cpu-type arez900/arch5,z990/arch6,z9-109,z9-ec/arch7,z10/arch8,z196/arch9,zEC12,z13/arch11,z14/arch12,z15/arch13,z16/arch14, andnative.
The default is -march=z900.
Specifying native as the cpu type selects the best architecture option for the host processor. Heads up though: -march=native has no effect if GCC doesn't recognize the processor. ๐ญ
-mtune=cpu-typeโ tune everything applicable about the generated code to cpu-type, except for the ABI and the set of available instructions. The list of cpu-type values is the same as for-march. The default is whatever value you used for-march.-mtpf-trace,-mno-tpf-traceโ generate code that adds (or doesn't add) TPF OS specific branches to trace routines in the operating system. This option is off by default, even when you're compiling for the TPF OS. ๐ซถ-mtpf-trace-skip,-mno-tpf-trace-skipโ generate code that changes (or doesn't change) the default branch targets enabled by-mtpf-traceso they point at specialized trace routines that can selectively skip function trace entries for the TPF OS. This one is also off by default, even when compiling for the TPF OS and specifying-mtpf-trace.-mfused-madd,-mno-fused-maddโ generate code that uses (or doesn't use) the floating-point multiply and accumulate instructions. These instructions are generated by default if hardware floating point is used. ๐ฅ-mwarn-framesize=framesizeโ emit a warning if the current function blows past the given frame size. Since it's a compile-time check, it doesn't have to be a real problem when the program actually runs โ it's meant to sniff out functions that most probably cause a stack overflow. Super useful in an environment with a limited stack size, e.g. the linux kernel. ๐-mwarn-dynamicstackโ emit a warning if the function calls"alloca"or uses dynamically-sized arrays. Ngl, that's generally a bad idea when your stack size is limited. ๐-mstack-guard=stack-guard,-mstack-size=stack-sizeโ if you provide these, the S/390 back end emits extra instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember: the stack on S/390 grows downward, bestie). If the stack-guard option is omitted, the smallest power of 2 larger than the frame size of the compiled function is chosen. These options are intended to help debug stack overflow problems. The extra code only adds a little overhead, so it can also be used in production-like systems without greater performance degradation. The given values have to be exact powers of 2, and stack-size has to be greater than stack-guard without exceeding 64k. To stay efficient, the extra code assumes the stack starts at an address aligned to the value given by stack-size. Also, the stack-guard option can only be used together with stack-size.-mhotpatch=pre-halfwords,post-halfwordsโ if the hotpatch option is enabled, a"hot-patching"function prologue is generated for all functions in the compilation unit. The funtion label gets prepended with the given number of two-byte NOP instructions (pre-halfwords, maximum 1000000). After the label,2 *post-halfwords bytes are appended, using the largest NOP like instructions the architecture allows (maximum 1000000).
If both arguments are zero, hotpatching is disabled.
This option can be overridden for individual functions with the "hotpatch" attribute.
๐ Score Options ๐
These options are defined for Score implementations:
-mebโ compile code for big-endian mode. This is the default.-melโ compile code for little-endian mode.-mnhwloopโ disable generation of"bcnz"instructions.-mulsโ enable generation of unaligned load and store instructions.-mmacโ enable the use of multiply-accumulate instructions. Disabled by default.-mscore5โ specify the SCORE5 as the target architecture.-mscore5uโ specify the SCORE5U of the target architecture.-mscore7โ specify the SCORE7 as the target architecture. This is the default.-mscore7dโ specify the SCORE7D as the target architecture.
๐ฆ SH Options ๐ฆ
These -m options are defined for the SH implementations:
-m1โ generate code for the SH1.-m2โ generate code for the SH2.-m2eโ generate code for the SH2e.-m2a-nofpuโ generate code for the SH2a without FPU, or for a SH2a-FPU in such a way that the floating-point unit is not used.-m2a-single-onlyโ generate code for the SH2a-FPU, in such a way that no double-precision floating-point operations are used.-m2a-singleโ generate code for the SH2a-FPU assuming the floating-point unit is in single-precision mode by default.-m2aโ generate code for the SH2a-FPU assuming the floating-point unit is in double-precision mode by default.-m3โ generate code for the SH3.-m3eโ generate code for the SH3e.-m4-nofpuโ generate code for the SH4 without a floating-point unit.-m4-single-onlyโ generate code for the SH4 with a floating-point unit that only supports single-precision arithmetic.-m4-singleโ generate code for the SH4 assuming the floating-point unit is in single-precision mode by default.-m4โ generate code for the SH4.-m4-100โ generate code for SH4-100.-m4-100-nofpuโ generate code for SH4-100 in such a way that the floating-point unit is not used.-m4-100-singleโ generate code for SH4-100 assuming the floating-point unit is in single-precision mode by default.-m4-100-single-onlyโ generate code for SH4-100 in such a way that no double-precision floating-point operations are used.-m4-200โ generate code for SH4-200.-m4-200-nofpuโ generate code for SH4-200 in such a way that the floating-point unit is not used.-m4-200-singleโ generate code for SH4-200 assuming the floating-point unit is in single-precision mode by default.-m4-200-single-onlyโ generate code for SH4-200 in such a way that no double-precision floating-point operations are used.-m4-300โ generate code for SH4-300.-m4-300-nofpuโ generate code for SH4-300 in such a way that the floating-point unit is not used.-m4-300-singleโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-300-single-onlyโ generate code for SH4-300 in such a way that no double-precision floating-point operations are used.-m4-340โ generate code for SH4-340 (no MMU, no FPU).-m4-500โ generate code for SH4-500 (no FPU). Passes-isa=sh4-nofputo the assembler.-m4a-nofpuโ generate code for the SH4al-dsp, or for a SH4a in such a way that the floating-point unit is not used.-m4a-single-onlyโ generate code for the SH4a, in such a way that no double-precision floating-point operations are used.-m4a-singleโ generate code for the SH4a assuming the floating-point unit is in single-precision mode by default.-m4aโ generate code for the SH4a.-m4alโ same as-m4a-nofpu, except that it implicitly passes-dspto the assembler. GCC doesn't generate any DSP instructions at the moment. ๐ซ-mbโ compile code for the processor in big-endian mode.-mlโ compile code for the processor in little-endian mode.-mdalignโ align doubles at 64-bit boundaries. Careful bestie: this changes the calling conventions, so some functions from the standard C library won't work unless you recompile it first with-mdalign.-mrelaxโ shorten some address references at link time, when possible; uses the linker option-relax.-mbigtableโ use 32-bit offsets in"switch"tables. The default is to use 16-bit offsets.-mbitopsโ enable the use of bit manipulation instructions on SH2A.-mfmovdโ enable the use of the instruction"fmovd". Check-mdalignfor alignment constraints.-mrenesasโ comply with the calling conventions defined by Renesas.-mno-renesasโ comply with the calling conventions defined for GCC before the Renesas conventions were available. This option is the default for all targets of the SH toolchain.-mnomacsaveโ mark the"MAC"register as call-clobbered, even if-mrenesasis given.-mieee,-mno-ieeeโ control the IEEE compliance of floating-point comparisons, which affects how cases are handled where the result of a comparison is unordered. By default-mieeeis implicitly enabled. If-ffinite-math-onlyis enabled,-mno-ieeeis implicitly set, which results in faster floating-point greater-equal and less-equal comparisons. The implicit settings can be overridden by specifying either-mieeeor-mno-ieee. โจ-minline-ic_invalidateโ bestie, this one inlines the code that invalidates instruction cache entries after you've set up nested function trampolines. But listen: it does absolutely nothing if-musermodeis in effect and the code-gen option you picked (like-m4) won't let you use the"icbi"instruction. And if your code-gen option doesn't allow"icbi"and-musermodeis not in effect, then the inlined code goes and pokes the instruction cache address array directly with an associative write. Which not only needs privileged mode at run time, but also ๐ fails entirely if the cache line was mapped via the TLB and then got unmapped.-misizeโ dumps the instruction size and location right into the assembly code. Little forensic moment for your asm, we love to see it. ๐-mpadstructโ โ ๏ธ okay this one is deprecated, just so you know. It pads structures to multiples of 4 bytes, which is not compatible with the SH ABI. Not the vibe anymore.-matomic-model=modelโ sets the model of atomic operations, plus extra parameters, all as a comma separated list. Wanna know the deets on the atomic built-in functions? Go look at__atomic Builtins. Here's what's supported:noneโ disables compiler-generated atomic sequences and emits library calls for atomic operations instead. This is the default if the target is notsh*-*-linux*.soft-gusaโ generates GNU/Linux compatible gUSA software atomic sequences for the atomic built-in functions. These sequences need extra support from the system's interrupt/exception handling code, and they're only suitable for SH3* and SH4* single-core systems. On by default when the target issh*-*-linux*and SH3* or SH4*. Oh and when the target is SH4A, this option also partially utilizes the hardware atomic instructionsmovli.landmovco.lto make more efficient code โ unless you specifiedstrict.soft-tcbโ generates software atomic sequences that use a variable in the thread control block. It's a variation on the gUSA sequences that also works on SH1* and SH2* targets. Same deal: needs extra support from the system's interrupt/exception handling code, and only suitable for single-core systems. When you use this model you have to also specify thegbr-offset=parameter, no skipping.soft-imaskโ generates software atomic sequences that temporarily disable interrupts by settingSR.IMASK = 1111. This one only works when the program runs in privileged mode, and it's only suitable for single-core systems. Good news: it does not need extra support from the interrupt/exception handling code. On by default when the target issh*-*-linux*and SH1* or SH2*.hard-llcsโ generates hardware atomic sequences using only themovli.landmovco.linstructions. Only available on SH4A, and it's suitable for multi-core systems. Since the hardware instructions only support 32 bit atomic variables, access to 8 or 16 bit variables is emulated with 32 bit accesses. Code compiled with this is also compatible with other software atomic model interrupt/exception handling systems if you run it on an SH4A system. And this model needs no extra support from the interrupt/exception handling code. โจgbr-offset=โ this parameter sets the offset in bytes of the variable in the thread control block structure that the generated atomic sequences should use, when thesoft-tcbmodel is selected. For any other model this parameter is just ignored. The value you give must be an integer multiple of four, and it has to be in the range 0-1020. ๐ฏstrictโ this parameter stops you from mixing multiple atomic models, even if they're compatible, and makes the compiler generate atomic sequences of the specified model only.
-mtasโ generates the"tas.b"opcode for__atomic_test_and_set. ๐ Heads up though: depending on your particular hardware and software config, this can tank overall performance because of the operand cache line flushes that the"tas.b"instruction implies. And on multi-core SH4A processors,"tas.b"must be used with caution since it can cause data corruption for certain cache configurations. Be careful out there.-mprefergotโ when generating position-independent code, this emits function calls using the Global Offset Table instead of the Procedure Linkage Table. GOT > PLT, in this household at least.-musermode,-mno-usermodeโ don't allow (allow) the compiler to generate privileged mode code. Specifying-musermodealso implies-mno-inline-ic_invalidateif the inlined code wouldn't work in user mode.-musermodeis the default when the target issh*-*-linux*. And if the target is SH1* or SH2*,-musermodehas no effect at all, since there's no user mode to speak of. ๐-multcost=numberโ sets the cost to assume for a multiply insn. Just, like, tell it how expensive a multiply is. ๐ธ-mdiv=strategyโ sets the division strategy for integer division operations. strategy can be one of:call-div1โ calls a library function that uses the single-step division instructiondiv1to do the thing. Division by zero calculates an unspecified result and does not trap. This is the default except for SH4, SH2A and SHcompact.call-fpโ calls a library function that does the operation in double precision floating point. Division by zero causes a floating-point exception. This is the default for SHcompact with FPU. If you specify this for targets that don't have a double precision FPU, it defaults tocall-div1.call-tableโ calls a library function that uses a lookup table for small divisors and thediv1instruction with case distinction for larger divisors. Division by zero calculates an unspecified result and does not trap. This is the default for SH4. If you specify this for targets that don't have dynamic shift instructions, it defaults tocall-div1.
And when you haven't specified a division strategy at all? The default strategy gets picked based on the current target. For SH2A the default strategy is to use the divs and divu instructions instead of library function calls. Slay. ๐
-maccumulate-outgoing-argsโ reserves space once for outgoing arguments in the function prologue, instead of around each call. Generally a win for performance and size. Also needed for unwinding so you don't change the stack frame around conditional code.-mdivsi3_libfunc=nameโ sets the name of the library function used for 32-bit signed division to name. This only affects the name used in the call division strategies, and the compiler still expects the exact same sets of input/output/clobbered registers as if this option weren't even there. Nothing else changes, fr fr.-mfixed-range=register-rangeโ generates code that treats the given register range as fixed registers. A fixed register is one the register allocator can't touch โ super useful when you're compiling kernel code. A register range is specified as two registers separated by a dash, and you can list multiple ranges separated by commas.-mbranch-cost=numโ assumes num to be the cost for a branch instruction. Higher numbers make the compiler try harder to generate branch-free code if it can. If you don't specify it, the value gets picked depending on the processor type you're compiling for.-mzdcbranch,-mno-zdcbranchโ assume (do not assume) that zero displacement conditional branch instructionsbtandbfare fast. If you say-mzdcbranch, the compiler prefers zero displacement branch code sequences. Enabled by default when generating code for SH4 and SH4A. You can explicitly turn it off with-mno-zdcbranch.-mcbranch-force-delay-slotโ forces the usage of delay slots for conditional branches, which just stuffs the delay slot with anopif no suitable instruction can be found. Disabled by default. You can enable it to work around hardware bugs like the ones found in the original SH7055. Classic hardware being messy. ๐ญ-mfused-madd,-mno-fused-maddโ generate code that uses (does not use) the floating-point multiply and accumulate instructions. These get generated by default if hardware floating point is used. Lowkey important note: the machine-dependent-mfused-maddoption is now mapped to the machine-independent-ffp-contract=fastoption, and-mno-fused-maddis mapped to-ffp-contract=off.-mfsca,-mno-fscaโ allow or disallow the compiler to emit thefscainstruction for sine and cosine approximations. The-mfscaoption must be used together with-funsafe-math-optimizations. Enabled by default when generating code for SH4A. Using-mno-fscadisables sine and cosine approximations even if-funsafe-math-optimizationsis in effect. โจ-mfsrra,-mno-fsrraโ allow or disallow the compiler to emit thefsrrainstruction for reciprocal square root approximations. The-mfsrraoption must be used together with-funsafe-math-optimizationsand-ffinite-math-only. Enabled by default when generating code for SH4A. Using-mno-fsrradisables reciprocal square root approximations even if-funsafe-math-optimizationsand-ffinite-math-onlyare both in effect.-mpretend-cmoveโ prefers zero-displacement conditional branches for conditional move instruction patterns. This can give you faster code on the SH4 processor. ๐-mfdpicโ generates code using the FDPIC ABI.
โจ Solaris 2 Options โจ
These -m options are supported on Solaris 2, bestie:
-mclear-hwcapโ-mclear-hwcaptells the compiler to remove the hardware capabilities generated by the Solaris assembler. This is only necessary when object files use ISA extensions that aren't supported by the current machine, but they check at runtime whether or not to use them.-mimpure-textโ-mimpure-text, used in addition to-shared, tells the compiler not to pass-z textto the linker when linking a shared object. Using this option, you can link position-dependent code into a shared object. ๐ซถ-mimpure-textโ this one suppresses that whole "relocations remain against allocatable but non-writable sections" linker error message. But bestie, listen. The relocations it needs trigger copy-on-write, so the shared object is not actually shared across processes anymore. ๐ญ Instead of reaching for-mimpure-text, you should compile all your source code with-fpicor-fPIC. That's the move. periodt.
On Solaris 2 you also get these switches on top of everything above, bestie:
-pthreadsโ it's literally just a synonym for-pthread. same vibe, different name ๐
SPARC Options โจ๐
These -m options are supported on the SPARC, and there are so many of them, buckle up:
-mno-app-regs,-mapp-regsโ pass-mapp-regsand GCC generates output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications. Just like global register 1, each of global registers 2 through 4 then gets treated as an allocable register that's clobbered by function calls. This is the default.
If you want to be fully SVR4 ABI-compliant and you're willing to eat some performance loss, pass -mno-app-regs instead. You should compile libraries and system software with this option. ๐
-mflat,-mno-flatโ with-mflat, the compiler doesn't generate save/restore instructions and instead uses a "flat" or single register window model. This model is compatible with the regular register window model. The local registers and the input registers (0--5) are still treated as "call-saved" registers and get saved on the stack as needed.
With -mno-flat (the default), the compiler generates save/restore instructions (except for leaf functions). This is the normal operating mode. ๐
-mfpu,-mhard-floatโ generate output containing floating-point instructions. This is the default. ๐ฅ-mno-fpu,-msoft-floatโ generate output containing library calls for floating point.
โ ๏ธ Warning: the requisite libraries are not available for all SPARC targets. Normally the facilities of the machine's usual C compiler are used, but this cannot be done directly in cross-compilation. You must make your own arrangements to provide suitable library functions for cross-compilation. The embedded targetssparc-*-aoutandsparclite-*-*do provide software floating-point support.
-msoft-float changes the calling convention in the output file, so it's only useful if you compile all of a program with this option. In particular, you need to compile libgcc.a, the library that comes with GCC, with -msoft-float in order for this to work. no skips, bestie. ๐
-mhard-quad-floatโ generate output containing quad-word (long double) floating-point instructions.-msoft-quad-floatโ generate output containing library calls for quad-word (long double) floating-point instructions. The functions called are those specified in the SPARC ABI. This is the default.
As of this writing, there are no SPARC implementations that have hardware support for the quad-word floating-point instructions. They all invoke a trap handler for one of these instructions, and then the trap handler emulates the effect of the instruction. Because of the trap handler overhead, this is much slower than calling the ABI library routines. Thus the -msoft-quad-float option is the default. ๐
-mno-unaligned-doubles,-munaligned-doublesโ assume that doubles have 8-byte alignment. This is the default.
With -munaligned-doubles, GCC assumes that doubles have 8-byte alignment only if they are contained in another type, or if they have an absolute address. Otherwise, it assumes they have 4-byte alignment. Specifying this option avoids some rare compatibility problems with code generated by other compilers. It is not the default because it results in a performance loss, especially for floating-point code. ๐ญ
-muser-mode,-mno-user-modeโ do not generate code that can only run in supervisor mode. This is relevant only for the"casa"instruction emitted for the LEON3 processor. This is the default.-mfaster-structs,-mno-faster-structsโ with-mfaster-structs, the compiler assumes that structures should have 8-byte alignment. This enables the use of pairs of"ldd"and"std"instructions for copies in structure assignment, in place of twice as many"ld"and"st"pairs. However, the use of this changed alignment directly violates the SPARC ABI. ๐ฑ So it's intended only for use on targets where the developer acknowledges that their resulting code is not directly in line with the rules of the ABI. you've been warned, bestie.-mstd-struct-return,-mno-std-struct-returnโ with-mstd-struct-return, the compiler generates checking code in functions returning structures or unions to detect size mismatches between the two sides of function calls, as per the 32-bit ABI.
The default is -mno-std-struct-return. This option has no effect in 64-bit mode.
-mlra,-mno-lraโ enable Local Register Allocation. This is the default for SPARC since GCC 7, so-mno-lraneeds to be passed to get old Reload. throwback vibes fr fr ๐ง-mcpu=cpu_typeโ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type arev7,cypress,v8,supersparc,hypersparc,leon,leon3,leon3v7,leon5,sparclite,f930,f934,sparclite86x,sparclet,tsc701,v9,ultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7andm8. โจ
Native Solaris and GNU/Linux toolchains also support the value native, which selects the best architecture option for the host processor. -mcpu=native has no effect if GCC does not recognize the processor. ๐
Default instruction scheduling parameters are used for values that select an architecture and not an implementation. These are v7, v8, sparclite, sparclet, v9.
Here is a list of each supported architecture and their supported implementations:
v7โcypress,leon3v7v8โsupersparc,hypersparc,leon,leon3,leon5sparcliteโf930,f934,sparclite86xsparcletโtsc701v9โultrasparc,ultrasparc3,niagara,niagara2,niagara3,niagara4,niagara7,m8
By default (unless configured otherwise), GCC generates code for the V7 variant of the SPARC architecture. With -mcpu=cypress, the compiler additionally optimizes it for the Cypress CY7C602 chip, as used in the SPARCStation/SPARCServer 3xx series. This is also appropriate for the older SPARCStation 1, 2, IPX etc.
With -mcpu=v8, GCC generates code for the V8 variant of the SPARC architecture. The only difference from V7 code is that the compiler emits the integer multiply and integer divide instructions which exist in SPARC-V8 but not in SPARC-V7. With -mcpu=supersparc, the compiler additionally optimizes it for the SuperSPARC chip, as used in the SPARCStation 10, 1000 and 2000 series.
With -mcpu=sparclite, GCC generates code for the SPARClite variant of the SPARC architecture. This adds the integer multiply, integer divide step and scan ("ffs") instructions which exist in SPARClite but not in SPARC-V7. With -mcpu=f930, the compiler additionally optimizes it for the Fujitsu MB86930 chip, which is the original SPARClite, with no FPU. With -mcpu=f934, the compiler additionally optimizes it for the Fujitsu MB86934 chip, which is the more recent SPARClite with FPU.
With -mcpu=sparclet, GCC generates code for the SPARClet variant of the SPARC architecture. This adds the integer multiply, multiply/accumulate, integer divide step and scan ("ffs") instructions which exist in SPARClet but not in SPARC-V7. With -mcpu=tsc701, the compiler additionally optimizes it for the TEMIC SPARClet chip.
With -mcpu=v9, GCC generates code for the V9 variant of the SPARC architecture. This adds 64-bit integer and floating-point move instructions, 3 additional floating-point condition code registers and conditional move instructions. With -mcpu=ultrasparc, the compiler additionally optimizes it for the Sun UltraSPARC I/II/IIi chips. With -mcpu=ultrasparc3, the compiler additionally optimizes it for the Sun UltraSPARC III/III+/IIIi/IIIi+/IV/IV+ chips. With -mcpu=niagara, the compiler additionally optimizes it for Sun UltraSPARC T1 chips. With -mcpu=niagara2, the compiler additionally optimizes it for Sun UltraSPARC T2 chips. With -mcpu=niagara3, the compiler additionally optimizes it for Sun UltraSPARC T3 chips. With -mcpu=niagara4, the compiler additionally optimizes it for Sun UltraSPARC T4 chips. With -mcpu=niagara7, the compiler additionally optimizes it for Oracle SPARC M7 chips. With -mcpu=m8, the compiler additionally optimizes it for Oracle M8 chips. ๐
-mtune=cpu_typeโ set the instruction scheduling parameters for machine type cpu_type, but do not set the instruction set or register set that the option-mcpu=cpu_typedoes.
The same values for -mcpu=cpu_type can be used for -mtune=cpu_type, but the only useful values are those that select a particular CPU implementation. Those are cypress, supersparc, hypersparc, leon, leon3, leon3v7, leon5, f930, f934, sparclite86x, tsc701, ultrasparc, ultrasparc3, niagara, niagara2, niagara3, niagara4, niagara7 and m8. With native Solaris and GNU/Linux toolchains, native can also be used. ๐
-mv8plus,-mno-v8plusโ with-mv8plus, GCC generates code for the SPARC-V8+ ABI. The difference from the V8 ABI is that the global and out registers are considered 64 bits wide. This is enabled by default on Solaris in 32-bit mode for all SPARC-V9 processors.-mvis,-mno-visโ with-mvis, GCC generates code that takes advantage of the UltraSPARC Visual Instruction Set extensions. The default is-mno-vis.-mvis2,-mno-vis2โ with-mvis2, GCC generates code that takes advantage of version 2.0 of the UltraSPARC Visual Instruction Set extensions. The default is-mvis2when targeting a cpu that supports such instructions, such as UltraSPARC-III and later. Setting-mvis2also sets-mvis. ๐ซถ-mvis3,-mno-vis3โ with-mvis3, GCC generates code that takes advantage of version 3.0 of the UltraSPARC Visual Instruction Set extensions. The default is-mvis3when targeting a cpu that supports such instructions, such asniagara-3and later. Setting-mvis3also sets-mvis2and-mvis. โจ-mvis4,-mno-vis4โ with-mvis4, GCC spits out code that eats up version 4.0 of the UltraSPARC Visual Instruction Set extensions. default is-mvis4when you're targeting a cpu that supports that kind of thing, likeniagara-7and later. and turning on-mvis4also turns on-mvis3,-mvis2and-mvis, bestie, it's a whole bundle ๐ซ-mvis4b,-mno-vis4bโ with-mvis4b, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions, plus the extra VIS instructions that showed up in the Oracle SPARC Architecture 2017. default is-mvis4bwhen targeting a cpu that supports those, likem8and later. setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvis. it's giving overachiever and we love that for it ๐-mcbcond,-mno-cbcondโ with-mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. default is-mcbcondwhen targeting a CPU that supports such instructions, such asNiagara-4and later. โจ-mfmaf,-mno-fmafโ with-mfmaf, GCC generates code that takes advantage of the UltraSPARC Fused Multiply-Add Floating-point instructions. default is-mfmafwhen targeting a CPU that supports such instructions, such asNiagara-3and later. ๐งฎ-mfsmuld,-mno-fsmuldโ with-mfsmuld, GCC generates code that takes advantage of the Floating-point Multiply Single to Double (FsMULd) instruction. default is-mfsmuldwhen targeting a CPU supporting the architecture versions V8 or V9 with FPU โ except-mcpu=leon, that one's the exception fr fr. ๐-mpopc,-mno-popcโ with-mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. default is-mpopcwhen targeting a CPU that supports such an instruction, such asNiagara-2and later. ๐ฅ-msubxc,-mno-subxcโ with-msubxc, GCC generates code that takes advantage of the UltraSPARC Subtract-Extended-with-Carry instruction. default is-msubxcwhen targeting a CPU that supports such an instruction, such asNiagara-7and later. ๐-mfix-at697fโ enable the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). it's a lil bug patch, iconic behavior honestly ๐ฉน-mfix-ut699โ enable the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.-mfix-ut700โ enable the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ enable the documented workaround for the back-to-back store errata of the GR712RC processor.
these -m options are supported in addition to the above on SPARC-V9 processors in 64-bit environments:
-m32,-m64โ generate code for a 32-bit or 64-bit environment. the 32-bit environment setsint,longand pointer to 32 bits. the 64-bit environment setsintto 32 bits andlongand pointer to 64 bits. ๐ซถ-mcmodel=whichโ set the code model to one of:medlowโ the Medium/Low code model: 64-bit addresses, programs must be linked in the low 32 bits of memory. programs can be statically or dynamically linked.medmidโ the Medium/Middle code model: 64-bit addresses, programs must be linked in the low 44 bits of memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.medanyโ the Medium/Anywhere code model: 64-bit addresses, programs may be linked anywhere in memory, the text and data segments must be less than 2GB in size and the data segment must be located within 2GB of the text segment.embmedanyโ the Medium/Anywhere code model for embedded systems: 64-bit addresses, the text and data segments must be less than 2GB in size, both starting anywhere in memory (determined at link time). the global register%g4points to the base of the data segment. programs are statically linked and PIC is not supported. no PIC bestie, she said no ๐
-mmemory-model=mem-modelโ set the memory model in force on the processor to one of:defaultโ the default memory model for the processor and operating system.rmoโ Relaxed Memory Orderpsoโ Partial Store Ordertsoโ Total Store Orderscโ Sequential Consistency
these memory models are formally defined in Appendix D of the SPARC-V9 architecture manual, as set in the processor's "PSTATE.MM" field. โจ
-mstack-bias,-mno-stack-biasโ with-mstack-bias, GCC assumes that the stack pointer, and frame pointer if present, are offset by-2047which must be added back when making stack frame references. this is the default in 64-bit mode. otherwise, assume no such offset is present. ๐
๐๏ธ Options for System V ๐๏ธ
these additional options are available on System V Release 4 for compatibility with other compilers on those systems:
-Gโ create a shared object. it is recommended that-symbolicor-sharedbe used instead. > ok so it still works but like... the girls are saying use-symbolicor-shared, periodt ๐-Qyโ identify the versions of each tool used by the compiler, in a".ident"assembler directive in the output.-Qnโ refrain from adding".ident"directives to the output file (this is the default). she's lowkey the chill one ๐ธ-YP,dirsโ search the directories dirs, and no others, for libraries specified with-l. no others. not one. ๐ค-Ym,dirโ look in the directory dir to find the M4 preprocessor. the assembler uses this option.
๐ TILE-Gx Options ๐
these -m options are supported on the TILE-Gx:
-mcmodel=smallโ generate code for the small model. the distance for direct calls is limited to500Min either direction. PC-relative addresses are 32 bits. absolute addresses support the full address range.-mcmodel=largeโ generate code for the large model. there is no limitation on call distance, pc-relative addresses, or absolute addresses. go anywhere, do anything, main character energy ๐-mcpu=nameโ selects the type of CPU to be targeted. currently the only supported type istilegx.-m32,-m64โ generate code for a 32-bit or 64-bit environment. the 32-bit environment setsint,long, and pointer to 32 bits. the 64-bit environment setsintto 32 bits andlongand pointer to 64 bits.-mbig-endian,-mlittle-endianโ generate code in big/little endian mode, respectively. ๐ฆ
๐ง TILEPro Options ๐ง
these -m options are supported on the TILEPro:
-mcpu=nameโ selects the type of CPU to be targeted. currently the only supported type istilepro.-m32โ generate code for a 32-bit environment, which setsint,long, and pointer to 32 bits. this is the only supported behavior so the flag is essentially ignored. > not me passing a flag that literally does nothing ๐ญ it's just there for the vibes
โญ V850 Options โญ
these -m options are defined for V850 implementations:
-mlong-calls,-mno-long-callsโ treat all calls as being far away (near). if calls are assumed to be far away, the compiler always loads the function's address into a register, and calls indirect through the pointer. ๐ฐ๏ธ-mno-ep,-mepโ do not optimize (do optimize) basic blocks that use the same index pointer 4 or more times to copy pointer into the"ep"register, and use the shorter"sld"and"sst"instructions. the-mepoption is on by default if you optimize.-mno-prolog-function,-mprolog-functionโ do not use (do use) external functions to save and restore registers at the prologue and epilogue of a function. the external functions are slower, but use less code space if more than one function saves the same number of registers. the-mprolog-functionoption is on by default if you optimize. slower but smaller, a tradeoff queen ๐-mspaceโ try to make the code as small as possible. at present, this just turns on the-mepand-mprolog-functionoptions.-mtda=nโ put static or global variables whose size is n bytes or less into the tiny data area that register"ep"points to. the tiny data area can hold up to256bytes in total (128bytes for byte references). tiny but mighty ๐-msda=nโ put static or global variables whose size is n bytes or less into the small data area that register"gp"points to. the small data area can hold up to64kilobytes.-mzda=nโ put static or global variables whose size is n bytes or less into the first32kilobytes of memory.-mv850โ specify that the target processor is the V850.-mv850e3v5โ specify that the target processor is the V850E3V5. the preprocessor constant"__v850e3v5__"is defined if this option is used.-mv850e2v4โ specify that the target processor is the V850E3V5. this is an alias for the-mv850e3v5option. > yeah bestie, they said V850E3V5 twice, it's an alias, don't @ me ๐-mv850e2v3โ specify that the target processor is the V850E2V3. the preprocessor constant"__v850e2v3__"is defined if this option is used.-mv850e2โ specify that the target processor is the V850E2. the preprocessor constant"__v850e2__"is defined if this option is used.-mv850e1โ specify that the target processor is the V850E1. the preprocessor constants"__v850e1__"and"__v850e__"are defined if this option is used.-mv850esโ specify that the target processor is the V850ES. this is an alias for the-mv850e1option.-mv850eโ specify that the target processor is the V850E. the preprocessor constant"__v850e__"is defined if this option is used.
if neither -mv850 nor -mv850e nor -mv850e1 nor -mv850e2 nor -mv850e2v3 nor -mv850e3v5 are defined then a default target processor is chosen and the relevant __v850*__ preprocessor constant is defined. ๐
the preprocessor constants "__v850" and "__v851__" are always defined, regardless of which processor variant is the target. always. no matter what. ride or die ๐ซถ
-mdisable-callt,-mno-disable-calltโ this option suppresses generation of the"CALLT"instruction for the v850e, v850e1, v850e2, v850e2v3 and v850e3v5 flavors of the v850 architecture.
this option is enabled by default when the RH850 ABI is in use (see -mrh850-abi), and disabled by default when the GCC ABI is in use. if "CALLT" instructions are being generated then the C preprocessor symbol "__V850_CALLT__" is defined.
-mrelax,-mno-relaxโ pass on (or do not pass on) the-mrelaxcommand-line option to the assembler. just passing the message along, she's a middleman โจ-mlong-jumps,-mno-long-jumpsโ disable (or re-enable) the generation of PC-relative jump instructions.-msoft-float,-mhard-floatโ turn OFF (or turn back ON) the generation of hardware floating point instructions ๐ this one only actually matters when the target architecture is V850E2V3 or higher, no cap. When hardware floating point instructions are being generated, the C preprocessor symbol__FPU_OK__gets defined โ otherwise the symbol__NO_FPU__is the one that shows up ๐ซถ-mloopโ enables use of the e3v5 LOOP instruction โจ heads up bestie, this is not enabled by default when the e3v5 architecture is selected, because using it is still experimental ๐-mrh850-abi,-mghsโ enables support for the RH850 version of the V850 ABI. This one is the default ๐ with this version of the ABI, these are the rules:- Integer sized structures and unions are returned via a memory pointer rather than a register.
- Large structures and unions (more than 8 bytes in size) are passed by value.
- Functions are aligned to 16-bit boundaries.
- The
-m8byte-aligncommand-line option is supported. - The
-mdisable-calltcommand-line option is enabled by default. The-mno-disable-calltcommand-line option is not supported.
When this version of the ABI is enabled, the C preprocessor symbol __V850_RH850_ABI__ is defined ๐
-mgcc-abiโ enables support for the old GCC version of the V850 ABI ๐ with this version of the ABI, the rules go like this:- Integer sized structures and unions are returned in register
r10. - Large structures and unions (more than 8 bytes in size) are passed by reference.
- Functions are aligned to 32-bit boundaries, unless optimizing for size.
- The
-m8byte-aligncommand-line option is not supported. - The
-mdisable-calltcommand-line option is supported but not enabled by default.
- Integer sized structures and unions are returned in register
When this version of the ABI is enabled, the C preprocessor symbol __V850_GCC_ABI__ is defined ๐
-m8byte-align,-mno-8byte-alignโ enables support fordoubleandlong longtypes to be aligned on 8-byte boundaries โจ the default is to restrict the alignment of all objects to at most 4-bytes. When-m8byte-alignis in effect, the C preprocessor symbol__V850_8BYTE_ALIGN__is defined ๐ธ-mbig-switchโ generate code suitable for big switch tables ๐ซถ only use this option if the assembler/linker complain about out of range branches within a switch table, okay?-mapp-regsโ this option causes r2 and r5 to be used in the code generated by the compiler. This setting is the default ๐-mno-app-regsโ this option causes r2 and r5 to be treated as fixed registers ๐
๐ VAX Options ๐
These -m options are defined for the VAX:
-munixโ do not output certain jump instructions (aobleqand so on) that the Unix assembler for the VAX cannot handle across long ranges ๐-mgnuโ do output those jump instructions, on the assumption that the GNU assembler is being used โจ-mgโ output code for G-format floating-point numbers instead of D-format.-mlra,-mno-lraโ enable Local Register Allocation ๐ฅ this is still experimental for the VAX, so by default the compiler uses standard reload.
๐ฆ Visium Options ๐ฆ
-mdebugโ a program which performs file I/O and is destined to run on an MCM target should be linked with this option. It causes the librarieslibc.aandlibdebug.ato be linked. The program should be run on the target under the control of the GDB remote debugging stub ๐-msimโ a program which performs file I/O and is destined to run on the simulator should be linked with option. This causes librarieslibc.aandlibsim.ato be linked.-mfpu,-mhard-floatโ generate code containing floating-point instructions. This is the default ๐-mno-fpu,-msoft-floatโ generate code containing library calls for floating-point.
okay so-msoft-floatchanges the calling convention in the output file ๐ therefore, it is only useful if you compile all of a program with this option. In particular, you need to compilelibgcc.a, the library that comes with GCC, with-msoft-floatin order for this to work.
- *
-mcpu=cpu_type* โ set the instruction set, register set, and instruction scheduling parameters for machine type cpu_type. Supported values for cpu_type aremcm,gr5andgr6โจ
mcm is a synonym of gr5 present for backward compatibility ๐ซถ
By default (unless configured otherwise), GCC generates code for the GR5 variant of the Visium architecture.
With -mcpu=gr6, GCC generates code for the GR6 variant of the Visium architecture. The only difference from GR5 code is that the compiler will generate block move instructions ๐
-mtune=cpu_type โ set the instruction scheduling parameters for machine type cpu_type, but do *not set the instruction set or register set that the option-mcpu=cpu_type* would.-msv-modeโ generate code for the supervisor mode, where there are no restrictions on the access to general registers. This is the default ๐-muser-modeโ generate code for the user mode, where the access to some general registers is forbidden: on the GR5, registersr24tor31cannot be accessed in this mode; on the GR6, only registersr29tor31are affected ๐ซถ
๐ VMS Options ๐
These -m options are defined for the VMS implementations:
-mvms-return-codesโ return VMS condition codes frommain. The default is to return POSIX-style condition (e.g. error) codes.- *
-mdebug-main=prefix* โ flag the first routine whose name starts with prefix as the main routine for the debugger โจ -mmalloc64โ default to 64-bit memory allocation routines.- *
-mpointer-size=size* โ set the default size of pointers. Possible options for size are32orshortfor 32 bit pointers,64orlongfor 64 bit pointers, andnofor supporting only 32 bit pointers. The later option disablespragma pointer_size๐
๐ธ VxWorks Options ๐ธ
The options in this section are defined for all VxWorks targets. Options specific to the target hardware are listed with the other options for that target ๐ซถ
-mrtpโ GCC can generate code for both VxWorks kernels and real time processes (RTPs). This option switches from the former to the latter. It also defines the preprocessor macro__RTP__โจ-non-staticโ link an RTP executable against shared libraries rather than static libraries. The options-staticand-sharedcan also be used for RTPs;-staticis the default.-Bstatic,-Bdynamicโ these options are passed down to the linker. They are defined for compatibility with Diab ๐-Xbind-lazyโ enable lazy binding of function calls. This option is equivalent to-Wl,-z,nowand is defined for compatibility with Diab.-Xbind-nowโ disable lazy binding of function calls. This option is the default and is defined for compatibility with Diab ๐
๐ฅ x86 Options ๐ฅ
These -m options are defined for the x86 family of computers:
- *
-march=cpu-type* โ generate instructions for the machine type cpu-type. In contrast to-mtune=cpu-type, which merely tunes the generated code for the specified cpu-type,-march=cpu-type allows GCC to generate code that may not run at all on processors other than the one indicated ๐ specifying-march=cpu-type implies-mtune=cpu-type, except where noted otherwise.
The choices for cpu-type are:
nativeโ this selects the CPU to generate code for at compilation time by determining the processor type of the compiling machine. Using-march=nativeenables all instruction subsets supported by the local machine (hence the result might not run on different machines). Using-mtune=nativeproduces code optimized for the local machine under the constraints of the selected instruction set โจx86-64โ a generic CPU with 64-bit extensions.x86-64-v2x86-64-v3x86-64-v4โ these choices for cpu-type select the corresponding micro-architecture level from the x86-64 psABI. On ABIs other than the x86-64 psABI they select the same CPU features as the x86-64 psABI documents for the particular micro-architecture level.
Since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. Specific tuning can be enabled using the -mtune=other-cpu-type option with an appropriate other-cpu-type value ๐ซถ
i386โ original Intel i386 CPU.i486โ Intel i486 CPU. (No scheduling is implemented for this chip.)i586pentiumโ Intel Pentium CPU with no MMX support.lakemontโ Intel Lakemont MCU, based on Intel Pentium CPU.pentium-mmxโ Intel Pentium MMX CPU, based on Pentium core with MMX instruction set support.pentiumproโ Intel Pentium Pro CPU.i686โ when used with-march, the Pentium Pro instruction set is used, so the code runs on all i686 family chips. When used with-mtune, it has the same meaning asgeneric.pentium2โ Intel Pentium II CPU, based on Pentium Pro core with MMX and FXSR instruction set support.pentium3pentium3mโ Intel Pentium III CPU, based on Pentium Pro core with MMX, FXSR and SSE instruction set support.pentium-mโ Intel Pentium M; low-power version of Intel Pentium III CPU with MMX, SSE, SSE2 and FXSR instruction set support. Used by Centrino notebooks ๐pentium4pentium4mโ Intel Pentium 4 CPU with MMX, SSE, SSE2 and FXSR instruction set support.prescottโ improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2, SSE3 and FXSR instruction set support.noconaโ improved version of Intel Pentium 4 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3 and FXSR instruction set support.core2โ Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, CX16, SAHF and FXSR instruction set support.nehalemโ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF and FXSR instruction set support ๐ฅ
westmereโ Intel Westmere CPU, and yes she's got 64-bit extensions plus MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR and PCLMUL instruction set support. โจsandybridgeโ Intel Sandy Bridge CPU, 64-bit extensions on deck with MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE and PCLMUL instruction set support. She's giving upgraded.ivybridgeโ Intel Ivy Bridge CPU, 64-bit extensions and MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND and F16C instruction set support. ๐ฆhaswellโ Intel Haswell CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE and HLE instruction set support. That list is long bestie, and she earned every single one.broadwellโ Intel Broadwell CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX and PREFETCHW instruction set support. ๐skylakeโ Intel Skylake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES and SGX instruction set support. Periodt.bonnellโ Intel Bonnell CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. Short and sweet, we love a minimal queen. ๐silvermontโ Intel Silvermont CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW and RDRND instruction set support.goldmontโ Intel Goldmont CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT and FSGSBASE instruction set support. โจgoldmont-plusโ Intel Goldmont Plus CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID and SGX instruction set support. She's the "plus" for a reason, no cap.tremontโ Intel Tremont CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, PCLMUL, PREFETCHW, RDRND, AES, SHA, RDSEED, XSAVE, XSAVEC, XSAVES, XSAVEOPT, CLFLUSHOPT, FSGSBASE, PTWRITE, RDPID, SGX, CLWB, GFNI-SSE, MOVDIRI, MOVDIR64B, CLDEMOTE and WAITPKG instruction set support. ๐knlโ Intel Knight's Landing CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1 instruction set support. Xeon Phi girlies rise up ๐knmโ Intel Knights Mill CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AVX512PF, AVX512ER, AVX512F, AVX512CD and PREFETCHWT1, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support. ๐skylake-avx512โ Intel Skylake Server CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support.cannonlakeโ Intel Cannonlake Server CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA and SHA instruction set support.icelake-clientโ Intel Icelake Client CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. ๐ง (yes the space before that comma is real, we don't edit the source bestie)icelake-serverโ Intel Icelake Server CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2 , VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD and CLWB instruction set support.cascadelakeโ Intel Cascadelake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support.cooperlakeโ Intel cooperlake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.tigerlakeโ Intel Tigerlake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, MOVDIRI, MOVDIR64B, CLWB, AVX512VP2INTERSECT and KEYLOCKER instruction set support. ๐ฏ main character energy fr frsapphirerapidsโ Intel sapphirerapids CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, SGX, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID, AVX512VPOPCNTDQ, PCONFIG, WBNOINVD, CLWB, MOVDIRI, MOVDIR64B, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI, AVX512-FP16 and AVX512BF16 instruction set support. ๐ the gem of the lineup, literally.alderlakeโ Intel Alderlake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE, WAITPKG, ADCX, AVX, AVX2, BMI, BMI2, F16C, FMA, LZCNT, PCONFIG, PKU, VAES, VPCLMULQDQ, SERIALIZE, HRESET, KL, WIDEKL and AVX-VNNI instruction set support.rocketlakeโ Intel Rocketlake CPU, 64-bit extensions and MOVBE, MMX, SSE, SSE2, SSE3, SSSE3 , SSE4.1, SSE4.2, POPCNT, CX16, SAHF, FXSR, AVX, XSAVE, PCLMUL, FSGSBASE, RDRND, F16C, AVX2, BMI, BMI2, LZCNT, FMA, MOVBE, HLE, RDSEED, ADCX, PREFETCHW, AES, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD PKU, AVX512VBMI, AVX512IFMA, SHA, AVX512VNNI, GFNI, VAES, AVX512VBMI2, VPCLMULQDQ, AVX512BITALG, RDPID and AVX512VPOPCNTDQ instruction set support. ๐ (and yeah, that stray space afterSSSE3and the missing comma beforePKUare exactly how she comes, we don't touch it)
And now we're switching teams to AMD, bestie. ๐
k6โ AMD K6 CPU, rocking MMX instruction set support.k6-2,k6-3โ improved versions of the AMD K6 CPU, with MMX and 3DNow! instruction set support. Glow up era โจathlon,athlon-tbirdโ AMD Athlon CPU, with MMX, 3dNOW!, enhanced 3DNow! and SSE prefetch instructions support.athlon-4,athlon-xp,athlon-mpโ improved AMD Athlon CPU, with MMX, 3DNow!, enhanced 3DNow! and full SSE instruction set support. Full set, no half measures. ๐k8,opteron,athlon64,athlon-fxโ processors based on the AMD K8 core, with x86-64 instruction set support, including the AMD Opteron, Athlon 64, and Athlon 64 FX processors. (This supersets MMX, SSE, SSE2, 3DNow!, enhanced 3DNow! and 64-bit instruction set extensions.) The 64-bit glow up we were all waiting for ๐k8-sse3,opteron-sse3,athlon64-sse3โ improved versions of AMD K8 cores, now with SSE3 instruction set support. She got the upgrade, bestie.amdfam10,barcelonaโ CPUs based on AMD Family 10h cores, with x86-64 instruction set support. (This supersets MMX, SSE, SSE2, SSE3, SSE4A, 3DNow!, enhanced 3DNow!, ABM and 64-bit instruction set extensions.)bdver1โ CPUs based on AMD Family 15h cores, with x86-64 instruction set support. (This supersets FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.) ๐ฅbdver2โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.) it's giving maximum features fr โจbdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, XOP, LWP, AES, PCLMUL, CX16, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.) FSGSBASE joined the party ๐bdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, TBM, F16C, FMA, FMA4, FSGSBASE, AVX, AVX2, XOP, LWP, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM and 64-bit instruction set extensions.) BMI2 AND AVX2 bestie we're so backznver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, and 64-bit instruction set extensions.) Ryzen era entered the chat ๐znver2โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, and 64-bit instruction set extensions.) CLWB, RDPID, WBNOINVD โ say it with me now ๐znver3โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, PKU, VPCLMULQDQ, VAES, and 64-bit instruction set extensions.) PKU + VPCLMULQDQ + VAES, obsessed ๐ญznver4โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersets BMI, BMI2, CLWB, F16C, FMA, FSGSBASE, AVX, AVX2, ADCX, RDSEED, MWAITX, SHA, CLZERO, AES, PCLMUL, CX16, MOVBE, MMX, SSE, SSE2, SSE3, SSE4A, SSSE3, SSE4.1, SSE4.2, ABM, XSAVEC, XSAVES, CLFLUSHOPT, POPCNT, RDPID, WBNOINVD, PKU, VPCLMULQDQ, VAES, AVX512F, AVX512DQ, AVX512IFMA, AVX512CD, AVX512BW, AVX512VL, AVX512BF16, AVX512VBMI, AVX512VBMI2, AVX512VNNI, AVX512BITALG, AVX512VPOPCNTDQ, GFNI and 64-bit instruction set extensions.) the entire AVX-512 alphabet like?? main character energy periodt ๐btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (This supersets MMX, SSE, SSE2, SSE3, SSSE3, SSE4A, CX16, ABM and 64-bit instruction set extensions.)btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includes MOVBE, F16C, BMI, AVX, PCLMUL, AES, SSE4.2, SSE4.1, CX16, ABM, SSE4A, SSSE3, SSE3, SSE2, SSE, MMX and 64-bit instruction set extensions.winchip-c6โ IDT WinChip C6 CPU, dealt in same way as i486 with additional MMX instruction set support. a lil retro moment ๐winchip2โ IDT WinChip 2 CPU, dealt in same way as i486 with additional MMX and 3DNow! instruction set support.c3โ VIA C3 CPU with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.) ngl no scheduling, we just vibingc3-2โ VIA C3-2 (Nehemiah/C5XL) CPU with MMX and SSE instruction set support. (No scheduling is implemented for this chip.)c7โ VIA C7 (Esther) CPU with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)samuel-2โ VIA Eden Samuel 2 CPU with MMX and 3DNow! instruction set support. (No scheduling is implemented for this chip.)nehemiahโ VIA Eden Nehemiah CPU with MMX and SSE instruction set support. (No scheduling is implemented for this chip.)estherโ VIA Eden Esther CPU with MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)eden-x2โ VIA Eden X2 CPU with x86-64, MMX, SSE, SSE2 and SSE3 instruction set support. (No scheduling is implemented for this chip.)eden-x4โ VIA Eden X4 CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, AVX and AVX2 instruction set support. (No scheduling is implemented for this chip.)nanoโ Generic VIA Nano CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-1000โ VIA Nano 1xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-2000โ VIA Nano 2xxx CPU with x86-64, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support. (No scheduling is implemented for this chip.)nano-3000โ VIA Nano 3xxx CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)nano-x2โ VIA Nano Dual Core CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)nano-x4โ VIA Nano Quad Core CPU with x86-64, MMX, SSE, SSE2, SSE3, SSSE3 and SSE4.1 instruction set support. (No scheduling is implemented for this chip.)geodeโ AMD Geode embedded processor with MMX and 3DNow! instruction set support. embedded bestie, tiny but fierce ๐ฆ
-mtune=cpu-typeโ tune everything applicable about the generated code to cpu-type, except for the ABI and the set of available instructions. So like, picking a specific cpu-type schedules things appropriately for that particular chip, but the compiler does not generate any code that can't run on the default machine type โ unless you also pass a-march=cpu-typeoption. Example bestie: if GCC is configured fori686-pc-linux-gnuthen-mtune=pentium4generates code that is tuned for Pentium 4 but still runs on i686 machines. tuned for the vibe, compatible with the room โจ
The choices for cpu-type are the same as for -march. In addition, -mtune supports 2 extra choices for cpu-type:
genericโ Produce code optimized for the most common IA32/AMD64/EM64T processors. If you know the CPU on which your code will run, then you should use the corresponding-mtuneor-marchoption instead of-mtune=generic. But, if you do not know exactly what CPU users of your application will have, then you should use this option. the "idk who's running this" option fr fr
As new processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the processors that are most common at the time that version of GCC is released. so like, it's a moving target, no cap
There is no -march=generic option because -march indicates the instruction set the compiler can use, and there is no generic instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized.
intelโ Produce code optimized for the most current Intel processors, which are Haswell and Silvermont for this version of GCC. If you know the CPU on which your code will run, then you should use the corresponding-mtuneor-marchoption instead of-mtune=intel. But, if you want your application performs better on both Haswell and Silvermont, then you should use this option. Haswell AND Silvermont?? multitasking queen ๐
As new Intel processors are deployed in the marketplace, the behavior of this option will change. Therefore, if you upgrade to a newer version of GCC, code generation controlled by this option will change to reflect the most current Intel processors at the time that version of GCC is released.
There is no -march=intel option because -march indicates the instruction set the compiler can use, and there is no common instruction set applicable to all processors. In contrast, -mtune indicates the processor (or, in this case, collection of processors) for which the code is optimized.
-mcpu=cpu-typeโ A deprecated synonym for-mtune. it's giving legacy, use the new one bestie ๐-mfpmath=unitโ Generate floating-point arithmetic for selected unit unit. The choices for unit are:387โ Use the standard 387 floating-point coprocessor present on the majority of chips and emulated otherwise. Code compiled with this option runs almost everywhere. The temporary results are computed in 80-bit precision instead of the precision specified by the type, resulting in slightly different results compared to most of other chips. See-ffloat-storefor more detailed description. 80-bit temporaries, it's a whole thing ๐ญ
This is the default choice for non-Darwin x86-32 targets.
sseโ Use scalar floating-point instructions present in the SSE instruction set. This instruction set is supported by Pentium III and newer chips, and in the AMD line by Athlon-4, Athlon XP and Athlon MP chips. The earlier version of the SSE instruction set supports only single-precision arithmetic, thus the double and extended-precision arithmetic are still done using 387. A later version, present only in Pentium 4 and AMD x86-64 chips, supports double-precision arithmetic too. precision lore drop ๐ธ
For the x86-32 compiler, you must use -march=cpu-type, -msse or -msse2 switches to enable SSE extensions and make this option effective. For the x86-64 compiler, these extensions are enabled by default.
The resulting code should be considerably faster in the majority of cases and avoid the numerical instability problems of 387 code, but may break some existing code that expects temporaries to be 80 bits. heads up bestie, this one bites sometimes โ ๏ธ
This is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default choice for x86-32 targets with the SSE2 instruction set when -ffast-math is enabled.
sse,387sse+387bothโ bestie, this one tries to flex both instruction sets at the same time โจ it literally doubles the registers you can play with, and on chips that have separate execution units for 387 and SSE you get double the execution resources too. But use it with care, it's still experimental โ the GCC register allocator doesn't model separate functional units well, so the performance is giving unstable, no cap ๐ญ
-masm=dialectโ spit out assembly instructions in whichever dialect you picked ๐ it also changes which dialect gets used for basicasmand extendedasm. The supported choices, in dialect order, areattorintel. Default isatt. And heads up: Darwin does not supportintel. ๐ซ-mieee-fp-mno-ieee-fpโ toggles whether the compiler uses IEEE floating-point comparisons or not. These are the ones that correctly handle the case where a comparison result is unordered. ๐ซถ-m80387-mhard-floatโ generate output that contains80387instructions for floating point.-mno-80387-msoft-floatโ generate output containing library calls for floating point.
Warning โ ๏ธ: the requisite libraries are not part of GCC. Normally the facilities of the machine's usual C compiler get used, but you can't do that directly in cross-compilation. You gotta make your own arrangements to provide suitable library functions for cross-compilation.
On machines where a function returns floating-point results in the 80387 register stack, some floating-point opcodes may be emitted even if -msoft-float is used. ๐
-mno-fp-ret-in-387โ don't use the FPU registers for return values of functions. ๐ โโ๏ธ
The usual calling convention has functions return values of types float and double in an FPU register, even if there is no FPU. The idea is that the operating system should emulate an FPU.
The option -mno-fp-ret-in-387 causes such values to be returned in ordinary CPU registers instead.
-mno-fancy-math-387โ some 387 emulators don't support thesin,cosandsqrtinstructions for the 387, so specify this option to avoid generating those instructions. This option gets overridden when-marchindicates that the target CPU always has an FPU and so the instruction doesn't need emulation. And ngl, these instructions aren't generated unless you also use the-funsafe-math-optimizationsswitch. ๐-malign-double-mno-align-doubleโ controls whether GCC alignsdouble,long double, andlong longvariables on a two-word boundary or a one-word boundary. Aligningdoublevariables on a two-word boundary produces code that runs somewhat faster on a Pentium, at the expense of more memory. ๐ธ
On x86-64, -malign-double is enabled by default.
Warning โ ๏ธ: if you use the -malign-double switch, structures containing the above types are aligned differently than the published application binary interface specifications for the x86-32 and are not binary compatible with structures in code compiled without that switch. ๐ฌ
-m96bit-long-double-m128bit-long-doubleโ these switches control the size oflong doubletype. The x86-32 application binary interface specifies the size to be 96 bits, so-m96bit-long-doubleis the default in 32-bit mode. ๐ฆ
Modern architectures (Pentium and newer) prefer long double to be aligned to an 8- or 16-byte boundary. In arrays or structures conforming to the ABI, this is not possible. So specifying -m128bit-long-double aligns long double to a 16-byte boundary by padding the long double with an additional 32-bit zero.
In the x86-64 compiler, -m128bit-long-double is the default choice as its ABI specifies that long double is aligned on 16-byte boundary.
Notice that neither of these options enable any extra precision over the x87 standard of 80 bits for a long double. ๐
Warning โ ๏ธ: if you override the default value for your target ABI, this changes the size of structures and arrays containinglong doublevariables, as well as modifying the function calling convention for functions takinglong double. Hence they are not binary-compatible with code compiled without that switch. ๐ญ
-mlong-double-64-mlong-double-80-mlong-double-128โ these switches control the size oflong doubletype. A size of 64 bits makes thelong doubletype equivalent to thedoubletype. This is the default for 32-bit Bionic C library. A size of 128 bits makes thelong doubletype equivalent to the__float128type. This is the default for 64-bit Bionic C library. โจ
Warning โ ๏ธ: if you override the default value for your target ABI, this changes the size of structures and arrays containinglong doublevariables, as well as modifying the function calling convention for functions takinglong double. Hence they are not binary-compatible with code compiled without that switch. ๐
-malign-data=typeโ control how GCC aligns variables. Supported values for type are:compatโ uses increased alignment value compatible uses GCC 4.8 and earlierabiโ uses alignment value as specified by the psABIcachelineโ uses increased alignment value to match the cache line size
compat is the default. ๐
-mlarge-data-threshold=thresholdโ when-mcmodel=mediumis specified, data objects larger than threshold are placed in the large data section. This value must be the same across all objects linked into the binary, and defaults to65535. ๐-mrtdโ use a different function-calling convention, in which functions that take a fixed number of arguments return with theret numinstruction, which pops their arguments while returning. This saves one instruction in the caller since there's no need to pop the arguments there. ๐ฅ
You can specify that an individual function is called with this calling sequence with the function attribute stdcall. You can also override the -mrtd option by using the function attribute cdecl.
Warning โ ๏ธ: this calling convention is incompatible with the one normally used on Unix, so you cannot use it if you need to call libraries compiled with the Unix compiler. ๐ฌ
Also, you must provide function prototypes for all functions that take variable numbers of arguments (including printf); otherwise incorrect code is generated for calls to those functions. ๐ญ
In addition, seriously incorrect code results if you call a function with too many arguments. (Normally, extra arguments are harmlessly ignored.) ๐
-mregparm=numโ control how many registers are used to pass integer arguments. By default, no registers are used to pass arguments, and at most 3 registers can be used. You can control this behavior for a specific function by using the function attributeregparm. ๐ซถ
Warning โ ๏ธ: if you use this switch, and num is nonzero, then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. ๐
-msseregparmโ use SSE register passing conventions for float and double arguments and return values. You can control this behavior for a specific function by using the function attributesseregparm. โจ
Warning โ ๏ธ: if you use this switch then you must build all modules with the same value, including any libraries. This includes the system libraries and startup modules. ๐ค
-mvect8-ret-in-memโ return 8-byte vectors in memory instead of MMX registers. This is the default on VxWorks to match the ABI of the Sun Studio compilers until version 12. Only use this option if you need to remain compatible with existing code produced by those previous compiler versions or older versions of GCC. ๐-mpc32-mpc64-mpc80โ set80387floating-point precision to 32, 64 or 80 bits. When-mpc32is specified, the significands of results of floating-point operations are rounded to 24 bits (single precision);-mpc64rounds the significands of results of floating-point operations to 53 bits (double precision) and-mpc80rounds the significands of results of floating-point operations to 64 bits (extended double precision), which is the default. When this option is used, floating-point operations in higher precisions are not available to the programmer without setting the FPU control word explicitly. ๐
Setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. Note that some mathematical libraries assume that extended-precision (80-bit) floating-point operations are enabled by default; routines in such libraries could suffer significant loss of accuracy, typically through so-called "catastrophic cancellation", when this option is used to set the precision to less than extended precision. ๐ฑ
-mdaz-ftzโ the flush-to-zero (FTZ) and denormals-are-zero (DAZ) flags in the MXCSR register are used to control floating-point calculations. SSE and AVX instructions including scalar and vector instructions could benefit from enabling the FTZ and DAZ flags when-mdaz-ftzis specified. Don't set FTZ/DAZ flags when-mno-daz-ftzis specified. ๐ง-mstackrealignโ realign the stack at entry. On the x86, the-mstackrealignoption generates an alternate prologue and epilogue that realigns the run-time stack if necessary. This supports mixing legacy codes that keep 4-byte stack alignment with modern codes that keep 16-byte stack alignment for SSE compatibility. See also the attributeforce_align_arg_pointer, applicable to individual functions. ๐-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. If-mpreferred-stack-boundaryis not specified, the default is 4 (16 bytes or 128 bits). ๐
โ ๏ธ Warning, bestie, listen up: when you're generating code for the x86-64 architecture with SSE extensions disabled,-mpreferred-stack-boundary=3can be used to keep the stack boundary aligned to an 8 byte boundary. Since x86-64 ABI require 16 byte stack alignment, this is ABI incompatible and intended to be used in controlled environment where stack space is important limitation. This option leads to wrong code when functions compiled with 16 byte stack alignment (such as functions from a standard library) are called with misaligned stack. In this case, SSE instructions may lead to misaligned memory access traps. In addition, variable arguments are handled incorrectly for 16 byte aligned objects (including x87long doubleand__int128), leading to wrong results. You must build all modules with-mpreferred-stack-boundary=3, including any libraries. This includes the system libraries and startup modules. ๐ญ
๐ซถ -mincoming-stack-boundary=num
Assume the incoming stack is aligned to a 2 raised to num byte boundary. If -mincoming-stack-boundary is not specified, the one specified by -mpreferred-stack-boundary is used.
On Pentium and Pentium Pro, "double" and "long double" values should be aligned to an 8-byte boundary (see -malign-double) or suffer significant run time performance penalties. On Pentium III, the Streaming SIMD Extension (SSE) data type "__m128" may not work properly if it is not 16-byte aligned.
To ensure proper alignment of this values on the stack, the stack boundary must be as aligned as that required by any value stored on the stack. Further, every function must be generated such that it keeps the stack aligned. Thus calling a function compiled with a higher preferred stack boundary from a function compiled with a lower preferred stack boundary most likely misaligns the stack. It is recommended that libraries that use callbacks always use the default setting. ๐
This extra alignment does consume extra stack space, and generally increases code size. Code that is sensitive to stack space usage, such as embedded systems and operating system kernels, may want to reduce the preferred alignment to -mpreferred-stack-boundary=2.
โจ The Big Extended-Instruction-Set Vibe Check โจ
Okay so this next bunch is iconic โ here's the full roster of switches, no skips:
-mmmx
-msse
-msse2
-msse3
-mssse3
-msse4
-msse4a
-msse4.1
-msse4.2
-mavx
-mavx2
-mavx512f
-mavx512pf
-mavx512er
-mavx512cd
-mavx512vl
-mavx512bw
-mavx512dq
-mavx512ifma
-mavx512vbmi
-msha
-maes
-mpclmul
-mclflushopt
-mclwb
-mfsgsbase
-mptwrite
-mrdrnd
-mf16c
-mfma
-mpconfig
-mwbnoinvd
-mfma4
-mprfchw
-mrdpid
-mprefetchwt1
-mrdseed
-msgx
-mxop
-mlwp
-m3dnow
-m3dnowa
-mpopcnt
-mabm
-madx
-mbmi
-mbmi2
-mlzcnt
-mfxsr
-mxsave
-mxsaveopt
-mxsavec
-mxsaves
-mrtm
-mhle
-mtbm
-mmwaitx
-mclzero
-mpku
-mavx512vbmi2
-mavx512bf16
-mavx512fp16
-mgfni
-mvaes
-mwaitpkg
-mvpclmulqdq
-mavx512bitalg
-mmovdiri
-mmovdir64b
-menqcmd
-muintr
-mtsxldtrk
-mavx512vpopcntdq
-mavx512vp2intersect
-mavx5124fmaps
-mavx512vnni
-mavxvnni
-mavx5124vnniw
-mcldemote
-mserialize
-mamx-tile
-mamx-int8
-mamx-bf16
-mhreset
-mkl
-mwidekl
These switches enable the use of instructions in the MMX, SSE, SSE2, SSE3, SSSE3, SSE4, SSE4A, SSE4.1, SSE4.2, AVX, AVX2, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX512VL, AVX512BW, AVX512DQ, AVX512IFMA, AVX512VBMI, SHA, AES, PCLMUL, CLFLUSHOPT, CLWB, FSGSBASE, PTWRITE, RDRND, F16C, FMA, PCONFIG, WBNOINVD, FMA4, PREFETCHW, RDPID, PREFETCHWT1, RDSEED, SGX, XOP, LWP, 3DNow!, enhanced 3DNow!, POPCNT, ABM, ADX, BMI, BMI2, LZCNT, FXSR, XSAVE, XSAVEOPT, XSAVEC, XSAVES, RTM, HLE, TBM, MWAITX, CLZERO, PKU, AVX512VBMI2, GFNI, VAES, WAITPKG, VPCLMULQDQ, AVX512BITALG, MOVDIRI, MOVDIR64B, AVX512BF16, ENQCMD, AVX512VPOPCNTDQ, AVX5124FMAPS, AVX512VNNI, AVX5124VNNIW, SERIALIZE, UINTR, HRESET, AMXTILE, AMXINT8, AMXBF16, KL, WIDEKL, AVXVNNI, AVX512-FP16 or CLDEMOTE extended instruction sets. Each has a corresponding -mno- option to disable use of these instructions. ๐
These extensions are also available as built-in functions: see x86 Built-in Functions, for details of the functions enabled and disabled by these switches.
To generate SSE/SSE2 instructions automatically from floating-point code (as opposed to 387 instructions), see -mfpmath=sse.
GCC depresses SSEx instructions when -mavx is used. Instead, it generates new AVX instructions or AVX equivalence for all SSEx instructions when needed. not me replacing the whole squad with the upgraded version ๐
These options enable GCC to use these extended instructions in generated code, even without -mfpmath=sse. Applications that perform run-time CPU detection must compile separate files for each supported architecture, using the appropriate flags. In particular, the file containing the CPU detection code should be compiled without these options.
๐ Tuning-Feature Switches ๐
-mdump-tune-featuresโ this option instructs GCC to dump the names of the x86 performance tuning features and default settings. The names can be used in-mtune-ctrl=feature-list.- *
-mtune-ctrl=feature-list* โ this option is used to do fine grain control of x86 code generation features. feature-list is a comma separated list of feature names. See also-mdump-tune-features. When specified, the feature is turned on if it is not preceded with^, otherwise, it is turned off.-mtune-ctrl=feature-list is intended to be used by GCC developers. Using it may lead to code paths not covered by testing and can potentially result in compiler ICEs or runtime errors. fr fr, do not touch this unless you know exactly what you're doing ๐ -mno-defaultโ this option instructs GCC to turn off all tunable features. See also-mtune-ctrl=feature-list and-mdump-tune-features.-mcldโ this option instructs GCC to emit a"cld"instruction in the prologue of functions that use string instructions. String instructions depend on the DF flag to select between autoincrement or autodecrement mode. While the ABI specifies the DF flag to be cleared on function entry, some operating systems violate this specification by not clearing the DF flag in their exception dispatchers. The exception handler can be invoked with the DF flag set, which leads to wrong direction mode when string instructions are used. This option can be enabled by default on 32-bit x86 targets by configuring GCC with the--enable-cldconfigure option. Generation of"cld"instructions can be suppressed with the-mno-cldcompiler option in this case.-mvzeroupperโ this option instructs GCC to emit a"vzeroupper"instruction before a transfer of control flow out of the function to minimize the AVX to SSE transition penalty as well as remove unnecessary"zeroupper"intrinsics.-mprefer-avx128โ this option instructs GCC to use 128-bit AVX instructions instead of 256-bit AVX instructions in the auto-vectorizer. lowkey the modest queen ๐- *
-mprefer-vector-width=opt* โ this option instructs GCC to use opt-bit vector width in instructions instead of default on the selected platform. - *
-mmove-max=bits* โ this option instructs GCC to set the maximum number of bits can be moved from memory to memory efficiently to bits. The valid bits are128,256and512. - *
-mstore-max=bits* โ this option instructs GCC to set the maximum number of bits can be stored to memory efficiently to bits. The valid bits are128,256and512.
And the values that go in -mprefer-vector-width=, so you know your options:
noneโ no extra limitations applied to GCC other than defined by the selected platform.128โ prefer 128-bit vector width for instructions.256โ prefer 256-bit vector width for instructions.512โ prefer 512-bit vector width for instructions.
๐ More x86 Options, We're So Back ๐
-mcx16โ this option enables GCC to generate"CMPXCHG16B"instructions in 64-bit code to implement compare-and-exchange operations on 16-byte aligned 128-bit objects. This is useful for atomic updates of data structures exceeding one machine word in size. The compiler uses this instruction to implement__syncBuiltins. However, for__atomicBuiltins operating on 128-bit integers, a library call is always used.-msahfโ this option enables generation of"SAHF"instructions in 64-bit code. Early Intel Pentium 4 CPUs with Intel 64 support, prior to the introduction of Pentium 4 G1 step in December 2005, lacked the"LAHF"and"SAHF"instructions which are supported by AMD64. These are load and store instructions, respectively, for certain status flags. In 64-bit mode, the"SAHF"instruction is used to optimize"fmod","drem", and"remainder"built-in functions; see Other Builtins for details.-mmovbeโ this option enables use of the"movbe"instruction to implement__builtin_bswap32and__builtin_bswap64.-mshstkโ the-mshstkoption enables shadow stack built-in functions from x86 Control-flow Enforcement Technology (CET).-mcrc32โ this option enables built-in functions__builtin_ia32_crc32qi,__builtin_ia32_crc32hi,__builtin_ia32_crc32siand__builtin_ia32_crc32dito generate the"crc32"machine instruction.-mmwaitโ this option enables built-in functions__builtin_ia32_monitor, and__builtin_ia32_mwaitto generate the"monitor"and"mwait"machine instructions.-mrecipโ this option enables use of"RCPSS"and"RSQRTSS"instructions (and their vectorized variants"RCPPS"and"RSQRTPS") with an additional Newton-Raphson step to increase precision instead of"DIVSS"and"SQRTSS"(and their vectorized variants) for single-precision floating-point arguments. These instructions are generated only when-funsafe-math-optimizationsis enabled together with-ffinite-math-onlyand-fno-trapping-math. Note that while the throughput of the sequence is higher than the throughput of the non-reciprocal instruction, the precision of the sequence can be decreased by up to 2 ulp (i.e. the inverse of1.0equals0.99999994). it's giving "fast but slightly delulu" ๐
Note that GCC implements "1.0f/sqrtf(x)" in terms of "RSQRTSS" (or "RSQRTPS") already with -ffast-math (or the above option combination), and doesn't need -mrecip.
Also, heads up bestie: GCC emits that whole sequence above with an extra Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already when you've got -ffast-math (or that option combo from before) turned on โ and it doesn't even need -mrecip. Slay, no extra flag required. ๐
-mrecip=optโ this one is the bouncer at the club ๐๏ธ deciding which reciprocal estimate instructions get to come in. opt is a comma-separated list, and any item can be prefixed with!to flip it to the opposite. Here's the VIP list:allโ let every single estimate instruction in. All of them. Periodt.defaultโ just the default ones, which is literally the same thing as plain-mrecip.noneโ nope, nobody gets in. Equivalent to-mno-recip.divโ turn on the approximation for scalar division.vec-divโ turn on the approximation for vectorized division.sqrtโ turn on the approximation for scalar square root.vec-sqrtโ turn on the approximation for vectorized square root.
So like, for example, -mrecip=all,!sqrt enables every reciprocal approximation except square root. Cherry-picking, we love to see it ๐
-mveclibabi=typeโ tells GCC which ABI type to use when vectorizing intrinsics with an external library. The supported type values aresvml(for the Intel short vector math library) andacml(for the AMD math core library). To actually use this, both-ftree-vectorizeand-funsafe-math-optimizationshave to be enabled, and you need an SVML- or ACML-ABI-compatible library specified at link time. No library, no vibes. ๐ญ
Right now, GCC emits calls to "vmldExp2", "vmldLn2", "vmldLog102", "vmldPow2", "vmldTanh2", "vmldTan2", "vmldAtan2", "vmldAtanh2", "vmldCbrt2", "vmldSinh2", "vmldSin2", "vmldAsinh2", "vmldAsin2", "vmldCosh2", "vmldCos2", "vmldAcosh2", "vmldAcos2", "vmlsExp4", "vmlsLn4", "vmlsLog104", "vmlsPow4", "vmlsTanh4", "vmlsTan4", "vmlsAtan4", "vmlsAtanh4", "vmlsCbrt4", "vmlsSinh4", "vmlsSin4", "vmlsAsinh4", "vmlsAsin4", "vmlsCosh4", "vmlsCos4", "vmlsAcosh4" and "vmlsAcos4" for the corresponding function type when -mveclibabi=svml is used, and "__vrd2_sin", "__vrd2_cos", "__vrd2_exp", "__vrd2_log", "__vrd2_log2", "__vrd2_log10", "__vrs4_sinf", "__vrs4_cosf", "__vrs4_expf", "__vrs4_logf", "__vrs4_log2f", "__vrs4_log10f" and "__vrs4_powf" for the corresponding function type when -mveclibabi=acml is used. That's the whole roster, no cap ๐ซก
-mabi=nameโ generate code for the calling convention you name. The permissible values aresysv(the ABI used on GNU/Linux and other systems) andms(the Microsoft ABI). The default is to use the Microsoft ABI when you're targeting Microsoft Windows, and the SysV ABI everywhere else. You can also control this behavior for specific functions by using thems_abiandsysv_abifunction attributes. Per-function lewks โจ-mforce-indirect-callโ forces literally all calls to functions to be indirect. Super useful with Intel Processor Trace, where it generates more precise timing information for function calls. Timestamps but make it fancy โฑ๏ธ-mmanual-endbrโ inserts an ENDBR instruction at function entry only via thecf_checkfunction attribute. Handy when paired with-fcf-protection=branchso you can control ENDBR insertion at the function entry yourself. You're the main character now ๐-mcall-ms2sysv-xloguesโ so here's the drama: because of differences in 64-bit ABIs, any Microsoft ABI function that calls a System V ABI function has to treat RSI, RDI and XMM6-15 as clobbered. By default the code for saving and restoring those registers gets emitted inline, which gives you some pretty lengthy prologues and epilogues. Using-mcall-ms2sysv-xloguesemits prologues and epilogues that use stubs in the static portion oflibgccto do those saves and restores instead โ so function size goes down, at the cost of a few extra instructions. Trade-offs, bestie, trade-offs โ๏ธ-mtls-dialect=typeโ generate code to access thread-local storage using thegnuorgnu2conventions.gnuis the conservative default;gnu2is more efficient, but it may add compile- and run-time requirements that can't be satisfied on all systems. Faster but pickier, it's giving high-maintenance ๐-mpush-args-mno-push-argsโ use PUSH operations to store outgoing parameters. This method is shorter and usually equally fast as the method using SUB/MOV operations, and it's enabled by default. In some cases disabling it may improve performance because of improved scheduling and reduced dependencies. Sometimes less is more, yk?-maccumulate-outgoing-argsโ if enabled, the maximum amount of space required for outgoing arguments is computed in the function prologue. This is faster on most modern CPUs because of reduced dependencies, improved scheduling, and reduced stack usage when the preferred stack boundary isn't equal to 2. The drawback? A notable increase in code size. Also, this switch implies-mno-push-args. Big brain move with a big binary consequence ๐ง-mthreadsโ supports thread-safe exception handling on MinGW. Programs that rely on thread-safe exception handling must compile and link all code with the-mthreadsoption. When compiling,-mthreadsdefines-D_MT; when linking, it links in a special thread helper library-lmingwthrdwhich cleans up per-thread exception-handling data. Cleanup crew reporting for duty ๐งน-mms-bitfields-mno-ms-bitfieldsโ enable/disable bit-field layout compatible with the native Microsoft Windows compiler. Here's the tea: if"packed"is used on a structure, or if bit-fields are used, it may be that the Microsoft ABI lays out the structure differently than the way GCC normally does. Especially when you're moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), you may need to access either format.
This option is enabled by default for Microsoft Windows targets. You can also control this behavior locally by using variable or type attributes โ for more info, see x86 Variable Attributes and x86 Type Attributes. ๐
The Microsoft structure layout algorithm is fairly simple, except for the bit-field packing. The padding and alignment of members of structures, and whether a bit-field can straddle a storage-unit boundary, are determined by these rules:
- Structure members are stored sequentially in the order in which they are declared: the first member has the lowest memory address and the last member the highest.
- Every data object has an alignment requirement. The alignment requirement for all data except structures, unions, and arrays is either the size of the object or the current packing size (specified with either the
"aligned"attribute or the"pack"pragma), whichever is less. For structures, unions, and arrays, the alignment requirement is the largest alignment requirement of its members. Every object is allocated an offset so that:
offset % alignment_requirement == 0
- Adjacent bit-fields are packed into the same 1-, 2-, or 4-byte allocation unit if the integral types are the same size and if the next bit-field fits into the current allocation unit without crossing the boundary imposed by the common alignment requirements of the bit-fields.
MSVC interprets zero-length bit-fields in the following ways:
- If a zero-length bit-field is inserted between two bit-fields that are normally coalesced, the bit-fields are not coalesced.
For example:
struct
{
unsigned long bf_1 : 12;
unsigned long : 0;
unsigned long bf_2 : 12;
} t1;
The size of "t1" is 8 bytes with the zero-length bit-field. If the zero-length bit-field were removed, "t1"'s size would be 4 bytes. Poof, halved ๐
- If a zero-length bit-field is inserted after a bit-field,
"foo", and the alignment of the zero-length bit-field is greater than the member that follows it,"bar","bar"is aligned as the type of the zero-length bit-field.
For example:
struct
{
char foo : 4;
short : 0;
char bar;
} t2;
struct
{
char foo : 4;
short : 0;
double bar;
} t3;
For "t2", "bar" is placed at offset 2, rather than offset 1. Accordingly, the size of "t2" is 4. For "t3", the zero-length bit-field does not affect the alignment of "bar" or, as a result, the size of the structure.
Taking this into account, it's important to note the following:
- If a zero-length bit-field follows a normal bit-field, the type of the zero-length bit-field may affect the alignment of the structure as whole. For example,
"t2"has a size of 4 bytes, since the zero-length bit-field follows a normal bit-field, and is of type short. - Even if a zero-length bit-field is not followed by a normal bit-field, it may still affect the alignment of the structure:
struct
{
char foo : 6;
long : 0;
} t4;
Here, "t4" takes up 4 bytes.
- Zero-length bit-fields following non-bit-field members are ignored:
struct
{
char foo;
long : 0;
char bar;
} t5;
Here, "t5" takes up 2 bytes.
-mno-align-stringopsโ don't align the destination of inlined string operations. This switch reduces code size and improves performance in case the destination is already aligned, but GCC doesn't know about it. Rude of GCC to not just trust you, honestly ๐-minline-all-stringopsโ by default GCC inlines string operations only when the destination is known to be aligned to at least a 4-byte boundary. This enables more inlining and increases code size, but may improve performance of code that depends on fast"memcpy"and"memset"for short lengths. The option also enables inline expansion of"strlen"for all pointer alignments. Short-string speedrun, go ๐โ๏ธ-minline-stringops-dynamicallyโ for string operations of unknown size, use run-time checks with inline code for small blocks and a library call for large blocks. Small stuff stays home, big stuff calls in the professionals ๐-mstringop-strategy=algโ override the internal decision heuristic for the particular algorithm to use when inlining string operations. The allowed values for alg are:rep_byterep_4byterep_8byteExpand using the i386"rep"prefix of the size you picked, bestie.byte_looploopunrolled_loopExpand it into an inline loop. Cute, right?libcallAlways use a library call. No inlining, no drama.
โจ MORE x86 OPTIONS (the saga continues) โจ
-mmemcpy-strategy=strategyโ Okay so this one overrides the internal decision heuristic that decides whether"__builtin_memcpy"should get inlined, and which inline algorithm to use when the expected size of the copy is known. The strategy is a comma-separated list ofalg:max_size:dest_aligntriplets.algis specified in-mstringop-strategy, andmax_sizespecifies the max byte size with which inline algorithm alg is allowed. For the last triplet, themax_sizemust be-1. Themax_sizeof the triplets in the list must be specified in increasing order. The minimal byte size for alg is0for the first triplet and"max_size + 1"of the preceding range. iykyk ๐-mmemset-strategy=strategyโ Same energy as-mmemcpy-strategy=except this one is here to control"__builtin_memset"expansion.-momit-leaf-frame-pointerโ Don't keep the frame pointer in a register for leaf functions, bestie. This dodges the instructions to save, set up, and restore frame pointers, and makes an extra register available in leaf functions. Heads up tho: the option-fomit-leaf-frame-pointerremoves the frame pointer for leaf functions, which might make debugging harder. ๐ญ-mtls-direct-seg-refs-mno-tls-direct-seg-refsControls whether TLS variables may be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer must be added. Whether or not this is valid depends on the operating system, and whether it maps the segment to cover the entire TLS area. For systems that use the GNU C Library, the default is on. โจ-msse2avx-mno-sse2avxSpecify that the assembler should encode SSE instructions with VEX prefix. The option-mavxturns this on by default. ๐-mfentry-mno-fentryIf profiling is active (-pg), put the profiling counter call before the prologue. Note: on x86 architectures the attribute"ms_hook_prologue"isn't possible at the moment for-mfentryand-pg. ๐ซ-mrecord-mcount-mno-record-mcountIf profiling is active (-pg), generate a__mcount_locsection that contains pointers to each profiling call. This is useful for automatically patching and out calls. ๐ฅ-mnop-mcount-mno-nop-mcountIf profiling is active (-pg), generate the calls to the profiling functions as NOPs. This is useful when they should be patched in later dynamically. This is likely only useful together with-mrecord-mcount.-minstrument-return=typeโ Instrument function exit in-pg -mfentryinstrumented functions with a call to the specified function. This only instruments true returns ending withret, but not sibling calls ending withjump. Valid types are:noneโ to not instrumentcallโ to generate a call to__return__nop5โ to generate a 5 byte nop
-mrecord-return-mno-record-returnGenerate a__return_locsection pointing to all return instrumentation code.-mfentry-name=nameโ Set the name of the__fentry__symbol called at function entry for-pg -mfentryfunctions.-mfentry-section=nameโ Set the name of the section to record-mrecord-mcountcalls (default__mcount_loc).-mskip-rax-setup-mno-skip-rax-setupWhen generating code for the x86-64 architecture with SSE extensions disabled,-mskip-rax-setupcan be used to skip setting up the RAX register when there are no variable arguments passed in vector registers.
Warning, bestie, listen up: Since the RAX register is used to avoid unnecessarily saving vector registers on stack when passing variable arguments, the impacts of this option are that callees may waste some stack space, misbehave, or jump to a random location. GCC 4.4 or newer don't have those issues, regardless of the RAX register value. ๐
-m8bit-idiv-mno-8bit-idivOn some processors, like Intel Atom, 8-bit unsigned integer divide is much faster than 32-bit/64-bit integer divide. This option generates a run-time check. If both dividend and divisor are within range of0to255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. โก-mavx256-split-unaligned-load-mavx256-split-unaligned-storeSplit 32-byte AVX unaligned load and store.-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offsetGenerate stack protection code using canary at guard. Supported locations areglobalfor global canary, ortlsfor per-thread canary in the TLS block (the default). This option has effect only when-fstack-protectoror-fstack-protector-allis specified.
With the latter choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset furthermore specify which segment register (%fs or %gs) to use as base register for reading the canary, and from what offset from that base register. The default for those is as specified in the relevant ABI. ๐
-mgeneral-regs-onlyโ Generate code that uses only the general-purpose registers. This prevents the compiler from using floating-point, vector, mask and bound registers. no extra regs invited to the party ๐-mrelax-cmpxchg-loopโ Relax cmpxchg loop by emitting an early load and compare before cmpxchg, execute pause if load value is not expected. This reduces excessive cachline bouncing when and works for all atomic logic fetch builtins that generates compare and swap loop. ๐ฅ-mindirect-branch=choiceโ Convert indirect call and jump with choice. The default iskeep, which keeps indirect call and jump unmodified.thunkconverts indirect call and jump to call and return thunk.thunk-inlineconverts indirect call and jump to inlined call and return thunk.thunk-externconverts indirect call and jump to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute"indirect_branch". ๐ฆ
Note: -mcmodel=large is incompatible with -mindirect-branch=thunk and -mindirect-branch=thunk-extern since the thunk function may not be reachable in the large code model. ๐ญ
Note: -mindirect-branch=thunk-extern is compatible with -fcf-protection=branch since the external thunk can be made to enable control-flow check. โจ
-mfunction-return=choiceโ Convert function return with choice. The default iskeep, which keeps function return unmodified.thunkconverts function return to call and return thunk.thunk-inlineconverts function return to inlined call and return thunk.thunk-externconverts function return to external call and return thunk provided in a separate object file. You can control this behavior for a specific function by using the function attribute"function_return". ๐
Note: -mindirect-return=thunk-extern is compatible with -fcf-protection=branch since the external thunk can be made to enable control-flow check. โจ
Note: -mcmodel=large is incompatible with -mfunction-return=thunk and -mfunction-return=thunk-extern since the thunk function may not be reachable in the large code model. ๐ญ
-mindirect-branch-registerโ Force indirect call and jump via register. periodt.-mharden-sls=choiceโ Generate code to mitigate against straight line speculation (SLS) with choice. The default isnone, which disables all SLS hardening.returnenables SLS hardening for function returns.indirect-jmpenables SLS hardening for indirect jumps.allenables all SLS hardening. ๐-mindirect-branch-cs-prefixโ Add CS prefix to call and jmp to indirect thunk with branch target in r8-r15 registers so that the call and jmp instruction length is 6 bytes to allow them to be replaced withlfence; call *%r8-r15orlfence; jmp *%r8-r15at run-time. ๐
These -m switches are supported in addition to the above on x86-64 processors in 64-bit environments, bestie. โจ
-m32-m64-mx32-m16-miamcuGenerate code for a 16-bit, 32-bit or 64-bit environment.
The -m32 option sets "int", "long", and pointer types to 32 bits, and generates code that runs in 32-bit mode. ๐
The -m64 option sets "int" to 32 bits and "long" and pointer types to 64 bits, and generates code for the x86-64 architecture. For Darwin only the -m64 option also turns off the -fno-pic and -mdynamic-no-pic options. ๐ฆ
The -mx32 option sets "int", "long", and pointer types to 32 bits, and generates code for the x86-64 architecture. ๐ธ
The -m16 option is the same as -m32, except for that it outputs the ".code16gcc" assembly directive at the beginning of the assembly output so that the binary can run in 16-bit mode. โญ
The -miamcu option generates code which conforms to Intel MCU psABI. It requires the -m32 option to be turned on. ๐ฅ
-mno-red-zoneโ Do not use a so-called "red zone" for x86-64 code. The red zone is mandated by the x86-64 ABI; it is a 128-byte area beyond the location of the stack pointer that is not modified by signal or interrupt handlers and therefore can be used for temporary data without adjusting the stack pointer. The flag-mno-red-zonedisables this red zone. ๐-mcmodel=smallโ Generate code for the small code model: the program and its symbols must be linked in the lower 2 GB of the address space. Pointers are 64 bits. Programs can be statically or dynamically linked. This is the default code model. โจ-mcmodel=kernelโ Generate code for the kernel code model. The kernel runs in the negative 2 GB of the address space. This model has to be used for Linux kernel code. ๐-mcmodel=mediumโ Generate code for the medium model: the program is linked in the lower 2 GB of the address space. Small symbols are also placed there. Symbols with sizes larger than-mlarge-data-thresholdare put into large data or BSS sections and can be located above 2GB. Programs can be statically or dynamically linked. ๐ฆ-mcmodel=largeโ Generate code for the large model. This model makes no assumptions about addresses and sizes of sections. ๐-maddress-mode=longโ Generate code for long address mode. This is only supported for 64-bit and x32 environments. It is the default address mode for 64-bit environments. โจ-maddress-mode=shortโ bestie this one makes the compiler generate code for short address mode. It's only a thing for 32-bit and x32 environments, and honestly? It's already the default address mode there, so it's giving "you were already doing this, congrats ๐ ".-mneeded-mno-neededโ these two control whether GCC emits aGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for the Linux target, which is the little note that says "hey, this binary needs at least this micro-architecture ISA level to run". โจ-mno-direct-extern-accessโ okay so listen: without-fpicand without-fPIC, this makes GCC always use the GOT pointer to reach external symbols. But with-fpicor-fPIC, it treats access to protected symbols as local symbols instead. The default is-mdirect-extern-access, for the record. ๐ซถ
โ ๏ธ Warning, and this one is real: shared libraries compiled with-mno-direct-extern-accessand an executable compiled with-mdirect-extern-accessmay not be binary compatible if protected symbols get used in both the shared library and the executable. No cap, be careful. ๐ญ
๐ช x86 Windows Options ๐ช
These extra options are available for Microsoft Windows targets, bestie:
-mconsoleโ says "we're making a console application" and tells the linker to set the PE header subsystem type that console apps need. Available for Cygwin and MinGW targets, and it's enabled by default on those targets. ๐-mdllโ available for Cygwin and MinGW targets. It says a DLL โ that's a dynamic link library, iykyk โ is what's being generated, which lets GCC pick the right runtime startup object and entry point. ๐-mnop-fun-dllimportโ available for Cygwin and MinGW targets. It says thedllimportattribute should just be ignored. Ignore her, she's not real ๐.-mthreadsโ available for MinGW targets. Specifies that MinGW-specific thread support is what we're using. ๐งต-municodeโ available for MinGW-w64 targets. It causes theUNICODEpreprocessor macro to be predefined, and it chooses Unicode-capable runtime startup code. Unicode slay โจ-mwin32โ available for Cygwin and MinGW targets. It says the typical Microsoft Windows predefined macros get set in the pre-processor, but โ important โ it does not influence the choice of runtime library or startup code. Just the macros, bestie.-mwindowsโ available for Cygwin and MinGW targets. Says a GUI application is being generated, by instructing the linker to set the PE header subsystem type appropriately. ๐ฆ-fno-set-stack-executableโ available for MinGW targets. It says the executable flag for the stack used by nested functions isn't set. This is necessary for binaries running in kernel mode of Microsoft Windows, because there the User32 API โ the thing used to set executable privileges โ isn't available at all. ๐ญ-fwritable-relocated-rdataโ available for MinGW and Cygwin targets. It says relocated-data in a read-only section gets put into the.datasection. This is necessary for older runtimes that don't support modification of.rdatasections for pseudo-relocation. Periodt.-mpe-aligned-commonsโ available for Cygwin and MinGW targets. It says the GNU extension to the PE file format that permits correct alignment ofCOMMONvariables should be used when generating code. It's enabled by default if GCC detects that the target assembler found during configuration supports the feature. ๐
See also under x86 Options for standard options. ๐
๐ฃ Xstormy16 Options ๐ฃ
These options are defined for Xstormy16:
-msimโ choose startup files and linker script that are suitable for the simulator. Simple as that, bestie.
๐ธ Xtensa Options ๐ธ
These options are supported for Xtensa targets:
-mconst16-mno-const16โ enable or disable use ofCONST16instructions for loading constant values. Fun fact: theCONST16instruction is currently not a standard option from Tensilica. When it's enabled,CONST16instructions are always used in place of the standardL32Rinstructions. The use ofCONST16is enabled by default only if theL32Rinstruction isn't available. ๐-mfused-madd-mno-fused-maddโ enable or disable use of fused multiply/add and multiply/subtract instructions in the floating-point option. It has no effect if the floating-point option isn't also enabled, okay? Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and the add/subtract operations. This may be desirable in some cases where strict IEEE 754-compliant results are required: the fused multiply add/subtract instructions don't round the intermediate result, which means they produce results with more bits of precision than the IEEE standard specifies. Disabling them also ensures that the program output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. Iconic little detail, ngl. โจ-mserialize-volatile-mno-serialize-volatileโ when this option is enabled, GCC insertsMEMWinstructions beforevolatilememory references to guarantee sequential consistency. The default is-mserialize-volatile. Use-mno-serialize-volatileto omit theMEMWinstructions. ๐ซถ-mforce-no-picโ for targets like GNU/Linux, where all user-mode Xtensa code must be position-independent code (PIC), this option disables PIC for compiling kernel code. Very "different rules for kernel mode" of it.-mtext-section-literals-mno-text-section-literalsโ these options control the treatment of literal pools. The default is-mno-text-section-literals, which places literals in a separate section in the output file. That lets the literal pool live in a data RAM/ROM, and it also lets the linker combine literal pools from separate object files to remove redundant literals and improve code size. With-mtext-section-literals, the literals are interspersed in the text section to keep them as close as possible to their references. This may be necessary for large assembly files. Literals for each function are placed right before that function. ๐-mauto-litpools-mno-auto-litpoolsโ also about literal pools, bestie. The default is-mno-auto-litpools, which places literals in a separate section in the output file unless-mtext-section-literalsis used. With-mauto-litpools, the literals are interspersed in the text section by the assembler. The compiler doesn't produce explicit.literaldirectives and loads literals into registers withMOVIinstructions instead ofL32R, so the assembler can do relaxation and place literals as necessary. This option lets the assembler create several literal pools per function and assemble very big functions, which may not be possible with-mtext-section-literals. ๐-mtarget-align-mno-target-alignโ when enabled, GCC instructs the assembler to automatically align instructions to reduce branch penalties, at the expense of some code density. The assembler attempts to widen density instructions to align branch targets and the instructions following call instructions. If there aren't enough preceding safe density instructions to align a target, no widening happens. The default is-mtarget-align. These options do not affect the treatment of auto-aligned instructions likeLOOP, which the assembler always aligns, either by widening density instructions or by inserting NOP instructions. ๐-mlongcalls-mno-longcallsโ when enabled, GCC instructs the assembler to translate direct calls into indirect calls unless it can determine that the target of a direct call is in the range allowed by the call instruction. This translation typically happens for calls to functions in other source files. Specifically, the assembler translates a directCALLinstruction into anL32Rfollowed by aCALLXinstruction. The default is-mno-longcalls. This option should be used in programs where the call target can potentially be out of range. Also, heads up: this option is implemented in the assembler, not the compiler, so the assembly code generated by GCC still shows direct call instructions โ look at the disassembled object code to see the actual instructions. And note that the assembler uses an indirect call for every cross-file call, not just those that really are out of range. ๐ญ-mabi=nameโ generate code for the specified ABI. Permissible values are:call0,windowed. The default ABI is chosen by the Xtensa core configuration. ๐ฆ-mabi=call0โ when this option is enabled, function parameters are passed in registersa2througha7, registersa12througha15are caller-saved, and registera15may be used as a frame pointer. When this version of the ABI is enabled, the C preprocessor symbol__XTENSA_CALL0_ABI__is defined. โจ-mabi=windowedโ when this option is enabled, function parameters are passed in registersa10througha15, and the called function rotates the register window by 8 registers on entry so that its arguments are found in registersa2througha7. Registera7may be used as a frame pointer. The register window is rotated 8 registers back upon return. When this version of the ABI is enabled, the C preprocessor symbol__XTENSA_WINDOWED_ABI__is defined. ๐ธ
๐ zSeries Options ๐
These are listed under
โจ ENVIRONMENT โจ
okay bestie, this whole section is the vibe check for the environment variables that change how GCC acts. Some of them work by specifying directories or prefixes to use when searching for various kinds of files. Some are used to specify other aspects of the compilation environment. we love a flexible queen ๐
Note: you can also specify places to search using options such as-B,-Iand-L. These take precedence over places specified using environment variables, which in turn take precedence over those specified by the configuration of GCC. periodt, hierarchy understood.
๐ LANG, LC_CTYPE, LC_MESSAGES, LC_ALL
These environment variables control the way that GCC uses localization information which allows GCC to work with different national conventions. GCC inspects the locale categories LC_CTYPE and LC_MESSAGES if it has been configured to do so. These locale categories can be set to any value supported by your installation. A typical value is en_GB.UTF-8 for English in the United Kingdom encoded in UTF-8. slay, international icon behavior ๐
LC_CTYPEโ specifies character classification. GCC uses it to determine the character boundaries in a string; this is needed for some multibyte encodings that contain quote and escape characters that are otherwise interpreted as a string end or escape. so specific, so necessary โจLC_MESSAGESโ specifies the language to use in diagnostic messages. she speaks your language, literally ๐ฌLC_ALLโ if set, it overrides the value ofLC_CTYPEandLC_MESSAGES; otherwise,LC_CTYPEandLC_MESSAGESdefault to the value of theLANGenvironment variable. If none of these variables are set, GCC defaults to traditional C English behavior. the ultimate override, no cap ๐
๐ TMPDIR
If TMPDIR is set, it specifies the directory to use for temporary files. GCC uses temporary files to hold the output of one stage of compilation which is to be used as input to the next stage: for example, the output of the preprocessor, which is the input to the compiler proper. temp files are the backstage pass of compilation ๐
๐ช GCC_COMPARE_DEBUG
Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. See the documentation of this option for more details. nearly equivalent, bestie, don't come for me ๐ฆ
๐งฌ GCC_EXEC_PREFIX
If GCC_EXEC_PREFIX is set, it specifies a prefix to use in the names of the subprograms executed by the compiler. No slash is added when this prefix is combined with the name of a subprogram, but you can specify a prefix that ends with a slash if you wish. choose your own prefix adventure ๐
If GCC_EXEC_PREFIX is not set, GCC attempts to figure out an appropriate prefix to use based on the pathname it is invoked with.
If GCC cannot find the subprogram using the specified prefix, it tries looking in the usual places for the subprogram.
The default value of GCC_EXEC_PREFIX is prefix/lib/gcc/ where prefix is the prefix to the installed compiler. In many cases prefix is the value of "prefix" when you ran the configure script.
Other prefixes specified with -B take precedence over this prefix.
This prefix is also used for finding files such as crt0.o that are used for linking.
In addition, the prefix is used in an unusual way in finding the directories to search for header files. For each of the standard directories whose name normally begins with /usr/local/lib/gcc (more precisely, with the value of GCC_INCLUDE_DIR), GCC tries replacing that beginning with the specified prefix to produce an alternate directory name. Thus, with -Bfoo/, GCC searches foo/bar just before it searches the standard directory /usr/local/lib/bar. If a standard directory begins with the configured prefix then the value of prefix is replaced by GCC_EXEC_PREFIX when looking for header files. the way this is so detailed and yet so chaotic ๐ญ
๐ฃ๏ธ COMPILER_PATH
The value of COMPILER_PATH is a colon-separated list of directories, much like PATH. GCC tries the directories thus specified when searching for subprograms, if it cannot find the subprograms using GCC_EXEC_PREFIX. path but make it compiler-core ๐ง
๐ LIBRARY_PATH
The value of LIBRARY_PATH is a colon-separated list of directories, much like PATH. When configured as a native compiler, GCC tries the directories thus specified when searching for special linker files, if it cannot find them using GCC_EXEC_PREFIX. Linking using GCC also uses these directories when searching for ordinary libraries for the -l option (but directories specified with -L come first). library girlies, this one's for you ๐
๐ฆ LANG
yes, LANG is back for round two โ she contains multitudes. This variable is used to pass locale information to the compiler. One way in which this information is used is to determine the character set to be used when character literals, string literals and comments are parsed in C and C++. When the compiler is configured to allow multibyte characters, the following values for LANG are recognized:
C-JISโ Recognize JIS characters. JIS said yesC-SJISโ Recognize SJIS characters. SJIS said yes tooC-EUCJPโ Recognize EUCJP characters. EUCJP completes the trio
If LANG is not defined, or if it has some other value, then the compiler uses "mblen" and "mbtowc" as defined by the default locale to recognize and translate multibyte characters. default locale fallback, she's reliable ๐
๐ฉบ GCC_EXTRA_DIAGNOSTIC_OUTPUT
If GCC_EXTRA_DIAGNOSTIC_OUTPUT is set to one of the following values, then additional text will be emitted to stderr when fix-it hints are emitted. -fdiagnostics-parseable-fixits and -fno-diagnostics-parseable-fixits take precedence over this environment variable. flags stay winning, bestie ๐ฅ
fixits-v1โ Emit parseable fix-it hints, equivalent to-fdiagnostics-parseable-fixits. In particular, columns are expressed as a count of bytes, starting at byte 1 for the initial column. bytes, not vibes ๐fixits-v2โ As"fixits-v1", but columns are expressed as display columns, as per-fdiagnostics-column-unit=display. glow up from v1 โจ
Some additional environment variables affect the behavior of the preprocessor.
๐ง CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH
Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon. semicolon vs colon, the eternal divide ๐
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed.
The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include. empty element, huge main character energy ๐
๐๏ธ DEPENDENCIES_OUTPUT
If this variable is set, its value specifies how to output dependencies for Make based on the non-system header files processed by the compiler. System header files are ignored in the dependency output. system headers, you're not invited to this party ๐
The value of DEPENDENCIES_OUTPUT can be just a file name, in which case the Make rules are written to that file, guessing the target name from the source file name. Or the value can have the form file target, in which case the rules are written to file file using target as the target name.
In other words, this environment variable is equivalent to combining the options -MM and -MF, with an optional -MT switch too. combo move, iconic ๐
โ๏ธ SUNPRO_DEPENDENCIES
This variable is the same as DEPENDENCIES_OUTPUT (see above), except that system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted. she's like DEPENDENCIES_OUTPUT but with a plot twist ๐ฆ
โณ SOURCE_DATE_EPOCH
If this variable is set, its value specifies a UNIX timestamp to be used in replacement of the current date and time in the __DATE__ and __TIME__ macros, so that the embedded timestamps become reproducible. reproducible builds, we love to see it ๐
The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00 represented in ASCII; identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command.
The value should be a known timestamp such as the last modification time of the source or package and it should be set by the build process. build process, do your thing ๐
๐ BUGS
For instructions on reporting bugs, see <file:///usr/share/doc/gcc-12/README.Bugs>. bugs? in MY compiler? it's more likely than you think ๐ญ
๐ FOOTNOTES
- On some systems,
gcc -sharedneeds to build supplementary stub code for constructors to work. On multi-libbed systems,gcc -sharedmust select the correct support libraries to link against. Failing to supply the correct flags may lead to subtle defects. Supplying them in cases where they are not necessary is innocuous. subtle defects are the worst kind, fr fr ๐
๐ SEE ALSO
gpl(7),gfdl(7),fsf-funding(7),cpp(1),gcov(1),as(1),ld(1),gdb(1),dbx(1)and the Info entries for gcc, cpp, as, ld, binutils and gdb. the whole friend group ๐ซถ
โ๏ธ AUTHOR
See the Info entry for gcc, or <https://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC. the contributors ate, periodt ๐
๐ COPYRIGHT
Copyright (c) 1988-2022 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the gfdl(7) man page. legal but make it cute ๐
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development.
and that's a wrap on GCC(1), bestie ๐
this page was gcc-12, dated 2024-07-11, and honestly? iconic. periodt. ๐โจ
๐ฆ where this page comes from
- ubuntu noble: g++-12-mipsisa32r6el-linux-gnu 12.4.0-2ubuntu1~24.04cross8
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms