GCC(1)
okay so real talk bestie โ this is the manual page for GCC(1), the GNU project C and C++ compiler, and it is iconic. It's also long, so buckle up, hydrate, and let's go. ๐
๐ธ NAME ๐ธ
gcc โ the GNU project C and C++ compiler. That's the whole name section. Short, sweet, main character energy. ๐
โจ SYNOPSIS โจ
gcc [-c|-S|-E] [-std=standard]
[-g] [-pg] [-Olevel]
[-Wwarn...] [-Wpedantic]
[-Idir...] [-Ldir...]
[-Dmacro[=defn]...] [-Umacro]
[-foption...] [-mmachine-option...]
[-o outfile] [@file] infile...
not me listing only the most useful options up there โ the rest of them are literally right below, keep scrolling, bestie. And heads up: g++ accepts mostly the same options as gcc. ๐ซถ
๐ DESCRIPTION ๐
So when you invoke GCC, it normally does preprocessing, compilation, assembly and linking. All four. In a row. Slay. โจ
The "overall options" let you stop that whole process at an intermediate stage. For example, the -c option says do not run the linker. And then what you get as output is object files output by the assembler. Cute, right?
Other options get passed on to one or more stages of processing. Some options control the preprocessor, others control the compiler itself. And yet other options control the assembler and the linker โ but most of those are not documented here, because honestly you rarely need to use any of them. ๐
Most of the command-line options 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. And if the description for a particular option doesn't mention a source language? Then you can use that option with all supported languages. Periodt. ๐
The usual way to run GCC is to run the executable called gcc, or machine-gcc when you're cross-compiling, or machine-gcc-version to run a specific version of GCC. And when you compile C++ programs, you should invoke GCC as g++ instead. iykyk. ๐
The gcc program accepts options and file names as operands. Now โ many options have multi-letter names, and therefore multiple single-letter options may not be grouped: -dv is very different from -d -v. Do not do the grouping thing. I'm serious. ๐ญ
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 with -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 gigibyte, and so on. Such arguments are designated by byte-size in the following text. And if you want the full listing and explanation of the binary and decimal byte size prefixes, go refer to the NIST, IEC, and other relevant national and international standards. ๐ (yes, the standards bodies. they ate.)
๐ OPTIONS ๐
๐ง Option Summary ๐ง
Here's the whole summary of all the options, grouped by type. The explanations live in the sections that follow. ๐ฆ
๐ 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-fgnu89-inline-fpermitted-flt-eval-methods=standard-aux-info filename-fallow-parameterless-variadic-functions-fno-asm-fno-builtin-fno-builtin-function-fgimple-fhosted-ffreestanding-fopenacc-fopenacc-dim=geom-fopenmp-fopenmp-simd-fms-extensions-fplan9-extensions-fsso-struct=endianness-fallow-single-precision-fcond-mismatch-flax-vector-conversions-fsigned-bitfields-fsigned-char-funsigned-bitfields-funsigned-char
๐ 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-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-Wno-mismatched-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
๐ Warning Options ๐
okay bestie, deep breath. this is the list. the one that goes on for so long your terminal scrollback gives up. every single one of these is a warning flag, and we're gonna walk through the whole roll call together, no skipping, no "eh you get the idea". you get all of it. ๐ซถ
๐ธ the opening acts ๐ธ
-fsyntax-only-fmax-errors=n-Wpedantic-pedantic-errors-w-Wextra-Wall
๐ฆ the a-through-b chapter ๐ฆ
-Wabi=n-Waddress-Wno-address-of-packed-member-Waggregate-return-Walloc-size-larger-than=byte-size-Walloc-zero-Walloca-Walloca-larger-than=byte-size-Wno-aggressive-loop-optimizations-Warith-conversion-Warray-bounds-Warray-bounds=n-Wno-attributes-Wattribute-alias=n-Wno-attribute-alias-Wno-attribute-warning-Wbool-compare-Wbool-operation-Wno-builtin-declaration-mismatch-Wno-builtin-macro-redefined
โจ the C and C++ compat girlies โจ
not me getting emotional over how many standards there are. every era gets its own flag, and honestly? iconic.
-Wc90-c99-compat-Wc99-c11-compat-Wc11-c2x-compat-Wc++-compat-Wc++11-compat-Wc++14-compat-Wc++17-compat-Wc++20-compat-Wcast-align-Wcast-align=strict-Wcast-function-type-Wcast-qual-Wchar-subscripts-Wclobbered-Wcomment-Wconversion-Wno-coverage-mismatch-Wno-cpp-Wdangling-else-Wdate-time
๐ the d-through-f saga ๐
-Wno-deprecated-Wno-deprecated-declarations-Wno-designated-init-Wdisabled-optimization-Wno-discarded-array-qualifiers-Wno-discarded-qualifiers-Wno-div-by-zero-Wdouble-promotion-Wduplicated-branches-Wduplicated-cond-Wempty-body-Wno-endif-labels-Wenum-compare-Wenum-conversion-Werror-Werror=*-Wexpansion-to-defined-Wfatal-errors-Wfloat-conversion-Wfloat-equal
bestie -Werror is right there in the middle of the list like it's not the single most plot-twist flag in the whole section. the audacity. ๐
๐ the format era ๐
-Wformat-Wformat=2-Wno-format-contains-nul-Wno-format-extra-args-Wformat-nonliteral-Wformat-overflow=n-Wformat-security-Wformat-signedness-Wformat-truncation=n-Wformat-y2k-Wframe-address-Wframe-larger-than=byte-size-Wno-free-nonheap-object-Wno-if-not-aligned-Wno-ignored-attributes-Wignored-qualifiers-Wno-incompatible-pointer-types-Wimplicit-Wimplicit-fallthrough-Wimplicit-fallthrough=n
๐ the i-through-m run ๐
-Wno-implicit-function-declaration-Wno-implicit-int-Winit-self-Winline-Wno-int-conversion-Wint-in-bool-context-Wno-int-to-pointer-cast-Wno-invalid-memory-model-Winvalid-pch-Wjump-misses-init-Wlarger-than=byte-size-Wlogical-not-parentheses-Wlogical-op-Wlong-long-Wno-lto-type-mismatch-Wmain-Wmaybe-uninitialized-Wmemset-elt-size-Wmemset-transposed-args-Wmisleading-indentation
๐ the missing-everything chapter ๐
look at all these -Wmissing- girlies. they're all just out here noticing what you forgot to write. supportive, honestly.
-Wmissing-attributes-Wmissing-braces-Wmissing-field-initializers-Wmissing-format-attribute-Wmissing-include-dirs-Wmissing-noreturn-Wno-missing-profile-Wno-multichar-Wmultistatement-macros-Wnonnull-Wnonnull-compare-Wnormalized=[none|id|nfc|nfkc]-Wnull-dereference-Wno-odr-Wopenmp-simd-Wno-overflow-Woverlength-strings-Wno-override-init-side-effects-Wpacked-Wno-packed-bitfield-compat
๐ง the p-through-s glow-up ๐ง
-Wpacked-not-aligned-Wpadded-Wparentheses-Wno-pedantic-ms-format-Wpointer-arith-Wno-pointer-compare-Wno-pointer-to-int-cast-Wno-pragmas-Wno-prio-ctor-dtor-Wredundant-decls-Wrestrict-Wno-return-local-addr-Wreturn-type-Wno-scalar-storage-order-Wsequence-point-Wshadow-Wshadow=global-Wshadow=local-Wshadow=compatible-local-Wno-shadow-ivar
๐ the shift/sizeof/sign situation ๐
-Wno-shift-count-negative-Wno-shift-count-overflow-Wshift-negative-value-Wno-shift-overflow-Wshift-overflow=n-Wsign-compare-Wsign-conversion-Wno-sizeof-array-argument-Wsizeof-array-div-Wsizeof-pointer-div-Wsizeof-pointer-memaccess-Wstack-protector-Wstack-usage=byte-size-Wstrict-aliasing-Wstrict-aliasing=n-Wstrict-overflow-Wstrict-overflow=n-Wstring-compare-Wno-stringop-overflow-Wno-stringop-overread
๐ the s-through-u finale ๐
-Wno-stringop-truncation-Wsuggest-attribute=[pure|const|noreturn|format|malloc]-Wswitch-Wno-switch-bool-Wswitch-default-Wswitch-enum-Wno-switch-outside-range-Wno-switch-unreachable-Wsync-nand-Wsystem-headers-Wtautological-compare-Wtrampolines-Wtrigraphs-Wtsan-Wtype-limits-Wundef-Wuninitialized-Wunknown-pragmas-Wunsuffixed-float-constants-Wunused
๐ the unused-and-beyond send-off ๐
and that's the whole warning roster. yes, all of it. we ate. ๐ฅ
-Wunused-but-set-parameter-Wunused-but-set-variable-Wunused-const-variable-Wunused-const-variable=n-Wunused-function-Wunused-label-Wunused-local-typedefs-Wunused-macros-Wunused-parameter-Wno-unused-result-Wunused-value-Wunused-variable-Wno-varargs-Wvariadic-macros-Wvector-operation-performance-Wvla-Wvla-larger-than=byte-size-Wno-vla-larger-than-Wvolatile-register-var-Wwrite-strings-Wzero-length-bounds
๐ฌ Static Analyzer Options ๐ฌ
next up: the static analyzer squad. these ones are the deep-dive girlies, the ones that actually sit down and read your whole program like it's a group chat they got added to late. ๐ต๏ธโโ๏ธ
๐ง the core analyzer flags ๐ง
-fanalyzer-fanalyzer-call-summaries-fanalyzer-checker=name-fno-analyzer-feasibility-fanalyzer-fine-grained-fanalyzer-state-merge-fanalyzer-state-purge-fanalyzer-transitivity-fanalyzer-verbose-edges-fanalyzer-verbose-state-changes-fanalyzer-verbosity=level
๐๏ธ the dump crew ๐๏ธ
-fdump-analyzer-fdump-analyzer-stderr-fdump-analyzer-callgraph-fdump-analyzer-exploded-graph-fdump-analyzer-exploded-nodes-fdump-analyzer-exploded-nodes-2-fdump-analyzer-exploded-nodes-3-fdump-analyzer-feasibility-fdump-analyzer-json-fdump-analyzer-state-purge-fdump-analyzer-supergraph
๐จ the analyzer warning list ๐จ
-Wno-analyzer-double-fclose-Wno-analyzer-double-free-Wno-analyzer-exposure-through-output-file-Wno-analyzer-file-leak-Wno-analyzer-free-of-non-heap-Wno-analyzer-malloc-leak-Wno-analyzer-mismatching-deallocation-Wno-analyzer-null-argument-Wno-analyzer-null-dereference-Wno-analyzer-possible-null-argument-Wno-analyzer-possible-null-dereference-Wno-analyzer-shift-count-negative-Wno-analyzer-shift-count-overflow-Wno-analyzer-stale-setjmp-buffer-Wno-analyzer-tainted-array-index-Wanalyzer-too-complex-Wno-analyzer-unsafe-call-within-signal-handler-Wno-analyzer-use-after-free-Wno-analyzer-use-of-pointer-in-stale-stack-frame-Wno-analyzer-use-of-uninitialized-value-Wno-analyzer-write-to-const-Wno-analyzer-write-to-string-literal
๐ C and Objective-C-only Warning Options ๐
these ones are for the C and Objective-C besties specifically. if that's not your language, no worries, scroll on. if it is? hi, this is your section. ๐
-Wbad-function-cast-Wmissing-declarations-Wmissing-parameter-type-Wmissing-prototypes-Wnested-externs-Wold-style-declaration-Wold-style-definition-Wstrict-prototypes-Wtraditional-Wtraditional-conversion-Wdeclaration-after-statement-Wpointer-sign
๐ Debugging Options ๐
and now the debugging section, aka the "what actually happened in my program" corner. -g girlies rise up. ๐ซก
๐ฌ the g-family basics ๐ฌ
-g-glevel-gdwarf-gdwarf-version-ggdb-grecord-gcc-switches-gno-record-gcc-switches-gstabs-gstabs+-gstrict-dwarf-gno-strict-dwarf
๐ the location-tracking era ๐
-gas-loc-support-gno-as-loc-support-gas-locview-support-gno-as-locview-support-gcolumn-info-gno-column-info-gdwarf32-gdwarf64-gstatement-frontiers-gno-statement-frontiers-gvariable-location-views-gno-variable-location-views-ginternal-reset-location-views-gno-internal-reset-location-views-ginline-points-gno-inline-points
๐๏ธ the other debug formats + compression ๐๏ธ
-gvms-gxcoff-gxcoff+-gz[=type]-gsplit-dwarf-gdescribe-dies-gno-describe-dies
๐ง the f-prefixed debug knobs ๐ง
-fdebug-prefix-map=old=new-fdebug-types-section-fno-eliminate-unused-debug-types-femit-struct-debug-baseonly-femit-struct-debug-reduced-femit-struct-debug-detailed[=spec-list]-fno-eliminate-unused-debug-symbols-femit-class-debug-always-fno-merge-debug-strings-fno-dwarf2-cfi-asm-fvar-tracking-fvar-tracking-assignments
โจ Optimization Options โจ
okay bestie, this is the optimization menu and it's literally a whole buffet of compiler glow-up flags. no cap, there are so many. Let's go through every single one, fr fr.
-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-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-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-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]-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-fthread-jumps-ftracer-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-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--param name=value-O-O0-O1-O2-O3-Os-Ofast-Og
๐ Program Instrumentation Options ๐
next up, instrumentation. this is where you spy on your program but in a cute way. ๐
-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]-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]-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,...
๐ธ Preprocessor Options ๐ธ
preprocessor time! it's giving 'before the main event' energy. ๐
-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 โจ
assembler options, short and sweet. โจ
-Wa,option-Xassembler option
๐ Linker Options ๐
<link>linker options, the final boss of building.</link> ๐
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 ๐บ๏ธ
directory options, for when you need to tell the compiler where stuff is. ๐บ๏ธ
-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 ๐ฅ
code generation options, this is where the magic happens. ๐ฅ
-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 ๐ง
developer options, for when you want to peek behind the curtain. ๐ง
-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 ๐โโ๏ธ
machine-dependent options, because every architecture is a little different.
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 if you're out here targeting Epiphany, this is your whole lil kit, bestie โ every single one of these, no skips:
-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
short, sweet, absolutely serving:
-march=gpu-mtune=gpu-mstack-size=bytes
๐ฆ ARC Options
ARC has so many of these it's giving encyclopedia, but we're listing all of them because that's the vibe ๐
-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-compactmlra-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
not me pointing out that mlra-priority-noncompact is sitting there with no dash, exactly as written, because we do not fix things around here ๐ซถ
๐ ARM Options
the ARM roster, iconic as always:
-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-munaligned-access-mneon-for-64bits-mslow-flash-data-masm-syntax-unified-mrestrict-it-mverbose-cost-dump-mpure-code-mcmse-mfix-cmse-cve-2021-35465-mfdpic
๐ AVR Options
tiny chip, big personality:
-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
this list is long long, but every single one is here, periodt:
-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
yes bestie,-sectobjectsymbols,-segs_read_only_addrand-segs_read_write_addreach show up twice in that list, and we're keeping both of each because that's literally what's written ๐ญ
๐ฆ 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
๐ง 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
๐ง 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
-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
-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
okay so this is the part where every CPU family on planet earth gets its own lil flag drop ๐ like a group chat where every member is a different architecture and they ALL want to talk. Same rules as always: every single flag is here, character for character, no cap. Don't @ me if you don't know what a MIPS is, you will by the end. ๐ฆ
๐ MIPS Options ๐
MIPS said "let me just list literally everything" and honestly? iconic. ๐
-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
-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 ๐
Knuth's lil baby architecture, we love to see it. โจ
-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 ๐
-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 ๐ฆ
tiny list, tiny architecture, big vibes.
-meb -mel -mmul.x -mno-crt0
๐ MSP430 Options ๐
the microcontroller bestie ๐
all those = flags are just waiting for you to fill in the blank.
-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 โญ
-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 ๐
-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 ๐ง
short and sweet, GPU girlies rise ๐ธ
-m64 -mmainkernel -moptimize
๐ OpenRISC 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
๐ PDP-11 Options ๐
vintage queen. the original. she was there first. ๐
-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 ๐ธ
-mae=ae_type
-mvliw-lookahead=N
-msymbol-as-address
-mno-inefficient-warnings
๐ PowerPC Options ๐
bestie this one is just a redirect, no cap: See RS/6000 and PowerPC Options. ๐
๐ฅ PRU Options ๐ฅ
-mmcu=mcu -minrt -mno-relax -mloop -mabi=variant
๐ซถ RISC-V Options ๐ซถ
open source royalty, she ate and left no crumbs โจ
-mbranch-cost=N-instruction
-mplt -mno-plt
-mabi=ABI-string
-mfdiv -mno-fdiv -mdiv -mno-div
-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 ๐
-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 โญ
the big one. the main character of this entire section, lowkey. look how long she is. ๐ญ
-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 ๐
-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 ๐ฆ
mainframe baddies, we see you ๐
-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 ๐
-meb -mel -mnhwloop -muls -mmac
-mscore5 -mscore5u -mscore7 -mscore7d
๐ธ SH Options ๐ธ
-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 ๐
-mclear-hwcap -mno-clear-hwcap
-mimpure-text -mno-impure-text
-pthreads
๐ฅ SPARC Options ๐ฅ
-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 โจ
short king energy.
-Qy -Qn -YP,paths -Ym,dir
๐ง TILE-Gx Options ๐ง
-mcpu=CPU -m32 -m64
-mbig-endian -mlittle-endian
-mcmodel=code-model
๐ TILEPro Options ๐
two whole flags, she's low maintenance, we stan ๐
-mcpu=cpu -m32
๐ฆ V850 Options ๐ฆ
bestie here's the whole V850 menu โ the manpage just drops the names and dips, no descriptions, no notes, so that's exactly what you're getting ๐
-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
๐ 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 ๐ฅ
okay so this is THE list, the main character of option lists, no cap. every single one of these is real and here they all are:
-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-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,-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,-mindirect-branch=choice,-mfunction-return=choice,-mindirect-branch-register,-mharden-sls=choice,-mindirect-branch-cs-prefix,-mneeded
๐ช 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 ๐
See S/390 and zSeries Options.
โจ Options Controlling the Kind of Output โจ
okay bestie, so a full compile is lowkey a four-stage glow-up and it ALWAYS goes in this order: preprocessing, then compilation proper, then assembly, then linking. no skipping ahead, no doing the steps out of order, the pipeline said what it said ๐
GCC can preprocess and compile a whole bunch of files either into a bunch of separate assembler input files, or into one single assembler input file. then each assembler input file spits out an object file, and linking takes all those object files โ the freshly compiled ones and the ones you handed in as input โ and smooshes them into one executable file. it's giving assembly line but make it iconic.
for any input file you give it, the file name suffix is what decides which kind of compilation happens:
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. heads up: you must link with thelibobjclibrary for an Objective-C program to actually work.file.miโ Objective-C source code that should not be preprocessed.file.mm,file.Mโ Objective-C++ source code. again: you must link with thelibobjclibrary for an Objective-C++ program to work. and yes,.Mmeans a literal capital M, not a vibe.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 (that's the default), or a C, C++ header file to be turned into an Ada spec (when you pass 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. in.cxxthe last two letters have to both be literallyx, and.Cis a literal capital C. the compiler is picky like that, and honestly? respect.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.brigโ BRIG files (binary representation of HSAIL).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). these files also go by specs.file.adbโ Ada source code file containing a library unit body (a subprogram or package body). these ones 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 gets treated this way.
and you can also just say what language it is 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
brig
-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, you tell gcc where to start with -x (or with filename suffixes), and then you tell it where to stop with one of -c, -S, or -E. and lowkey watch out: some combos instruct gcc to do absolutely nothing at all โ like -x cpp-output -E for example. do with that information what you will ๐
-cโ Compile or assemble the source files, but do not link. the linking stage simply does not happen. the ultimate output is 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 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 preprocessed source code, and it gets sent to the standard output.
Input files that don't require preprocessing are ignored.
-o fileโ Place the primary output in file. this applies to whatever sort of output is being produced โ executable file, object file, assembler file, preprocessed C code, doesn't matter, it's all going in there.
if -o is not specified, the default is to put an executable file in a.out, the object file for source.suffix in source.o, its assembler file in source.s, a precompiled header file in source.suffix.gch, and all preprocessed C source on standard output. slay.
okay so real talk about -o โ it names the primary output, yeah, but bestie it is so much more than that. It also runs the naming of your auxiliary outputs and your dump outputs. Peep the examples below. ๐
Unless something overrides it, both auxiliary outputs and dump outputs get dropped in the same directory as the primary output. The naming tea goes like this:
- In auxiliary outputs, the suffix of the input file gets swapped out for the suffix of the auxiliary 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 auxiliary and dump outputs is the base name 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 those two share the same base name (suffix not invited to the party), the result of the combination is that base name. Otherwise? They get concatenated, separated by a dash. Periodt.
So like, this:
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. Iconic behaviour honestly. โจ
But if you explicitly specify a non-linker output file, then aux and dump files by default take that 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 is different though โ it prefixes the aux and dump outputs instead:
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 and only exception to all of the above is when the executable shares its base name with the single input:
gcc foo.c -o dir/foo ...
in which case aux outputs get named dir/foo.* and dump outputs get named dir/foo.c.*. ๐ฆ
And if you wanna adjust the location and names of auxiliary and dump outputs yourself, the options -dumpbase, -dumpbase-ext, -dumpdir, -save-temps=cwd, and -save-temps=obj are your girls.
๐ธ -dumpbase dumpbase
This option sets the base name for auxiliary and dump output files. It does NOT touch the name of the primary output file, okay? Mind the boundaries. ๐ซถ
Intermediate outputs, when they're 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 save-foo.i, compiles to save-foo.s (now an intermediate, so like, an 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) get the input name suffix, and aux output files (those requested by other non-dump options, e.g. -save-temps, -gsplit-dwarf, -fcallgraph-info) get them without it. ๐
You can get that same suffix differentiation for dump and aux outputs with an explicitly-given -dumpbase basename.suf by also specifying -dumpbase-ext .suf.
If dumpbase is explicitly specified with any directory component, then any dumppfx specification (e.g. -dumpdir or -save-temps=*) gets 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. She said overriding, and she meant it. ๐
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. Sneaky but slay.
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 the trailing auxdropsuf from dumpbase before appending any suffixes. If it's not specified, this option defaults to the suffix of a default dumpbase โ i.e. the suffix of the input file when -dumpbase is not present in the command line, or dumpbase is combined with dumppfx.
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 doesn't 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, use dumppfx as 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. The options -save-temps=cwd and -save-temps=obj override this default, just like an explicit -dumpdir option does. And 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 an 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. Now contrast that with the single-input compilation:
gcc foo.c -c -dumpdir dir/pfx- -dumpbase main ...
which, 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 that 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 here 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 the 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 are named foo.*, and dump outputs foo.c.*, in the current working directory as ultimately requested by -save-temps=cwd. ๐
okay bestie, let's wrap our heads around this dump data flow because it's giving organized chaos โจ. So picture it: the primary output name gets split 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 -dumpbase overrides it. If you've got multiple inputs or you're linking, this dumpbase can get combined with dumppfx and taken from each input file. Auxiliary output names for each input? They're made by combining dumppfx, dumpbase minus its suffix, and the auxiliary output suffix; dump output names are only different because they keep the suffix from dumpbase. periodt ๐
Now when auxiliary and dump outputs get created during LTO recompilation, a combo of dumppfx and dumpbaseโeither as given or derived from the linker output name but not from inputs, even in cases where that combo wouldn't normally be used that wayโgets passed down with a trailing period replacing the compiler-added dash (if there was one) as a -dumpdir option to lto-wrapper. And because lto-wrapper is involved in linking, it doesn't normally get any -dumpbase and -dumpbase-ext, and it straight-up ignores them. so real ๐
When it runs sub-compilers, lto-wrapper appends LTO stage names to the dumppfx it received, makes sure it contains a directory component so it overrides any -dumpdir, and passes that as -dumpbase to the sub-compilers. slay ๐ฆ
-vโ print (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. the receipts, bestie ๐-###โ like-vexcept the commands are not executed and arguments are quoted unless they contain only alphanumeric characters or"./-_". This is useful for shell scripts to capture the driver-generated command lines. script girlies, this one's for you ๐--helpโ print (on the standard output) a description of the command-line options understood bygcc. If the-voption is also specified then--helpis also passed on to the various processes invoked bygcc, so that they can display the command-line options they accept. If the-Wextraoption has also been specified (prior to the--helpoption), then command-line options that have no documentation associated with them are also displayed. the ultimate flag glow-up ๐--target-helpโ print (on the standard output) a description of target-specific command-line options for each tool. For some targets extra target-specific information may also be printed. niche but necessary โจ--help={class|[^]qualifier}[,...]โ print (on the standard output) a description of the command-line options understood by the compiler that fit into all specified classes and qualifiers. These 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 however, target-specific options of the linker and assembler are not displayed. This is because those tools do not 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, one needs to selectcommonclass.commonโ display the options that are common to all languages.
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, such as:--help=target.separateโ display options taking an argument that appears as a separate word following the original option, such as:-o output-file.
Thus for example to display all the undocumented target-specific switches supported by the compiler, use:
--help=target,undocumented
The sense of a qualifier can be inverted 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 do not take an argument) that have a description, use:
--help=warnings,^joined,^undocumented
The argument to --help= should not consist solely of inverted qualifiers. periodt ๐
Combining several classes is possible, although this usually restricts the output so much that there is nothing to display. One case where it does work, however, 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. If --help is also specified anywhere on the command line then this 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= is changed. Instead of describing the displayed options, an indication is given as to whether the option is enabled, disabled or set to a specific value (assuming that the compiler knows this at the point where the --help= option is used).
Here is 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 it is possible to 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
--versionโ display the version number and copyrights of the invoked GCC. the classic "who dis?" but make it legal ๐-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. dramatic but useful ๐-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. iconic behavior, honestly ๐-specs=fileโ process file after the compiler reads in the standard specs file, in order to override the defaults which 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 are processed in order, from left to right. left to right, no skipping โจ-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, thus the invocation of cc1 is gdb --args cc1 .... backstage pass for your debugger ๐๏ธ
-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-mapand-fdebug-prefix-map. reproducible build queen ๐-fplugin=name.soโ load the plugin code in file name.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. plug in, bestie ๐-fplugin-arg-name-key=valueโ define an argument called key with a value of value for the plugin called name. passing notes in class, but for plugins ๐-fdump-ada-spec[-slim]โ for C and C++ source and include files, generate corresponding Ada specs. Ada girlies, rise ๐-fada-spec-parent=unitโ in conjunction with-fdump-ada-spec[-slim]above, generate Ada specs as child units of parent unit. family tree but make it Ada ๐ณ-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. Go off, then ๐น@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. recursive, like your fave playlist ๐
๐ 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 yes, you can still call it gcc and it'll know ๐
However, the use of gcc does not add the C++ library. g++ is 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. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations. 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. like, pick your fighter bestie ๐ซถ
โจ 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. rip to your little niceties, honestly
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. she's chill until you ask her to be strict, love that for her
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. she keeps receipts on which extensions are legal, periodt
A value for this option must be provided; possible values are
c90,c89,iso9899: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.c99,c9x,iso9899:1999,iso9899: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 <http://gcc.gnu.org/c99status.html> for more information. The namesc9xandiso9899:199xare deprecated.c11,c1x,iso9899: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.c17,c18,iso9899:2017,iso9899: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. ๐gnu90,gnu89โ GNU dialect of ISO C90 (including some C99 features).gnu99,gnu9xโ GNU dialect of ISO C99. The namegnu9xis deprecated.gnu11,gnu1xโ GNU dialect of ISO C11. The namegnu1xis deprecated.gnu17,gnu18โ 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++98,c++03โ The 1998 ISO C++ standard plus the 2003 technical corrigendum and some additional defect reports. Same as-ansifor C++ code.gnu++98,gnu++03โ GNU dialect of-std=c++98.c++11,c++0xโ The 2011 ISO C++ standard plus amendments. The namec++0xis deprecated.gnu++11,gnu++0xโ GNU dialect of-std=c++11. The namegnu++0xis deprecated.c++14,c++1yโ The 2014 ISO C++ standard plus amendments. The namec++1yis deprecated.gnu++14,gnu++1yโ GNU dialect of-std=c++14. The namegnu++1yis deprecated.c++17,c++1zโ The 2017 ISO C++ standard plus amendments. The namec++1zis deprecated.gnu++17,gnu++1zโ GNU dialect of-std=c++17. This is the default for C++ code. The namegnu++1zis deprecated. ๐c++20,c++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++20,gnu++2aโ GNU dialect of-std=c++20. Support is experimental, and could change in incompatible ways in future releases. The namegnu++2ais deprecated.c++2b,c++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. fr fr do not build your whole life on this onegnu++2b,gnu++23โ GNU dialect of-std=c++2b. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
-fgnu89-inline
The option -fgnu89-inline tells GCC to use the traditional GNU semantics for inline functions when in C99 mode.
Using this option 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.
-fpermitted-flt-eval-methods=style
ISO/IEC TS 18661-3 defines new permissible values for FLT_EVAL_METHOD that 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 of FLT_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.
-aux-info filename
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. she simply does not hear you unless you're speaking C, and honestly? valid
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++. C++ said "already legal bestie" and walked off ๐
-fno-asmโ okay so do NOT treatasm,inlineortypeofas keywords, so your code can totally use those words as identifiers. Instead you can use__asm__,__inline__and__typeof__. And just so you know,-ansiimplies-fno-asm. ๐
In C++, this switch only affects the typeof keyword, because asm and inline are standard keywords. You might wanna use -fno-gnu-keywords instead โ same effect, different vibe. And 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. big mood, but also big tradeoff. 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-function option only the built-in function function is disabled. function must not begin with __builtin_. If a function is named that is not built-in in this version of GCC, this option is ignored. There is no corresponding -fbuiltin-function option; if you wish to enable built-in functions selectively when using -fno-builtin or -ffreestanding, you may define macros such as:
#define abs(n) __builtin_abs ((n))
#define strcpy(d, s) __builtin_strcpy ((d), (s))
-fgimpleโ Enable parsing of function definitions marked with__GIMPLE. This is an experimental feature that allows unit testing of GIMPLE passes. ๐งช experimental, bestie!-fhostedโ Assert that compilation targets a hosted environment. This implies-fbuiltin. A hosted environment is one in which the entire standard library is available, and in whichmainhas a return type ofint. Examples are nearly everything except a kernel. This is equivalent to-fno-freestanding. ๐-ffreestandingโ Assert that compilation targets a freestanding environment. This implies-fno-builtin. A freestanding environment is one in which the standard library may not exist, and program startup may not necessarily be atmain. The most obvious example is an OS kernel. This is equivalent to-fno-hosted. ๐ง-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 do not 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. โจ-fgnu-tmโ When the option-fgnu-tmis specified, the compiler generates code for the Linux variant of Intel's current Transactional Memory ABI specification document (Revision 1.1, May 6 2009). This is an experimental feature whose interface may change in future versions of GCC, as the official specification changes. Please note that not all architectures are supported for this feature. ๐งช
For more information on GCC's support for transactional memory,
Note that the transactional memory feature is not supported with non-call exceptions (-fnon-call-exceptions). ๐
-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 types declarations.
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. ๐
-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++. ๐
-fcond-mismatchโ Allow conditional expressions with mismatched types in the second and third arguments. The value of such an expression is void. This option is not supported for C++. ๐ญ-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. do not use for new code, bestie! ๐ซ-funsigned-charโ Let the typecharbe unsigned, likeunsigned char. ๐ธ
Each kind of machine has a default for what char should be. It is 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 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. ๐
-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-char is equivalent to -funsigned-char. ๐
-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. ๐-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 โจ
This section 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, which first appeared in G++ 4.5, implements a standard mangling for vector types.
Version 5, which 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, which 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, which 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, which first appeared in G++ 4.9, corrects the substitution behavior of function types with function-cv-qualifiers.
Version 9, which first appeared in G++ 5.2, corrects the alignment of nullptr_t.
Version 10, which 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, which first showed up in G++ 7, fixes the mangling of sizeof... expressions and operator names. And for multiple entities with the same name inside 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, which 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. But oopsie โ it accidentally changes the calling convention for classes with a deleted copy constructor and a trivial move constructor. ๐
Version 13, which first appeared in G++ 8.2, fixes that accidental change from version 12. We love a redemption arc. ๐ซถ
Version 14, which first appeared in G++ 10, corrects the mangling of the nullptr expression.
Version 15, which first appeared in G++ 11, changes the mangling of "__alignof__" so it's distinct from that of "alignof", plus 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 whenever it's defining a symbol with an incorrect mangled name. This switch tells it which ABI version to use for that alias.
With -fabi-version=0 (the default), this defaults to 11 (that's GCC 7 compatibility, bestie). If another ABI version is explicitly selected, this defaults to 0. And if you need compatibility with GCC versions 3.2 through 4.9, use -fabi-compat-version=2.
If you don't provide this option but you do pass -Wabi=n, that version gets used for the compatibility aliases. If you provide this option alongside -Wabi (without the version), then the version from this option is used for the warning. Slay, it all just works out. ๐
-fno-access-controlโ turns off all access checking. This switch is mainly useful for working around bugs in the access control code. (iykyk, sometimes you just gotta โ๏ธ past the bouncer.)-faligned-newโ enables support for C++17newof types that need more alignment than"void* ::operator new(std::size_t)"provides. You can pass a numeric argument like-faligned-new=32to specify how much alignment (in bytes) that function provides, but honestly few users will ever need to override the default ofalignof(std::max_align_t).
This flag is on by default for -std=c++17. ๐
-fchar8_t-fno-char8_tโ enables support for"char8_t"as adopted for C++20. That means a whole new"char8_t"fundamental 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_t"and"__cpp_lib_char8_t"feature test macros. She's got range. ๐
This option lets functions 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 it 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. Like, 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
๐ญ the errors really said "not today."
-fcheck-newโ check that the pointer returned by"operator new"is non-null before trying to modify the storage that was allocated. This check is normally unnecessary, because the C++ standard says"operator new"only returns 0 if it's declaredthrow(), and in that case the compiler always checks the return value even without this option. In all the other cases, when"operator new"has a non-empty exception specification, memory exhaustion is signalled by throwing"std::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 heads up bestie โ the standard spec 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 with -fconcepts-ts. ๐ฆ
-fconstexpr-depth=nโ set the maximum nested evaluation depth for C++11 constexpr functions to n. A limit is needed so we can 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 to n. It's a heuristic that trades off compilation speed (when the cache avoids repeated calculations) against memory consumption (when the cache grows super large from highly recursive evaluations). The default is 8. Very few users are likely to want to touch it, but if your code does heavy constexpr calculations you might want to experiment and find which value vibes best for you. โจ-fconstexpr-loop-limit=nโ set the maximum number of iterations for a loop in C++14 constexpr functions to n. 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 the 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 the body of some loop, or even outside of a loop, too many expressions need to be evaluated โ the resulting constexpr evaluation might take way 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's 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 makes G++ 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. no cap. ๐
-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 it may be useful for reducing code size in production builds, a lot like defining"NDEBUG".
โ ๏ธ 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โ the C++11 and OpenMP standards allow"thread_local"and"threadprivate"variables to have dynamic (runtime) initialization. To support that, any use of such a variable goes through a wrapper function that performs whatever initialization is necessary. When the use and 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's significant overhead even if the variable doesn't actually need dynamic initialization. If 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), they 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.
-fno-gnu-keywordsโ don't recognize"typeof"as 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.-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, or you'll get undefined symbols at link time. ๐ญ
-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, don't emit out-of-line copies of inline functions controlled by"#pragma implementation".
โ ๏ธ This causes linker errors if these functions aren't inlined everywhere they're called.
-fmodules-ts-fno-modules-tsโ enable support for C++20 modules. The-fno-modules-tsis usually not needed, as that's the default. And even though this is a C++20 feature, it is not currently implicitly enabled by selecting that standard version. ๐-fmodule-header,-fmodule-header=user,-fmodule-header=systemโ bestie, this compiles a header file so it becomes an importable header unit. That's the whole job. ๐-fmodule-implicit-inlineโ so member functions that get defined right inside their class definitions are normally not implicitly inline when you're doing modular code. That's a deliberate choice and it's different from classic C++ behaviour, for good reasons. But it can make porting code a whole thing ๐ญ. This flag makes those function definitions implicitly inline anyway. Big caveat though: it generates an ABI incompatibility, so you have to use it everywhere or nowhere โ no halfsies. (And fyi, definitions like that outside of a named module stay implicitly inline regardless, so don't worry about those.) ๐-fno-module-lazyโ turns off lazy module importing and module mapper creation. Done and dusted.-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]โ this is your oracle โจ, i.e. the thing you query to map module names onto filenames. If you don't specify it, theCXX_MODULE_MAPPERenvironment variable gets used instead, and if that isn't set either, you get an in-process default. The vibes are: something's always handling it. ๐ฆ-fmodule-onlyโ only emit the Compiled Module Interface, and inhibit any object file. Just the CMI, nothing else, periodt.-fms-extensionsโ silencesWpedanticwarnings about constructs used in MFC, like implicitintand grabbing a pointer to a member function via non-standard syntax. MFC girlies, this one's for you ๐ซถ-fnew-inheriting-ctorsโ enables the P0136 adjustment to how C++11 constructor inheritance behaves. It's part of C++17, but it's also considered a Defect Report against C++11 and C++14. On by default unless you've specified-fabi-version=10or lower. โญ-fnew-ttp-matchingโ enables the P0522 resolution to Core issue 150, all about template template parameters and default arguments: it lets a template with default template arguments be used as an argument for a template template parameter that has fewer template parameters. Enabled by default for-std=c++17. ๐-fno-nonansi-builtinsโ kills the built-in declarations of functions that ANSI/ISO C doesn't mandate. That list includesffs,alloca,_exit,index,bzero,conjf, and other related functions. Bye besties ๐-fnothrow-optโ treats athrow()exception specification as if it were anoexceptspecification, which reduces or eliminates the text size overhead compared to a function with no exception spec at all. And plot twist: if the function has local variables whose types have non-trivial destructors, the exception spec actually makes the function smaller, because the EH cleanups for those variables can be optimized away. Semantically, this means an exception thrown out of a function with such a spec results in a call toterminaterather thanunexpected. Noted. ๐-fno-operator-namesโ do not treat the operator name keywordsand,bitand,bitor,compl,not,orandxoras synonyms for keywords. They're just words now, fr fr.-fno-optional-diagsโ disables diagnostics that the standard says a compiler doesn't need to issue. Currently the only such diagnostic G++ issues is the one for a name having multiple meanings within a class. That's it. The whole list. ๐ญ-fpermissiveโ downgrades some diagnostics about nonconformant code from errors to warnings. So yeah, using-fpermissivelets some nonconforming code actually compile. You're on your own with it though ๐-fno-pretty-templatesโ okay so normally, when an error message refers to a specialization of a function template, the compiler prints the signature of the template followed by the template arguments and any typedefs or typenames in the signature (likevoid f(T) [with T = int]rather thanvoid f(int)) so it's clear which template is involved. And when an error message refers to a specialization of a class template, the compiler omits any template arguments that match that template's default template arguments. If either of those behaviours makes the error message harder to read instead of easier, use-fno-pretty-templatesto turn them off. ๐ง-fno-rttiโ disables generating information about every class with virtual functions, the info the C++ run-time type identification features use (dynamic_castandtypeid). If you don't use those parts of the language, you can save some space with this flag. Note that exception handling uses the same information, but G++ generates it as needed. Also, thedynamic_castoperator can still be used for casts that don't require run-time type information, i.e. casts tovoid *or to unambiguous base classes.
Mixing code compiled with -frtti and code compiled with -fno-rtti may not work. Like, programs may fail to link if a class compiled with -fno-rtti is used as a base for a class compiled with -frtti. So... don't mix, bestie ๐
-fsized-deallocationโ enables 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. And the flag -Wsized-deallocation warns about places that might want to add a definition. ๐
-fstrict-enumsโ lets the compiler optimize on 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). Heads up: that assumption may not be valid if the program uses a cast to convert an arbitrary integer value to the enumerated type. So like, careful. โ ๏ธ-fstrong-eval-orderโ evaluates member access, array subscripting, and shift expressions in left-to-right order, and evaluates assignment in right-to-left order, as adopted for C++17. Enabled by default with-std=c++17. Meanwhile-fstrong-eval-order=someenables just the ordering of member access and shift expressions, and that one is the default without-std=c++17. Slay, order matters ๐-ftemplate-backtrace-limit=nโ sets the max number of template instantiation notes for a single warning or error to n. The default value is10. ๐-ftemplate-depth=nโ sets the maximum instantiation depth for template classes to n. You need a limit on template instantiation depth 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, because the compiler can run out of stack space before hitting1024in some situations. ๐-fno-threadsafe-staticsโ don't emit the extra code that uses the routines specified in the C++ ABI for thread-safe initialization of local statics. You can use this to shave off a bit of code size in code that doesn't need to be thread-safe. Lowkey a size optimization, highkey a "do you actually need this" question. ๐ธ-fuse-cxa-atexitโ registers 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 it only works if your C library supports__cxa_atexit. So check that first ๐ซถ-fno-use-cxa-get-exception-ptrโ don't use the__cxa_get_exception_ptrruntime routine. This causesstd::uncaught_exceptionto be incorrect, but it's necessary if that runtime routine isn't available. Trade-off city ๐ญ-fvisibility-inlines-hiddenโ this switch declares that the user doesn't attempt to compare pointers to inline functions or methods where the addresses of the two functions are taken in different shared objects.
What that means in practice: GCC may effectively mark inline methods with __attribute__ ((visibility ("hidden"))), so they don't show up in a DSO's export table and don't need a PLT indirection when used inside the DSO. Enabling this can have a dramatic effect on a DSO's load and link times, because it massively shrinks the dynamic export table when the library makes heavy use of templates. Iconic honestly โจ
But heads up: the behaviour isn't quite the same as marking the methods hidden directly, because it doesn't affect static variables local to the function, and it doesn't cause the compiler to deduce that the function is defined in only one shared object.
You can mark a method as having visibility explicitly to negate the effect of the switch for that one method. For example, if you do want to compare pointers to a particular inline method, you might mark it as having default visibility. Marking the enclosing class with explicit visibility has no effect, though. And 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. ๐
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.
In new code it's better to use -fvisibility=hidden and export the classes you actually intend to be externally visible. Unfortunately it's possible for code to rely โ maybe accidentally โ on the Visual Studio behaviour. ๐
Among the consequences: static data members of the same type with the same name but defined in different shared objects are different, so changing one doesn't change the other; and pointers to function members defined in different shared objects may not compare equal. And when this flag is given, it's a violation of the ODR to define types with the same name differently. Yeah. Read that twice. ๐
-fno-weakโ don't use weak symbol support, even if the linker provides it. By default G++ uses weak symbols if they're available. But listen: this option exists only for testing, and end-users should not use it; it results in inferior code and has no benefits. It may be removed in a future release of G++. So like, hands off bestie ๐ซ
-fext-numeric-literals(C++ and Objective-C++ only) โ bestie, this one lets you accept imaginary, fixed-point, or machine-defined literal number suffixes as GNU extensions. Turn it off and those suffixes get treated as C++11 user-defined literal numeric suffixes instead. It's 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++โ do not 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.) ๐-flang-info-include-translate,-flang-info-include-translate-not,-flang-info-include-translate=headerโ these three are the include-translation gossip girls ๐ฃ๏ธ. They inform you 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 allows specification of 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 ๐ญ. However, a comma expression wrapped in( )is not deprecated. Example:
void f(int *a, int b, int c) {
a[b,c]; // deprecated
a[(b,c)]; // OK
}
Enabled by default with -std=c++20.
-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 will point 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 whendeleteis used to destroy an instance of a class that has virtual functions and 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. 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 ofstd::initializer_listthat are likely to result in dangling pointers ๐ฑ. Since the underlying array for aninitializer_listis 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 localinitializer_listvariable, 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 theinitializer_listin the heap has a dangling pointer. - When an
initializer_listvariable is assigned from a brace-enclosed initializer list, the temporary array created for the right side of the assignment only lives until the end of the full-expression, so at the next statement theinitializer_listvariable has a dangling pointer.
- If a function returns a temporary
// 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, this doesn't extend the lifetime of the array, so if a class variable is constructed from a temporaryinitializer_list, the pointer is left dangling by the end of the variable declaration statement.
-Winvalid-imported-macrosโ verify all imported macro definitions are valid at the end of compilation ๐ง. This is not enabled by default, as it requires additional processing to determine. It may be useful when preparing sets of header-units to ensure consistent macros.-Wno-literal-suffix(C++ and Objective-C++ only) โ do not warn when a string or character literal is followed by a ud-suffix which does not begin with an underscore ๐ธ. As a conforming extension, GCC treats such suffixes as separate preprocessing tokens in order to maintain backwards compatibility with code that uses formatting macros from<inttypes.h>. 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.
This option also controls warnings 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 are diagnosed by default, as required by the standard ๐. 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 makingnoexceptpart 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>.
-Wclass-memaccess</p> (C++ and Objective-C++ only)
okay so this one is giving โ stop right there energy. It yells at you when the destination of a call to a raw memory function like memset or memcpy is an object of class type, and when writing into that object might:
- bypass the class's 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 to memset below is undefined because it modifies a non-trivial class object and is, therefore, diagnosed:
std::string str = "abc";
memset (&str, 0, sizeof str);
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. bestie, please just use the constructor ๐
-Wclass-memaccess is enabled by -Wall. And if you really know what you're doing, 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</p> (C++ and Objective-C++ only)
Warns when a class has virtual functions and an accessible non-virtual destructor โ either in 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 the base class. it's giving "works on my machine until it doesn't" ๐
This warning is automatically enabled if -Weffc++ is specified.
-Wregister</p> (C++ and Objective-C++ only)
Warns on uses of the register storage class specifier โ except when it's part of the GNU Explicit Register Variables extension. The use of the register keyword as a storage class specifier has been deprecated in C++11 and removed in C++17. Enabled by default with -std=c++17. she's old, she's retired, let her rest ๐ซถ
-Wreorder</p> (C++ and Objective-C++ only)
Warns 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. your init list order is a vibe check the compiler does NOT let you skip ๐ญ
-Wno-pessimizing-move</p> (C++ and Objective-C++ only)
This warning warns when a call to std::move prevents 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. not you sabotaging your own optimization bestie ๐ญ
This warning is enabled by -Wall.
-Wno-redundant-move</p> (C++ and Objective-C++ only)
This warning warns about redundant calls to std::move โ that is, when a move operation would have been performed even without the std::move call. 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</p> (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. tiny copies get a pass, big ones get read ๐
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. every. single. iteration. ๐
This warning is enabled by -Wall.
-Wredundant-tags</p> (C++ and Objective-C++ only)
Warns 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
context is everything, the keyword stays when it has to ๐
-Wno-subobject-linkage</p> (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 .C file, as those are unlikely to have multiple definitions. -Wsubobject-linkage is enabled by default.
-Weffc++</p> (C++ and Objective-C++ only)
Warns about violations of the following style guidelines from Scott Meyers' Effective C++ series of books:
- Define a copy constructor and an assignment operator for classes with dynamically-allocated memory.
- Prefer initialization to assignment in constructors.
- Have
operator=return a reference to*this. - Don't try to return a reference when you must return an object.
- Distinguish between prefix and postfix forms of increment and decrement operators.
- Never overload
&&,||, or,.
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 selecting this option, be aware that the standard library headers do not obey all of these guidelines; use grep -v to filter out those warnings. the STL is not passing Scott Meyers' vibe check and that's just how it is ๐
-Wno-exceptions</p> (C++ and Objective-C++ only)
Disable the warning about the case when an exception handler is shadowed by another handler, which can point out a wrong ordering of exception handlers. catch blocks are read top to bottom, bestie, order matters ๐ซถ
-Wstrict-null-sentinel</p> (C++ and Objective-C++ only)
Warns about the use of an uncasted NULL as sentinel. When compiling only with GCC this is a valid sentinel, as NULL is defined to __null. Although it is a null pointer constant rather than a null pointer, it is guaranteed to be of the same size as a pointer. But this use is not portable across different compilers. works here, breaks everywhere else, classic ๐
-Wno-non-template-friend</p> (C++ and Objective-C++ only)
Disable warnings when non-template friend functions are declared within a template. In very old versions of GCC that predate implementation of the ISO standard, declarations such as friend 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 is enabled by default. legacy lore, iykyk ๐
-Wold-style-cast</p> (C++ and Objective-C++ only)
Warns if an old-style (C-style) cast to a non-void type is used within a C++ program. The new-style casts (dynamic_cast, static_cast, reinterpret_cast, and const_cast) are less vulnerable to unintended effects and much easier to search for. glow up your casts, bestie โจ
-Woverloaded-virtual</p> (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. not the signature change sneak attack ๐ญ
-Wno-pmf-conversions</p> (C++ and Objective-C++ only)
Disable the diagnostic for converting a bound pointer to member function to a plain pointer.
-Wsign-promo</p> (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 "we're doing it this way now" and that's that periodt ๐
-Wtemplates</p> (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. so you can still live your STL fantasy, just no declaring your own ๐
-Wno-mismatched-new-delete<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ bestie, this one yells at you when youroperator newandoperator deletecalls don't match up with their allocation/deallocation buddy. That includes calling C++operator deleteon pointers that came from a mismatched form ofoperator new, or from other functions that allocate objects whereoperator deletejust isn't the right deallocator. Also flags calls to other deallocation functions on pointers returned fromoperator newwhen the deallocation function isn't suitable. ๐
Like, check this โ the delete in this function gets diagnosed because it doesn't match the array form of the new the pointer came from. And the free call gets flagged too:
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 catches mismatches involving allocation and deallocation functions that aren't operator new and operator delete.
<span style="color:mint">-Wmismatched-new-delete is enabled by default.</span> โจ
-Wmismatched-tags<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns you when structs, classes, class templates and their specializations get declared with a class-key that doesn't match either the definition or the first declaration (if there's no definition). ๐
For example, the declaration of struct Object in the argument list of draw triggers the warning. To dodge it, either yeet the redundant struct class-key or swap it for class to match its definition:
class Object {
public:
virtual ~Object () = 0;
};
void draw (struct Object*);
It's not actually wrong to declare a class with the struct class-key like the example above shows. The -Wmismatched-tags option is just here to help you get a consistent style of class declarations. In code meant to be portable to Windows-based compilers, the warning helps prevent unresolved references from the difference in symbol mangling when declared with different class-keys. You can use it on its own or together with -Wredundant-tags. ๐ฆ
-Wmultiple-inheritance<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns when a class is defined with multiple direct base classes. Some coding rules are like "no multiple inheritance" and this can enforce that rule. The warning is inactive inside a system header file, like the STL, so you can still use the STL. You can also define classes that indirectly use multiple inheritance. ๐-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 you can still use the STL. You 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. <span style="color:red">This is dangerous</span> because if the virtual base is reachable along more than one path, it gets 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, you can disable this warning. ๐-Wnamespacesโ warns when a namespace definition is opened. Some coding rules disallow namespaces, and this can enforce that rule. The warning is inactive inside a system header file, such as the STL, so you can still use the STL. You can also use using directives and qualified names. โจ-Wno-terminate<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ disables the warning about a throw-expression that will immediately result in a call toterminate. ๐ญ-Wno-vexing-parse<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns about the most vexing parse syntactic ambiguity. This flags the cases where 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 for how to deal with such an ambiguity; like, it can suggest removing the parentheses or using braces instead.
<span style="color:mint">This warning is enabled by default.</span> ๐
-Wno-class-conversion<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ 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 literally never be called. ๐-Wvolatile<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ 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. ๐ซถ
<span style="color:mint">Enabled by default with -std=c++20.</span>
-Wzero-as-null-pointer-constant<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns when a literal0is used as a null pointer constant. This can be useful to help with converting tonullptrin C++11. โญ-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, like constructing an object in a buffer that's 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];
<span style="color:mint">This warning is enabled by default.</span>
-Wplacement-new=1โ 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. For example, the followingnewexpression 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โ at this level, in addition to 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. While the previous example would be diagnosed, the following construct makes use of the flexible member array extension to avoid 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<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns about catch handlers that don't catch via reference. With-Wcatch-value=1(or just-Wcatch-valuefor short) it warns about polymorphic class types that are caught by value. With-Wcatch-value=2it warns about all class types caught by value. With-Wcatch-value=3it warns about all types that are not caught by reference.-Wcatch-valueis enabled by-Wall. ๐-Wconditionally-supported<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns for conditionally-supported (C++11 [intro.defs]) constructs. ๐-Wno-delete-incomplete<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ do not warn when deleting a pointer to an incomplete type, which may cause undefined behavior at runtime. <span style="color:mint">This warning is enabled by default.</span> ๐-Wextra-semi<span style="color:hotpink">(C++, Objective-C++ only)</span> โ warns about redundant semicolons after in-class function definitions. ๐ฅ-Wno-inaccessible-base<span style="color:hotpink">(C++, Objective-C++ only)</span> โ this option controls warnings when a base class is inaccessible in a class derived from it due to ambiguity. <span style="color:mint">The warning is enabled by default.</span> 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<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ 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, though,offsetoftypically gives meaningful results. This flag is for users who are aware that they're 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. ๐
-Wsized-deallocation<span style="color:hotpink">(C++ and Objective-C++ only)</span> โ warns about a definition of an unsized deallocation function
void operator delete (void *) noexcept;
void operator delete[] (void *) noexcept;
...but there's no definition of the matching sized deallocation function
void operator delete (void *, std::size_t) noexcept;
void operator delete[] (void *, std::size_t) noexcept;
...or the other way round. Turned on by -Wextra, chillin' right alongside -fsized-deallocation. โจ
-Wsuggest-final-typesโ bestie, if a type has virtual methods and it would be so much better as a C++11finaltype (or maybe tucked into an anonymous namespace), GCC will gently tell you. Why do we care? Because that lets GCC go full beast mode and devirtualize the polymorphic calls ๐ This warning hits different with link-time optimization, where the whole class hierarchy graph is actually visible. ๐-Wsuggest-final-methodsโ same vibe, but for virtual methods: it warns when declaring the methodfinal(or yeeting its type into an anonymous namespace, or slappingfinalon the type) would level up your code quality. Also way more effective with link-time optimization since the class hierarchy graph is more complete there. Pro tip: go look at the-Wsuggest-final-typessuggestions first, then rebuild with your new annotations. ๐ฆ-Wsuggest-overrideโ warns when you're overriding a virtual function but forgot to mark it with theoverridekeyword. ๐-Wuseless-cast(C++ and Objective-C++ only) โ warns when you cast an expression to its own type. Girl, that's you talking to a mirror. ๐ช-Wno-conversion-null(C++ and Objective-C++ only) โ stops warning about conversions betweenNULLand non-pointer types. Heads up:-Wconversion-nullis on by default. ๐
๐ Options Controlling Objective-C and Objective-C++ Dialects ๐
(Heads up bestie: this manual does not describe the Objective-C and Objective-C++ languages themselves. We're just doing the compiler flags here.) ๐
This bit is all about the command-line options that only mean something for Objective-C and Objective-C++ programs. That said, you can still use most of the language-independent GNU compiler options with them too. Like, you could compile a file some_class.m like this:
gcc -g -fgnu-runtime -O -c some_class.m
See how -fgnu-runtime in there is an option that's only for Objective-C and Objective-C++ programs? The other options in that line work with any language GCC supports. ๐ซถ
And real talk: since Objective-C is an extension of C, your Objective-C compilations can also use C-front-end-specific options (think -Wtraditional). Same energy for Objective-C++ โ it can use C++-specific options (hi -Wabi). โจ
Okay so here's the list of options that are only for compiling Objective-C and Objective-C++ programs:
- *
-fconstant-string-class=class-name* โ useclass-nameas the name of the class to instantiate for each literal string you write with the syntax@"...". The default class name isNXConstantStringif the GNU runtime is in play, andNSConstantStringif it's the NeXT runtime (more on that below ๐). On Darwin (macOS, MacOS X) platforms, if-fconstant-cfstringsis also present, it overrides the-fconstant-string-classsetting and makes those@"..."literals get laid out as constant CoreFoundation strings. Also FYI:-fconstant-cfstringsis an alias for the target-specific-mconstant-cfstringsequivalent. ๐ -fgnu-runtimeโ generates object code that's compatible with the standard GNU Objective-C runtime. This is the default for most types of systems. ๐-fnext-runtimeโ generates output compatible with the NeXT runtime. This is the default for NeXT-based systems, Darwin and Mac OS X included. Oh and the macro__NEXT_RUNTIME__gets predefined if (and only if) this option is used. โญ-fno-nil-receiversโ assumes that every single Objective-C message dispatch ([receiver message:arg]) in this translation unit guarantees the receiver isn'tnil. That lets the runtime use more efficient entry points. Heads up though: this one's only available with the NeXT runtime and ABI version 0 or 1. ๐ฅ- *
-fobjc-abi-version=n* โ use versionnof the Objective-C ABI for whichever runtime you picked. Currently only supported for the NeXT runtime. In that case:- Version 0 is the traditional (32-bit) ABI, no support for properties or the other Objective-C 2.0 additions.
- Version 1 is the traditional (32-bit) ABI with support for properties and other Objective-C 2.0 additions.
- Version 2 is the modern (64-bit) ABI.
If you don't specify anything, the 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, GCC checks 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 non-trivial default constructors on any such instance variables, in order, and then returnsself. Same deal the other direction: it checks whether any instance variable is a C++ object with a non-trivial destructor, and if so it synthesizes a special- (void) .cxx_destructmethod that runs all such default destructors, in reverse order. ๐
The - (id) .cxx_construct and - (void) .cxx_destruct methods generated this way only operate on instance variables declared in the current Objective-C class โ not the ones inherited from superclasses. It's the Objective-C runtime's job to invoke all such methods across an object's inheritance hierarchy. The - (id) .cxx_construct methods get invoked by the runtime right after a new object instance is allocated; the - (void) .cxx_destruct methods get invoked right 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_constructand- (void) .cxx_destructmethods.
-fobjc-direct-dispatchโ allows fast jumps to the message dispatcher. On Darwin this happens via the comm page. ๐-fobjc-exceptionsโ enables syntactic support for structured exception handling in Objective-C, similar to what C++ gives you. You need this option to use the Objective-C keywords@try,@throw,@catch,@finallyand@synchronized. Available with both the GNU runtime and the NeXT runtime โ but not available with the NeXT runtime on Mac OS X 10.2 and earlier. ๐ญ-fobjc-gcโ enables garbage collection (GC) in Objective-C and Objective-C++ programs. Only available with the NeXT runtime; the GNU runtime has a different garbage collection implementation that doesn't need special compiler flags. โป๏ธ-fobjc-nilcheckโ for the NeXT runtime with version 2 of the ABI, this checks for a nil receiver in method invocations before actually doing the 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 this way, no matter what you set this flag to. Currently this flag does literally nothing when the GNU runtime is used, or an older version of the NeXT runtime ABI. ๐-fobjc-std=objc1โ conform to the language syntax of Objective-C 1.0, the language GCC 4.0 recognized. This only affects the Objective-C additions to the C/C++ language; it does not affect conformance to C/C++ standards, which is handled by the separate C/C++ dialect option flags. When you use this with the Objective-C or Objective-C++ compiler, any Objective-C syntax that GCC 4.0 didn't recognize gets rejected. Super useful if you need to make sure your Objective-C code can compile with older versions of GCC. ๐ธ-freplace-objc-classesโ emits a special marker tellingld(1)not to statically link in the resulting object file, and lettingdyld(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 can be recompiled and dynamically reloaded while the program is running โ no need to restart the program itself. 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 class name 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 that behavior and causes calls toobjc_getClass("...")to be retained. Useful in Zero-Link debugging mode, since it lets individual class implementations 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 inside 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, which dodges those variable shadowing issues. ๐-fivar-visibility=[public|protected|private|package]โ sets the default instance variable visibility to whatever option you picked, so instance variables declared outside the scope of any access modifier directives default to that visibility. ๐-gen-declsโ dumps interface declarations for all classes seen in the source file to a file namedsourcename.decl. ๐-Wassign-intercept(Objective-C and Objective-C++ only) โ warns whenever an Objective-C assignment is being intercepted by the garbage collector. ๐-Wno-property-assign-default(Objective-C and Objective-C++ only) โ doesn't warn if a property for an Objective-C object has no assign semantics specified. ๐คซ-Wno-protocol(Objective-C and Objective-C++ only) โ okay so when a class says it implements a protocol, GCC is like "bestie you're missing methods" and warns for every method in that protocol the class doesn't implement. The default vibe is: warn about every method that isn't explicitly implemented in the class, even if it's inherited from the superclass. But if you pass-Wno-protocol, then methods inherited from the superclass count as implemented and you get zero warnings for them. ๐ซถ-Wobjc-root-class(Objective-C and Objective-C++ only) โ this one yells at you if a class interface has no superclass. Like, most classes will inherit fromNSObject(orObject) for example. When you're intentionally declaring root classes, you can hush the warning by marking the interfaces with__attribute__((objc_root_class)). ๐-Wselector(Objective-C and Objective-C++ only) โ warns if the compiler finds multiple methods of different types hanging out under the same selector during compilation. The check runs on the list of methods in the final stage of compilation. On top of that, it checks each selector that shows up in a@selector(...)expression, and a corresponding method for that selector has been found during compilation. And because these checks only scan the method table at the very end of compilation, you get no warnings if the final stage is never reached โ say an error got found during compilation, or you're using-fsyntax-only. ๐-Wstrict-selector-match(Objective-C and Objective-C++ only) โ warns if multiple methods with differing argument and/or return types are found for a given selector when you're trying to send a message using that selector to a receiver of typeidorClass. When this flag is off (which is the default), the compiler just skips those warnings if any differences found are confined to types that share the same size and alignment. โจ-Wundeclared-selector(Objective-C and Objective-C++ only) โ warns if a@selector(...)expression referring to an undeclared selector is found. A selector counts as 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 runs its checks the instant a@selector(...)expression is found, while-Wselectoronly checks in the final stage of compilation. It also enforces that coding-style convention that methods and selectors must be declared before being used. periodt. ๐-print-objc-runtime-infoโ generates a C header describing the largest structure that is passed by value, if any. ๐ธ
๐ฉบ Options to Control Diagnostic Messages Formatting ๐
So like, traditionally diagnostic messages have been formatted with zero regard for the output device's aspect (its width, and so on...). You can use the options below to control the formatting algorithm for diagnostic messages โ things like how many characters per line, and how often source location info should be reported. Heads up though: some language front ends may not honor these options. ๐
-fmessage-length=n โ tries to format error messages so they fit on lines of about n characters. If n is zero, then no line-wrapping happens; 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#errorand#warningpre-processor directives, and the deprecated function/type/variable attribute. It does not, however, affect thepragma GCC warningandpragma GCC errorpragmas.
-fdiagnostics-plain-outputโ this one asks for diagnostic output to look as plain as possible, which is lowkey useful when runningdejagnuor other utilities that need to parse diagnostics output and prefer it stay 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 meaningful in line-wrapping mode. Tells the diagnostic messages reporter to emit source location information once; that is, if the message is too long to fit on a single physical line and has to be wrapped, the source location won't be emitted (as a prefix) again and again on subsequent continuation lines. This is the default behavior. โ-fdiagnostics-show-location=every-lineโ only meaningful in line-wrapping mode. Tells the diagnostic messages reporter to emit the same source location info (as a prefix) for the physical lines that result from breaking a message too long to fit on a single line. ๐-fdiagnostics-color[=WHEN],-fno-diagnostics-colorโ use color in diagnostics. WHEN isnever,always, orauto. The default depends on how the compiler has been configured; it can be any of the above WHEN options, 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. (Peep 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. 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 also tries to sniff out a few terminals that are known to not implement the URL feature, and that have bugs (or at least had bugs in some versions that are still out there in the wild) where the URL escapes are likely to misbehave, i.e. just print garbage all over your screen. ๐ That list is currently xfce4-terminal, certain known-to-be-buggy gnome-terminal versions, the linux console, and mingw. You can skip this whole check with -fdiagnostics-urls=always.
-fno-diagnostics-show-optionโ bestie, by default every diagnostic that pops off also includes text telling you which command-line option directly controls that diagnostic (if the diagnostic machinery even knows of such an option, that is). Slap on-fno-diagnostics-show-optionand that behavior gets suppressed. ๐ซ-fno-diagnostics-show-caretโ default behavior? Every diagnostic includes the original source line plus a caret^pointing at the column. This option suppresses that info. Ngl the source line gets truncated to n characters if you passed-fmessage-length=n. And when the output is going to the terminal, the width is limited to whatever theCOLUMNSenvironment variable says โ or, if that's not set, to the terminal width. ๐-fno-diagnostics-show-labelsโ when printing source code (via-fdiagnostics-show-caret), diagnostics can label ranges of source code with pertinent info, like the types of expressions. It's giving:
printf ("foo %s bar", long_i + long_j);
~^ ~~~~~~~~~~~~~~~
| |
char * long int
This option suppresses the printing of those labels (in the example above, the vertical bars and the "char *" and "long int" text go bye-bye).
-fno-diagnostics-show-cweโ diagnostic messages can optionally have an associated CWE identifier (the Common Weakness Enumeration situation,https://cwe.mitre.org/index.html). GCC itself only provides that kind of metadata for some of the-fanalyzerdiagnostics. GCC plugins may also hand over diagnostics with such metadata. By default, if this info is present, it gets printed with the diagnostic. This option suppresses the printing of that 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 that left margin. โจ-fdiagnostics-minimum-margin-width=widthโ this one 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 gets 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 example above, 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 \", and 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). ๐
-fno-elide-typeโ by default when the C++ frontend prints diagnostics showing mismatching template types, common parts of the types are printed as[...]to simplify the error message. For example:
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. This flag also affects the output of the -fdiagnostics-show-template-tree flag.
-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 at all.
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.
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 extra info 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. (iykyk ๐ )
-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, is like, super aware of how many display columns each character is hogging. And that is NOT always the same as the bytes, bestie. It can be bigger than the byte count โ hi, tab characters ๐ โ or smaller, which is what happens with multibyte characters. Example time: the character "GREEK SMALL LETTER PI (U+03C0)" takes up one display column, but its UTF-8 encoding needs two bytes. And the character "SLIGHTLY SMILING FACE (U+1F642)" takes up two display columns while its UTF-8 encoding needs four bytes. The math is mathing, it's just not the same math. ๐
Set UNIT to byte and the column number becomes the raw byte count in every single case โ which is literally how GCC did it before version 11.1.0. Throwback era. ๐
-fdiagnostics-column-origin=ORIGINโ picks where column numbers start, aka which column gets to be called "first". The default is1, which matches old-school GCC behavior and the GNU style guide. Some utilities lowkey vibe better with an origin of0โ and honestly, any non-negative value is fair game, you can specify whatever. โจ-fdiagnostics-format=FORMATโ switches up how diagnostics get printed. FORMAT is eithertextorjson. Default istext. No cap.
The json format is a top-level JSON array, and inside it are JSON objects representing the diagnostics. It gets emitted as one single line, no pretty formatting โ the examples below have been formatted for clarity only, don't come for me. ๐
Diagnostics can have child diagnostics, because of course they can, it's giving family tree. 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:
[
{
"kind": "warning",
"locations": [
{
"caret": {
"display-column": 3,
"byte-column": 3,
"column": 3,
"file": "misleading-indentation.c",
"line": 15
},
"finish": {
"display-column": 4,
"byte-column": 4,
"column": 4,
"file": "misleading-indentation.c",
"line": 15
}
}
],
"message": "this \u2018if\u2019 clause does not guard...",
"option": "-Wmisleading-indentation",
"option_url": "https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wmisleading-indentation",
"children": [
{
"kind": "note",
"locations": [
{
"caret": {
"display-column": 5,
"byte-column": 5,
"column": 5,
"file": "misleading-indentation.c",
"line": 17
}
}
],
"message": "...this statement, but the latter is ..."
}
]
"column-origin": 1,
},
...
]
where the "note" is a child of the "warning". Parent-child diagnostic moment, we love to see it. ๐ซถ
A diagnostic has a "kind". If that kind is "warning", then there's an "option" key describing the command-line option that's controlling the warning. Sneaky little key.
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 indicating a column position:
"display-column"counts display columns, and it accounts for tabs and multibyte characters."byte-column"counts raw bytes."column"is equal to one of the previous two โ whichever one the-fdiagnostics-column-unitoption says it should be. Choose your fighter.
All three columns are relative to the origin specified by -fdiagnostics-column-origin, which is typically equal to 1 but may be set, for instance, to 0 for 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 have been omitted for brevity. Gone but not forgotten bestie. ๐
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 also has two secondary locations, describing the left and right-hand sides of the expression, and those two 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}"
}
],
"message": "invalid operands to binary + ..."
}
If a diagnostic contains fix-it hints, it has a "fixits" array, made up of half-open intervals, similar to the output of -fdiagnostics-parseable-fixits. Half-open intervals are giving math class but make it JSON. 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
}
}
],
"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 are expressed by having "start" equal "next". Insert = start equals next, delete = string goes bye-bye, periodt. ๐
If the diagnostic has a path of control-flow events associated with it, it has a "path" array of objects representing those events. Each event object has a "description" string, a "location" object, along with 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
}
}
]
๐ Options to Request or Suppress Warnings ๐
Okay so warnings?? They're diagnostic messages that call out constructions that aren't like, inherently wrong, but they're risky ๐ or they're giving "bestie there might have been an error here". Not errors, just... vibes that are off.
The next few options are language-independent, meaning they don't turn on any specific warning, they just control the kind of diagnostics GCC spits out at you.
-fsyntax-onlyโ Check the code for syntax errors only. That's it. Nothing beyond that. Not the moment for anything else. ๐-fmax-errors=n โ Caps the max number of error messages at n, and once you hit that, GCC just gives up and bails rather than trying to keep processing the source code. If n is0(which is the default), there is *no limit on how many error messages get produced. And if-Wfatal-errorsis *also specified, then-Wfatal-errorstakes precedence over this option. Rude but okay.-wโ Inhibit all warning messages. All of them. Gone. Silence. ๐-Werrorโ Make every single warning into an error. Iconic. Terrifying. Both.-Werror=โ Make the specified warning into an error. You append the specifier for the warning; for example-Werror=switchturns the warnings controlled by-Wswitchinto errors. This switch also has a negative form, which you use to negate-Werrorfor specific warnings; for example-Wno-error=switchmakes-Wswitchwarnings not be errors, even when-Werroris in effect.
The warning message for each controllable warning includes the option that controls the warning. That option can then be used with -Werror= and -Wno-error= as described above. (You can turn off the printing of the option in the warning message with the -fno-diagnostics-show-option flag.)
Note bestie: specifying -Werror=foo automatically implies -Wfoo. However, -Wno-error=foo does not imply anything. Nothing at all. It's giving unbothered. ๐
-Wfatal-errorsโ This one makes the compiler abort compilation on the first error that occurs, instead of trying to keep going and printing further error messages. Girl just stops. ๐
So you can request a ton of specific warnings with options that start with -W, like -Wimplicit to request warnings on implicit declarations. Every one of these specific warning options also has a negative form starting with -Wno- to turn the warnings off; like -Wno-implicit. This manual only lists one of the two forms โ whichever one is not the default. For more language-specific options, also go look at C++ Dialect Options and Objective-C and Objective-C++ Dialect Options. And extra warnings can be produced by enabling the static analyzer.
Some options, like -Wall and -Wextra, turn on other options, like -Wunused, which may turn on further options, like -Wunused-value. The combined effect of positive and negative forms is that more specific options have priority over less specific ones, no matter where they sit in the command line. For options of the same specificity, the last one takes effect. And options enabled or disabled via pragmas take effect as if they appeared at the end of the command-line. Periodt.
When you request an unrecognized warning option (e.g. -Wunknown-warning), GCC emits a diagnostic saying that the option is not recognized. BUT โ plot twist โ if you use the -Wno- form, the behavior is slightly different: no diagnostic is produced for -Wno-unknown-warning unless other diagnostics are being produced. This lets you use new -Wno- options with old compilers, but if something goes wrong, the compiler warns you that an unrecognized option is present. Protective king behavior honestly. ๐ซถ
Also the effectiveness of some warnings depends on optimizations being enabled too. For example -Wsuggest-final-types is more effective with link-time optimization, and -Wmaybe-uninitialized doesn't warn at all unless optimization is enabled. Just so you know.
-Wpedantic-pedanticโ Issue all the warnings demanded by strict ISO C and ISO C++; reject all programs that use forbidden extensions, and also some other programs that 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 require -ansi or a -std option specifying the required version of ISO C). However โ without this option, certain GNU extensions and traditional C and C++ features are supported as well. With this option, they get rejected. ๐ซ
-Wpedantic does not cause warning messages for use of the alternate keywords whose names begin and end with __. This 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__. However, only system header files should use these escape routes; application programs should avoid them. Bestie. Don't. ๐
Some users try to use -Wpedantic to check programs for strict ISO C conformance. They soon find that it doesn't do quite 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 would 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. Sorry babes ๐
Where the standard specified with -std represents a GNU extended dialect of C, such as gnu90 or gnu99, there is a corresponding base standard โ the version of ISO C on which the GNU extended dialect is based. Warnings from -Wpedantic are given where they are required by the base standard. (It does not 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 would be nothing to warn about.) Like. Correct. ๐
-pedantic-errorsโ Give an error whenever the base standard (see-Wpedantic) requires a diagnostic, in some cases where there is undefined behavior at compile-time and in some other cases that do not prevent compilation of programs that are valid according to the standard. This is not equivalent to-Werror=pedantic, since there are errors enabled by this option and not enabled by the latter and vice versa. Two different girlies, two different jobs. ๐-Wallโ This enables 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. This also enables some language-specific warnings described in C++ Dialect Options and Objective-C and Objective-C++ Dialect Options.
-Wall turns on the following warning flags:
-Waddress
-Warray-bounds=1 (only with -O2)
-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
-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++)
-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
-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 that users generally don't consider questionable, but which occasionally you might wish to check for; others warn about constructions that are necessary or hard to avoid in some cases, and 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. So -Wall isn't actually "all". It's giving โจ all โจ in quotes. ๐ญ
-Wextraโ This enables some extra warning flags that are not enabled by-Wall. (This option used to be called-W. The older name is still supported, but the newer name is more descriptive.) Glow-up behavior honestly. ๐
Here's what it turns on:
-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 the following 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)
Okay bestie, this one is the ABI gossip column ๐ โ it warns you about code that's affected by ABI changes. That includes code that may not play nice with the vendor-neutral C++ ABI, plus the psABI for whatever target you're on.
Since G++ now defaults to updating the ABI with each major release, normally -Wabi only warns about C++ ABI compatibility problems if there's a check added later in a release series for an ABI issue discovered since the initial release. But -Wabi warns about more things if an older ABI version is selected (with -fabi-version=n).
You can also use -Wabi 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.
Real talk though: even though an effort has been made to warn about all such cases, there are probably some cases that are not warned about, even though G++ is generating incompatible code ๐ญ. And there may also be cases where warnings are emitted even though the code that is generated is compatible. Messy, ik.
You should rewrite your code to avoid these warnings if you're concerned about the fact that code generated by G++ may not be binary compatible with code generated by other compilers.
Known incompatibilities in -fabi-version=2 (which was the default from GCC 3.4 to 4.9) include:
- 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))"and"noreturn"were mangled as type qualifiers, and"decltype"of 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_arg"to complain. On most targets this does not actually affect the parameter passing ABI, as there is no way to pass an argument smaller than"int".
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 a"nullptr_t"parameter, 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 enables warnings about psABI-related changes. The known psABI changes at this point include:
- For SysV/x86-64, unions with
"long double"members 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
Warns you if an array subscript has type "char" ๐. 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
Warns you if feedback profiles do not match when using the -fprofile-use option. If a source file is changed between compiling with -fprofile-generate and 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-mismatch can be used to disable the warning or -Wno-error=coverage-mismatch can 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. Periodt.
โจ -Wno-cpp
(C, Objective-C, C++, Objective-C++ and Fortran only) Suppress warning messages emitted by "#warning" directives. That's it, that's the whole vibe ๐ซถ.
๐ฅ -Wdouble-promotion (C, C++, Objective-C and Objective-C++ only)
Gives you a warning when a value of type "float" is implicitly promoted to "double" ๐ญ. Here's the tea: CPUs with a 32-bit "single-precision" floating-point unit implement "float" in hardware, but emulate "double" in software. On such a machine, doing computations using "double" values 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)
Warns you if a declaration has duplicate "const", "volatile", "restrict" or "_Atomic" specifier. This warning is enabled by -Wall.
๐ -Wformat / -Wformat=n
Checks calls to "printf" and "scanf", 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 the "printf", "scanf", "strftime" and "strfmon" (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 -ffreestanding or -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 -Wformat is specified, do not warn about format strings that contain NUL bytes.
๐ -Wno-format-extra-args
If -Wformat is specified, do not warn about excess arguments to a "printf" or "scanf" format 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
Warns you about calls to formatted input/output functions such as "sprintf" and "vsprintf" that 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โ bestie, this is level 1 of-Wformat-overflow(it comes free with-Wformat), and it's playing it safe. It only yells about calls that most likely blow past the buffer. At this level, numeric args to format directives whose values are unknown get assumed to be one, and strings of unknown length get assumed to be empty. But if a numeric arg is known to be bounded to a subrange of its type, or a string arg's output is bounded either by the directive's precision or by a finite set of string literals, then GCC assumes the value in that range that gives the most bytes on output. For example, thesprintfcall below gets diagnosed because even with bothaandbset to zero, the terminating NUL character ('\0') that the function appends to the destination buffer will be written past its end. Bumping the buffer size by a single byte is enough to dodge the warning, though ngl it may not be enough to dodge the actual overflow.
void f (int a, int b)
{
char buf [13];
sprintf (buf, "a = %i, b = %i\n", a, b);
}
-Wformat-overflow=2โ level 2 is extra and also warns about calls that might overflow the destination buffer, given an argument of sufficient length or magnitude. At level 2, unknown numeric args 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 args whose length can't be assumed bounded (neither by the directive's precision, nor by a finite set of string literals they might evaluate to, nor by the character array they might point to) get assumed to be 1 character long.
At level 2, the call in the example above is diagnosed again, 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 no matter what the two variables hold, the destination buffer size must be increased to at least 34 bytes. GCC even drops the minimum buffer size in an informational note right after the warning. ๐ซถ
An alternative to making the buffer bigger is to constrain the range of formatted values. The maximum length of string args can be bounded by specifying the precision in the format directive. And when numeric args of format directives can be assumed bounded by less than the precision of their type, picking an appropriate length modifier for the format specifier will shrink the required buffer size. So like, 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 brings the max required buffer size down to 24 bytes.
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 says zero-length formats are allowed, so live your truth. โจ-Wformat-nonliteralโ if-Wformatis specified, also warn when the format string isn't a string literal (so it can't 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. Right now this warns about calls toprintfandscanffunctions where the format string isn't a string literal and there are no format arguments, likeprintf (foo);. That may be a security hole if the format string came from untrusted input and contains%n. Big yikes energy. (This is currently a subset of what-Wformat-nonliteralwarns about, but in the future more warnings may be added to-Wformat-securitythat aren't included in-Wformat-nonliteral.)-Wformat-signednessโ if-Wformatis specified, also warn when the format string requires an unsigned argument but the argument is signed, or vice versa.-Wformat-truncation-Wformat-truncation=levelโ warn about calls to formatted input/output functions likesnprintfandvsnprintfthat might result in output truncation. When the exact number of bytes written by a format directive can't be determined at compile-time, it gets estimated based on heuristics that depend on the level argument and on optimization. Enabling optimization will in most cases improve the warning's accuracy, but it may also cause false positives. Except as noted otherwise, this option uses the same logic as-Wformat-overflow.-Wformat-truncation-Wformat-truncation=1โ level 1 of-Wformat-truncation(enabled by-Wformat) is the cautious era: it only warns about calls to bounded functions whose return value is unused and that will most likely result in output truncation.-Wformat-truncation=2โ level 2 also warns 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. (yes this is real and it's giving 1999 ๐)-Wnonnullโ warn about passing a null pointer for arguments marked as requiring a non-null value by thenonnullfunction attribute.
-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. ๐
-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 by dereferencing a null pointer. This option is only active when-fdelete-null-pointer-checksis active, which is enabled by optimizations in most targets. How precise these warnings are depends on the optimization options used.-Winit-self(C, C++, Objective-C and Objective-C++ only) โ warn about uninitialized variables that are initialized with themselves. Note that this option can only be used with the-Wuninitializedoption. ๐
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 doesn't 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.-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:
switch (cond)
{
case 1:
a = 1;
break;
case 2:
a = 2;
case 3:
a = 3;
break;
}
This warning does not fire when the last statement of a case can't fall through โ like when there's a return statement or a call to a 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 actually desirable, GCC provides an attribute, __attribute__ ((fallthrough)), that's meant 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's 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.-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:
โฆand the rest of the regexes for -Wimplicit-fallthrough=3 (matched case sensitively) are these iconic little pattern babies:
"-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=4โ case sensitively matches one of these:"-fallthrough""@fallthrough@""lint -fallthrough[ \t]*""[ \t]*FALLTHR(OUGH|U)[ \t]*"
-Wimplicit-fallthrough=5โ doesn't recognize any comments as fallthrough comments. Only attributes disable the warning. That's it, that's the whole vibe. ๐
Okay so the comment itself has to be followed โ after optional whitespace and other comments โ by "case" or "default" keywords, or by a user label that comes before some "case" or "default" label. Like:
switch (cond)
{
case 1:
bar (0);
/* FALLTHRU */
default:
...
}
The -Wimplicit-fallthrough=3 warning is enabled by -Wextra.
-Wno-if-not-aligned(C, C++, Objective-C and Objective-C++ only) โ controls whether warnings triggered by the"warn_if_not_aligned"attribute get issued. These warnings are enabled by default. ๐-Wignored-qualifiers(C and C++ only) โ warns if the return type of a function has a type qualifier like"const". For ISO C, that kind of type qualifier literally has no effect, because the value returned by a function is not an lvalue. For C++, the warning only fires for scalar types or"void". And ISO C prohibits qualified"void"return types on function definitions, so those return types always get a warning even without this option. no cap.
This warning is also enabled by -Wextra.
-Wno-ignored-attributes(C and C++ only) โ this one controls warnings when an attribute gets ignored. It's different from the-Wattributesoption because it warns whenever the compiler decides to drop an attribute, not that the attribute is unknown or used in a wrong place, etc. This warning is enabled by default.-Wmainโ warns if the type of"main"is suspicious."main"should be a function with external linkage, returningint, taking either zero arguments, two, or three arguments of appropriate types. Enabled by default in C++, and enabled by either-Wallor-Wpedantic.-Wmisleading-indentation(C and C++ only) โ warns when the indentation of the code does not reflect the block structure. Specifically, a warning gets 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. it's giving trap ๐ญ
In this next 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". */
When it's mixed tabs and spaces, the warning uses the -ftabstop= option to figure out if the statements line up (defaulting to 8).
The warning is not issued for code involving multiline preprocessor logic like this:
if (flagA)
foo (0);
#if SOME_CONDITION_THAT_DOES_NOT_HOLD
if (flagB)
#endif
foo (1);
And it's not issued after a "#line" directive either, since that typically means autogenerated code, and you can't make any assumptions about the layout of the file that directive references.
This warning is enabled by -Wall in C and C++.
-Wmissing-attributesโ warns when a declaration of a function is missing one or more attributes that a related function is declared with, where that absence may adversely affect the correctness or efficiency of the 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. By contrast, the-Wattribute-alias=2option 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 gets 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โ warns if an aggregate or union initializer isn't fully bracketed. In the next example, the initializer for"a"isn't fully bracketed, but the one for"b"is fully bracketed. โจ
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 and Objective-C++ only) โ warns if a user-supplied include directory does not exist. simple as that bestie.-Wno-missing-profileโ this option controls warnings if feedback profiles are missing when using the-fprofile-useoption. It diagnoses those cases where a new function or a new file got added between compiling with-fprofile-generateand with-fprofile-use, without regenerating the profiles. In those 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 can't use any profile feedback information. In all these cases, warnings get issued to inform you that a profile generation step is due. Ignoring the warning can result in poorly optimized code.-Wno-missing-profilecan be used to disable the warning, but this is not recommended and should be done only when non-existent profile data is justified.-Wno-mismatched-deallocโ warns 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-builtinoption, 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 enabled by default.
-Wmultistatement-macrosโ warns about unsafe multiple statement macros that look like they're guarded by a clause such as"if","else","for","switch", or"while", when actually only the first statement is guarded after the macro is expanded. the betrayal ๐ญ
Like:
#define DOIT x++; y++
if (c)
DOIT;
This will increment "y" unconditionally, not just when "c" holds. You can usually fix it 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โ warns if parentheses are omitted in certain contexts, like 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. we've all been there.
It also warns if a comparison like "x<=y<=z" shows up; that's equivalent to "(x<=y ? 1 : 0) <= z", which is a totally different interpretation from ordinary mathematical notation.
It also warns 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. ๐
For C++ it 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โ warns 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 literally define the order that expressions in a C/C++ program get evaluated in terms of sequence points ๐ โ which are basically a partial ordering between the execution of parts of your program: the bits that run before the sequence point, and the bits that run after it. Where do these little guys show up?
- after the evaluation of a full expression (one that isn't part of a bigger 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 what the sequence point rules say, the order of evaluation of subexpressions of an expression is not specified. And bestie, all these rules describe only a partial order, not a total order โ because, 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 ๐ญ. That said, the standards committee has ruled that function calls do not overlap.
It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior ๐. The C and C++ standards say it like this:
"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."
If a program breaks these rules, the results on any particular implementation are entirely unpredictable ๐.
Examples of code with undefined behavior are a = a++;, a[n] = b[n++] and a[i++] = i;. Some more complicated cases are not diagnosed by this option, and it may give an occasional false positive result, but in general it has been found fairly effective at detecting this sort of problem in programs. ngl, pretty iconic of it ๐ธ.
The C++17 standard will define the order of evaluation of operands in more cases: in particular it requires that the right-hand side of an assignment be evaluated before the left-hand side, so the above examples are no longer undefined. But this option will still warn about them, to help people avoid writing code that is undefined in C and earlier revisions of C++ ๐ซถ.
The standard is worded confusingly, therefore there is some debate over the precise meaning of the sequence point rules in subtle cases. Links to discussions of the problem, including proposed formal definitions, may be found on the GCC readings page, at <http://gcc.gnu.org/readings.html> ๐ฅ.
This warning is enabled by -Wall for C and C++.
-Wno-return-local-addrโ bestie, this one says do NOT warn about returning a pointer (or in C++, a reference) to a variable that goes out of scope after the function returns. (Which is likeโฆ handing someone your house key as the house is being demolished, but okay ๐ญ)-Wreturn-typeโ warns whenever a function is defined with a return type that defaults toint. It also warns about anyreturnstatement with no return value in a function whose return type is notvoid(falling off the end of the function body counts as returning without a value).
For C only, it warns 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. periodt.
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โ warns if you left shift 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-shifting1into 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-shifting1into the sign bit, unless C++14 mode (or newer) is active.
-Wswitchโ warns 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โ warns whenever aswitchstatement does not have adefaultcase ๐ฑ.-Wswitch-enumโ warns 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 option gives a warning about an omitted enumeration code even if there is adefaultlabel.-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. It is possible to 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) โ warns when__sync_fetch_and_nandand__sync_nand_and_fetchbuilt-in functions are used. These functions changed semantics in GCC 4.4 ๐.-Wunused-but-set-parameterโ warns 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โ warns 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โ warns 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โ warns 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) โ warns when a typedef locally defined in a function is not used. This warning is enabled by-Wall.-Wunused-parameterโ warns 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โ warns 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โ warns 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โ bestie, this one clocks you when a statement computes a result that literally nobody asked for. It's explicitly not used, and GCC is like "girl why". ๐
Wanna shut it up? Just cast that unused expression to void. Easy.
This covers an expression-statement, or the left-hand side of a comma expression, that has no side effects. Classic example: x[i,j] gets a warning (the i is just vibing, doing nothing), but x[(void)i,j] is fine because you told it to chill. โจ
This warning is enabled by -Wall.
-Wunusedโ it's giving "all of the above, bundled". Every-Wunusedoption listed above, combined into one glorious package. ๐
But heads up, bestie: if you want a warning about an unused function parameter, you have to either say -Wextra -Wunused (and yes, -Wall implies -Wunused), or spell out -Wunused-parameter all by yourself. No free rides. ๐
-Wuninitializedโ this one yells if an object with automatic or allocated storage duration gets used before it's been initialized. Rude behavior, honestly. In C++, it also warns if a non-static reference or a non-staticconstmember shows up in a class that has no constructors.
Bonus tea: passing 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 the object? Also diagnosed here. (-Wmaybe-uninitialized is what gets issued for ordinary functions instead.)
Want a warning about code that reads a variable's uninitialized value inside its own initializer? That's a whole separate vibe โ use -Winit-self. ๐ฆ
These warnings fire for individual uninitialized elements of structure, union or array variables, and for variables that are uninitialized as a whole. They do not fire for variables or elements declared volatile. And because they depend on optimization, the exact variables/elements you get warned about depend on the precise optimization options and the version of GCC you're running. No cap.
Also note: there may be no warning about a variable that's only used to compute a value that itself is never used โ because data flow analysis can just delete those computations before the warnings even get printed. Gone. Poof. ๐ญ
-Wno-invalid-memory-modelโ okay so this option controls warnings for invocations of__atomicBuiltins,__syncBuiltins, and the C11 atomic generic functions when the memory consistency argument is either invalid for the operation or outside the range of values of thememory_orderenumeration. ๐
Example time: since __atomic_store and __atomic_store_n are only defined for the relaxed, release, and sequentially consistent memory orders, this little snippet gets diagnosed:
void store (int *i)
{
__atomic_store_n (i, 0, memory_order_consume);
}
-Winvalid-memory-model is enabled by default. (So yes, -Wno- is how you turn it off, iykyk.) ๐
-Wmaybe-uninitializedโ for an object with automatic or allocated storage duration: if there's a path from function entry to a use of the object where it's initialized, but there are also some other paths where it's not initialized, the compiler throws a warning if it can't prove those uninitialized paths never actually run at runtime. ๐ฅ
Extra: passing a pointer (or, in C++, a reference) to an uninitialized object into a const-qualified function argument also gets diagnosed here. (-Wuninitialized is what's issued for built-in functions known to read the object.) And if you annotate the function with attribute access (none), that tells GCC the argument isn't used to access the object โ and that dodges the warning. โจ
These warnings are only possible in optimizing compilation, because otherwise GCC isn't keeping track of the state of variables at all. It's not being lazy, it literally can't see. ๐
They're made optional because GCC might not be able to tell when the code is actually correct despite looking like an error. Here's an example of exactly how that happens:
{
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. To suppress the warning, you need to give it a default case with assert(0) or similar code. ๐ซถ
This option also warns when a non-volatile automatic variable might get changed by a call to longjmp. Here's the thing: the compiler only sees the calls to setjmp. It has no idea where longjmp will be called โ and honestly, a signal handler could call it at any point in the code. So you might get a warning even when there's genuinely no problem, because longjmp can't actually be called at the place that would cause a problem. ๐
And some spurious warnings can be avoided entirely if you declare all the functions you use that never return as noreturn. Chef's kiss. ๐
This warning is enabled by-Wallor-Wextra.
-Wunknown-pragmasโ warns whenever a#pragmadirective shows up that GCC just... doesn't understand. If you use this command-line option, warnings get issued even for unknown pragmas hiding in system header files. That is not the case if the warnings are only enabled by the-Wallcommand-line option. Sneaky difference, fr fr. ๐-Wno-pragmasโ do not warn about misuses of pragmas. We're talking incorrect parameters, invalid syntax, or conflicts between pragmas. Also see-Wunknown-pragmasabove. ๐ธ-Wno-prio-ctor-dtorโ do not warn if a priority from 0 to 100 is used for a constructor or destructor. So like, the constructor and destructor attributes let you assign a priority to the constructor/destructor to control its order of execution beforemainis 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 itself. Respect the reservation. ๐-Wstrict-aliasingโ this option is only active when-fstrict-aliasingis active. It warns about code that might break the strict aliasing rules the compiler is using for optimization. It doesn't catch every case (be real, nothing does), but it does attempt to catch the more common pitfalls. It's included in-Wall. And it's equivalent to-Wstrict-aliasing=3. โจ-Wstrict-aliasing=nโ same deal, only active when-fstrict-aliasingis active, warns about code that might break those strict aliasing rules. Higher levels = higher accuracy (fewer false positives). Higher levels also = more effort, kinda like how-Oworks. And reminder:-Wstrict-aliasingis 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. It warns for all pointer conversions between possibly incompatible types โ even if they're 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. It 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. Iconic behavior, honestly. ๐
- Level 1: Most aggressive, quick, least accurate. Possibly useful when higher levels don't warn but
-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. Note that it does not warn about all cases where the code might overflow โ it only warns about cases where the compiler actually implements some optimization. So this warning depends on the optimization level. ๐
An optimization that assumes signed overflow doesn't occur is perfectly safe if the values of the variables involved are such that overflow never in fact happens. So this warning can easily give a false positive: a warning about code that isn't actually a problem. To help you focus on the important stuff, 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 > xto1. 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. And btw,-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. You've been warned, bestie. ๐
-Wstring-compareโ bestie, this one's for when you callstrcmporstrncmpand the compiler already knows the answer, because one argument's length is bigger than the size of the array the other one lives in (or bigger than the bound, in thestrncmpcase). That's almost always a mistake, and GCC will side-eye you for it. Like, look at thisstrcmpcall โ it gets flagged because its result is necessarily non-zero, no matter what's actually inside the arraya:
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 switched on for you by -Wextra. ๐
-Wno-stringop-overflow-Wstringop-overflow-Wstringop-overflow=typeโ this trio is the buffer-overflow alarm ๐จ. It warns about calls to string-manipulation functions likememcpyandstrcpythat GCC can prove will overflow the destination buffer. The optional argument is one greater than the type of Object Size Checking used to figure out the size of the destination. Heads up though: that argument only means anything for functions that work on character arrays โ raw memory functions likememcpyalways use Object Size type-0, no matter what. The option also yells at calls that specify a size bigger than the largest possible object, or at mostSIZE_MAX / 2bytes. It works best with optimization turned on, but it can still catch a small subset of simple buffer overflows even with no optimization, in calls to GCC built-ins like__builtin_memcpythat match the standard functions. Either way, it only warns about a subset of the overflows that the corresponding overflow-checking built-ins can detect. For example, it warns on thestrcpybelow because it copies at least 5 characters (the string"blue"plus the terminating NUL) into a buffer of size 4:
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 determine the sizes of destination objects. At this setting it 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 could be any one of several objects, it just assumes it's the biggest one of them. On Linux systems, with optimization enabled at this setting, it warns on the same code as when the _FORTIFY_SOURCE macro is defined to a non-zero value. ๐ธ
-Wstringop-overflow=2
The -Wstringop-overflow=2 option uses type-one Object Size Checking to determine the sizes of destination objects. At this setting it warns about overflows when writing to members of the largest complete objects whose exact size is known. But it will not warn about excessive writes to those same members of unknown objects referenced by pointers, since those pointers might point at arrays with an unknown number 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 determine the sizes of destination objects. At this setting it warns about overflowing the smallest object or data member. This is the most restrictive setting of the option โ and ngl, it may end up warning about perfectly safe code. ๐ญ
-Wstringop-overflow=4
The -Wstringop-overflow=4 option uses type-three Object Size Checking to determine the sizes of destination objects. At this setting it 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 warn. Same energy as -Wstringop-overflow=3: this setting may also produce warnings for totally benign code. ๐
-Wno-stringop-overreadโ warns about calls to string-manipulation functions likememchr, orstrcpy, that GCC determines will read past the end of the source sequence. ๐
Option -Wstringop-overread is enabled by default.
-Wno-stringop-truncationโ tells GCC not to warn about calls to bounded string-manipulation functions likestrncat,strncpy, andstpncpythat might either truncate the copied string or leave the destination untouched.
In this next example, the strncat call gives a bound that's shorter than the source string, so the copy gets truncated and the call gets diagnosed. Want 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: this strncpy call copies into d only the characters before the terminating NUL, and never appends the NUL at the end. Assuming the result of strncpy is necessarily a NUL-terminated string is a super common mistake, so the call gets diagnosed. If you're not expecting a NUL-terminated result, call memcpy instead and the warning goes away. ๐
void copy (char *d, const char *s)
{
strncpy (d, s, strlen (s));
}
And one more: this strncpy call passes the size of the destination buffer as the bound. If the source string's length is equal to or greater than that size, the copy won't be NUL-terminated, so the call is diagnosed too. To avoid the warning, pass 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);
...
}
Now, if you've got a character array that's meant to hold a sequence of bytes with no terminating NUL, you can annotate it with the nonstring attribute to shut this warning up. Careful though โ those arrays are not suitable arguments for functions that expect NUL-terminated strings. To help catch accidental misuse of arrays like that, GCC issues warnings unless it can prove the use is safe. ๐ซถ
-Wsuggest-attribute=[pure|const|noreturn|format|cold|malloc]โ warns you when slapping an attribute on a function would probably be a glow-up. The attributes currently supported are listed right below. โญ
-Wsuggest-attribute=pure / -Wsuggest-attribute=const / -Wsuggest-attribute=noreturn / -Wmissing-noreturn / -Wsuggest-attribute=malloc
Warns about functions that might be candidates for the pure, const, noreturn or malloc attributes. The compiler only warns for functions that are visible in other compilation units, or โ for pure and const โ when it can't prove the function returns normally. A function counts as returning normally if it doesn't contain an infinite loop and doesn't return abnormally by throwing, calling abort, or trapping. This analysis needs the option -fipa-pure-const, which is enabled by default at -O and higher. Higher optimization levels make the analysis more accurate. ๐
-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, bestie. GCC guesses that function pointers with format attributes which get used in assignment, initialization, parameter passing or return statements should have a matching 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 carry a format attribute to avoid the warning.
GCC also warns about function definitions that might be candidates for format attributes. Again โ only possible candidates. GCC guesses that format attributes might be appropriate for any function that calls something like vprintf or vscanf, but that's not always the case, and some functions that genuinely deserve format attributes might not get detected at all. ๐
-Wsuggest-attribute=cold
Warns about functions that might be candidates for the cold attribute. This is based on static detection, and it generally only warns about functions that always lead to a call to another cold function โ think wrappers of C++ throw, or fatal-error-reporting functions that lead to abort. ๐ง
-Walloc-zeroโ warns about calls to allocation functions decorated with thealloc_sizeattribute that ask for zero bytes, including the built-in forms ofaligned_alloc,alloca,calloc,malloc, andrealloc. Why? Because the behaviour of these functions when called with a zero size differs between implementations โ and in the case ofreallocit's been deprecated โ so relying on it can cause subtle portability bugs and should be avoided. ๐ซ-Walloc-size-larger-than=byte-sizeโ warns about calls to functions decorated with thealloc_sizeattribute that try to allocate objects bigger 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 ofPTRDIFF_MAXon the target.-Walloc-size-larger-than=PTRDIFF_MAXis enabled by default. Want the warnings off? Either specify a byte-size ofSIZE_MAXor more, or just use-Wno-alloc-size-larger-than. โจ-Wno-alloc-size-larger-thanโ turns OFF the-Walloc-size-larger-than=warnings. Bestie, this is literally the same energy as-Walloc-size-larger-than=SIZE_MAXor bigger. ๐-Wallocaโ screams at you every single time you useallocain the source. Every. Single. Time. ๐ฅ-Walloca-larger-than=byte-size โ warns on calls toallocawith an integer argument whose value is either *zero, or that isn't bounded by a controlling predicate keeping it at most *byte-size. It also warns when the bound value is just... unknown ๐. Arguments of non-integer types count as unbounded even if they look constrained to the expected range. Sneaky like that.
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);
}
In the above example, passing -Walloca-larger-than=1000 would not issue a warning because the call to alloca is known to be at most 1000 bytes. However, if -Walloca-larger-than=500 were passed, the compiler would emit a warning. Yeah. ๐
Unbounded uses, on the other hand, are uses of alloca with no controlling predicate constraining its integer argument. 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 cap.
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. the audacity tbh ๐ญ
This option also warns when alloca is used in a loop. ๐
-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โ turns OFF the-Walloca-larger-than=warnings. Same as saying-Walloca-larger-than=SIZE_MAXor larger. ๐ซถ-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. lowkey nosy but okay โจ
void f (char c, int i)
{
c = c + i; // warns with -Wconversion
c = c + 1; // only warns with -Warith-conversion
}
-Warray-bounds-Warray-bounds=n โ this option is only active when-ftree-vrpis active (default for-O2and above). It warns about subscripts to arrays that are **always out of bounds. This warning is enabled by-Wall. ๐-Warray-bounds=1โ this is the warning level of-Warray-boundsand is enabled by-Wall; higher levels are not, and must be explicitly requested. you have to ask nicely bestie.-Warray-bounds=2โ this warning level also warns about out of bounds access for arrays at the end of a struct and for arrays accessed through pointers. Heads up though: this warning level may give a larger number of false positives and is deactivated by default. ๐
-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.
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. iykyk.
- *
-Wattribute-alias=n* -Wno-attribute-aliasโ warn about declarations using thealiasand similar attributes whose target is incompatible with the type of the alias. mismatched besties, not it ๐-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. red flag fr.-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. the full roster, iconic โจ
-Wattribute-aliasis equivalent to-Wattribute-alias=1. This is the default. You can disable these warnings with either-Wno-attribute-aliasor-Wattribute-alias=0.
-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;
-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) { ... }
-Wframe-addressโ warn when the__builtin_frame_addressor__builtin_return_addressis called with an argument greater than 0. 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. shhh, it's fine ๐คซ-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) โ do not warn about incompatible integer to pointer and pointer to integer conversions. This warning is about implicit conversions; for explicit conversions the warnings-Wno-int-to-pointer-castand-Wno-pointer-to-int-castmay be used. receipts ๐-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
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.
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
}
Oh and btw, -Wzero-length-bounds gets switched on for you by -Warray-bounds โ no extra work, bestie ๐
-Wno-div-by-zeroโ okay so this one tells GCC to not warn when you divide an integer by zero at compile time. But floating-point division by zero? That one doesn't get warned about at all, because ngl it can be a totally legit way to get yourself an infinity or a NaN ๐-Wsystem-headersโ this makes GCC print warning messages for stuff it finds in system header files. Normally those warnings are โจsuppressedโจ because the assumption is they usually don't mean real problems and they just make the compiler output harder to read (fair tbh). Using this command-line option tells GCC to emit warnings from system headers as if they happened in your code. BUT โ heads up โ using-Walltogether with this option still does not warn about unknown pragmas in system headers. For that you also need-Wunknown-pragmas๐-Wtautological-compareโ warns you when a self-comparison always evaluates to true or false. Like, it catches these little mistakes, for example:
int i = 1;
...
if (i > i) { ... }
It also warns about bitwise comparisons that always evaluate to true or false, for instance:
if ((a & 16) == 10) { ... }
which, bestie, will always be false ๐
This warning is enabled by -Wall.
-Wtrampolinesโ warns about trampolines generated for pointers to nested functions. And what's a trampoline, you ask? It's a small piece of data or 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 ๐ For some targets it's made up of data only, so it needs no special treatment. But for most targets it's made up of code, which means the stack has to be made executable for the program to work properly. So yeah, that's the vibe.-Wfloat-equalโ warns if floating-point values are used in equality comparisons. The idea here is that sometimes it's convenient (for the programmer, not for the computer ๐ญ) to think of floating-point values as approximations to infinitely precise real numbers. If that's what you're doing, then you need to figure out (by analyzing the code, or some other way) the maximum, or likely maximum, error the computation introduces, and allow for it when you do comparisons (and when you produce output too, but that's a whole different problem). Specifically: instead of testing for equality, you should check whether the two values have ranges that overlap โ and that's done with the relational operators. So equality comparisons are probably mistaken, fr fr.-Wtraditional(C and Objective-C only) โ warns about certain constructs that behave differently in traditional C versus ISO C. It also warns about ISO C constructs that have no traditional C equivalent, and/or problematic constructs you should just avoid ๐- Macro parameters that show up inside string literals in the macro body. In traditional C, macro replacement happens inside string literals, but in ISO C it does not.
- In traditional C, some preprocessor directives did not exist. Traditional preprocessors only considered a line a directive if the
#appeared in column 1 on the line. So-Wtraditionalwarns about directives that traditional C understands but ignores because the#isn't the first character on the line. It also suggests you hide directives like#pragmathat traditional C doesn't understand by indenting them. Some traditional implementations don't 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. Some traditional C compilers don't accept this construct. - 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) โ warns if a prototype causes a type conversion that's different from what would happen to the same argument without 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 it's the same as the default promotion. ๐ฆ-Wdeclaration-after-statement(C and Objective-C only) โ warns 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, just so you know ๐-Wshadowโ warns 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 also includes all instances of local shadowing. Which means-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 (on top of-Wshadow=local) is based on the idea that when a local variable shadows another one of incompatible type, it's 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* โ warns whenever an object is defined whose size exceedsbyte-size.-Wlarger-than=PTRDIFF_MAXis enabled by default. Warnings controlled by this option can be disabled either by specifyingbyte-sizeofSIZE_MAXor more, or by-Wno-larger-than.
It also warns for calls to bounded functions such as memchr or strnlen that specify a bound greater than the largest possible object, which is PTRDIFF_MAX bytes by default. These warnings can only be disabled by -Wno-larger-than.
-Wno-larger-thanโ disable-Wlarger-than=warnings. This option is equivalent to-Wlarger-than=SIZE_MAXor larger ๐-Wframe-larger-than=byte-sizeโ bestie, this one yells at you if a function's stack frame is bigger than byte-size. BUT. And this is the important part ๐ โ the math it does to figure out the frame size is approximate and not conservative. So your actual stack needs might be a lil bit bigger than byte-size and it still won't warn you. Also, anything you grab withalloca, variable-length arrays, or related constructs? The compiler does not count that at all when deciding whether to warn.-Wframe-larger-than=PTRDIFF_MAXis on by default. Wanna turn the warnings off? Either pass a byte-size ofSIZE_MAXor more, or just use-Wno-frame-larger-than.-Wno-frame-larger-thanโ kills the-Wframe-larger-than=warnings. It's literally the same thing as-Wframe-larger-than=SIZE_MAXor bigger. Same energy, less typing ๐-Wno-free-nonheap-objectโ snitches on you when you try to deallocate something that either wasn't allocated on the heap at all, or you're freeing it through a pointer that didn't come back from the matching allocation function. Example time ๐ โstpcpyhands you back a pointer to the terminating nul character, NOT to the beginning of the object, so thisfreecall right here gets flagged:
void f (char *p)
{
p = stpcpy (p, "abc");
// ...
free (p); // warning
}
-Wfree-nonheap-object is enabled by default.
-Wstack-usage=byte-sizeโ warns you if a function's stack usage might go over byte-size. And unlike that last one, this computation is conservative โ it's not out here guessing cute. Anything fromalloca, variable-length arrays, or related constructs is included when the compiler decides whether to warn you.
The message matches the output of -fstack-usage.
- 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. To shut it up, either give a byte-size of SIZE_MAX or more, or use -Wno-stack-usage.
-Wno-stack-usageโ disables the-Wstack-usage=warnings. Equivalent to-Wstack-usage=SIZE_MAXor larger. Slay.-Wunsafe-loop-optimizationsโ warns you when a loop can't be optimized because the compiler can't assume anything about the bounds of the loop indices. And flip side ๐ โ with-funsafe-loop-optimizations, it warns if the compiler does make those assumptions.-Wno-pedantic-ms-format(MinGW targets only) โ when you pair this with-Wformatand-pedanticwithout GNU extensions, it shuts off the warnings about non-ISOprintf/scanfformat width specifiersI32,I64, andIon Windows targets. Those ones depend on the MS runtime, iykyk.-Wpointer-arithโ warns about anything that depends on the "size of" a function type or ofvoid. GNU C gives those types a size of1, purely for convenience when you're doing math withvoid *pointers and pointers to functions. In C++, it also warns when an arithmetic operation involvesNULL.-Wpedanticturns this one on too.-Wno-pointer-compareโ stops the warning when a pointer gets compared to a zero character constant. When that happens it usually means somebody meant to dereference the pointer. Like:
const char *p = foo ();
if (p == '\0')
return 42;
Heads up though โ that code up there is invalid in C++11. ๐
This warning is enabled by default.
-Wtsanโ warns about unsupported features in ThreadSanitizer.
ThreadSanitizer does not support std::atomic_thread_fence and 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 just that limited โ but it does not warn for constant expressions. So like, if you compare an unsigned variable against zero using<or>=? Warning.-Wextraenables this one too.-Wabsolute-value(C and Objective-C only) โ warns on calls to standard functions that compute the absolute value of an argument when there's a better-suited standard function sitting right there. Example: callingabs(3.14)triggers the warning, because the right function for the absolute value of adoubleargument isfabs. It also fires when the argument in a call to such a function has an unsigned type. You can suppress it with an explicit type cast, and-Wextraenables it too.-Wcomment-Wcommentsโ warns whenever a comment-start sequence/*shows up inside a/*comment, or whenever a backslash-newline shows up in a//comment. Enabled by-Wall.-Wtrigraphsโ warns if any trigraphs show up that could change the meaning of your program. Trigraphs inside comments don't get warned about โ except the ones that would form escaped newlines.
This option is implied by -Wall. If -Wall isn't given, it's still enabled unless trigraphs are enabled. Want trigraph conversion with no warnings but all the other -Wall warnings? Use -trigraphs -Wall -Wno-trigraphs.
-Wundefโ warns if an undefined identifier gets evaluated in an#ifdirective. Those identifiers just get replaced with zero, no cap.-Wexpansion-to-definedโ warns wheneverdefinedshows up in the expansion of a macro (including when the macro is expanded by an#ifdirective). That usage is not portable.-Wpedanticand-Wextraenable this one too.-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 also warns if the macro hadn't been used by the time it got redefined or undefined.
Built-in macros, macros defined on the command line, and macros defined in include files don't get warned about.
Note: if a macro actually is used but only inside skipped conditional blocks, the preprocessor will report it as unused. To dodge the warning in that case, you could tighten up the macro's scope by โ for example โ moving it into the first skipped block. Or you could just 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 sometimes in older programs with code shaped like:
#if FOO
...
#else FOO
...
#endif FOO
That second and third FOO should be in comments, bestie. This warning is on by default.
-Wbad-function-cast(C and Objective-C only) โ warns when a function call gets cast to a type that doesn't match. Like, warn if a call to a function returning an integer type gets cast to 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. For instance: variable length arrays, thelong longtype, thebooltype, compound literals, designated initializers, and so on. This option is independent of the standards mode. Warnings are disabled inside 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 that aren't in ISO C11 but are in ISO C2X. For instance: omitting the string in_Static_assert, using[[]]syntax for attributes, using decimal floating-point types, and so on. Independent of the standards mode. Warnings are disabled in the expression that follows__extension__.-Wc++-compat(C and Objective-C only) โ warns about ISO C constructs that fall outside the common subset of ISO C and ISO C++. Example: a request for implicit conversion fromvoid *to a pointer to 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. Example: identifiers in ISO C++ 1998 that are 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.-Wcast-qualโ warns whenever a pointer is cast in a way that strips a type qualifier off the target type. Like, warn if aconst char *gets cast to a plain oldchar *.
It also warns when a cast introduces a type qualifier in an unsafe way. For example, casting char ** to const char ** is unsafe โ check it:
/* 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 is cast in a way that increases the required alignment of the target. Example: warn if achar *gets cast to anint *on machines where integers can only be accessed at two- or four-byte boundaries. ๐ฆ-Wcast-align=strictโ bestie, this one screams at you whenever a pointer gets cast in a way that increases the alignment the target needs. Like, if achar *gets cast to anint *? Warning. Doesn't matter what machine you're on โ every target, no exceptions. ๐-Wcast-function-typeโ warns when you cast a function pointer to an incompatible function pointer. Okay so the deets: if the cast involves function types with a variable argument list, only the types of the initial arguments that are actually provided get considered. Any parameter of pointer-type matches any other pointer-type. Any benign differences in integral types are just ignored, likeintvs.longon ILP32 targets. Same energy for type qualifiers โ ignored. The function typevoid (*) (void)is special and matches literally everything, which you can use to suppress this warning. And if the cast involves pointer to member types, this warns 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 that 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 super careful about usingconstin declarations and prototypes. Otherwise it's just a nuisance. That's literally why-Walldoesn't request these warnings. ๐ซถ When compiling C++, it warns about the deprecated conversion from string literals tochar *. This warning is enabled by default for C++ programs.-Wclobberedโ warns for variables that might be changed bylongjmporvfork. Also enabled by-Wextra. ๐-Wconversionโ warns for implicit conversions that may alter a value. This includes:- conversions between real and integer, like
abs (x)whenxisdouble; - conversions between signed and unsigned, like
unsigned ui = -1; - and 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.
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 could be confusion over whichifstatement anelsebranch belongs to. Here's an example of that exact situation:
{
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's often not what the programmer expected โ as illustrated above by the indentation the programmer chose. When there's potential for this confusion, GCC issues a warning when this flag is specified. To kill the warning, add explicit braces around the innermost if statement so there's no way the else can belong to the enclosing if. The resulting code looks like this:
{
if (a)
{
if (b)
foo ();
else
bar ();
}
}
This warning is enabled by -Wparentheses. ๐
-Wdate-timeโ warns when macros__TIME__,__DATE__or__TIMESTAMP__are encountered, because they might prevent bit-wise-identical reproducible compilations. ๐-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. This warning is enabled by-Wextrain C. ๐ธ-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. This warning is 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 is 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 enabled also by-Wconversion. ๐-Wfloat-conversionโ warns for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values. This option is 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 two sizeof operators 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 won't yield the number of elements in the array โ which is probably what the user intended. This warning warns e.g. about:
int fn ()
{
int arr[10];
return sizeof (arr) / sizeof (short);
}
This warning is enabled by -Wall. ๐
-Wsizeof-pointer-divโ warns for suspicious divisions of two sizeof expressions that divide the pointer size by the element size โ which is the usual way to compute the array size but won't work out correctly with pointers. This warning warns e.g. aboutsizeof (ptr) / sizeof (ptr[0])ifptris not an array, but a pointer. This warning is enabled by-Wall. ๐-Wsizeof-pointer-memaccessโ warns for suspicious length parameters to certain string and memory built-in functions if the argument usessizeof. This warning triggers, for example, formemset (ptr, 0, sizeof (ptr));ifptris not an array, but a pointer, and suggests a possible fix โ or aboutmemcpy (&foo, ptr, sizeof (&foo));.-Wsizeof-pointer-memaccessalso warns about calls to bounded string copy functions likestrncatorstrncpythat specify as the bound asizeofexpression of the source array. For example, in the following function the call tostrncatspecifies the size of the source string as the bound. That is almost certainly a mistake, and so the call is diagnosed. ๐ญ
void make_file (const char *name)
{
char path[PATH_MAX];
strncpy (path, name, sizeof path - 1);
strncat (path, ".text", sizeof ".text");
...
}
The -Wsizeof-pointer-memaccess option is enabled by -Wall. โจ
-Wno-sizeof-array-argumentโ do not warn when thesizeofoperator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs. ๐-Wmemset-elt-sizeโ warns for suspicious calls to thememsetbuilt-in function, if 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 means the user has omitted a multiplication by the element size. This warning is enabled by-Wall. ๐-Wmemset-transposed-argsโ warns for suspicious calls to thememsetbuilt-in function where the second argument is not zero and the third argument is zero. For example, the callmemset (buf, sizeof buf, 0)is diagnosed becausememset (buf, 0, sizeof buf)was meant instead. The diagnostic is only emitted if the third argument is a literal zero. Otherwise, if it's an expression that is folded to zero, or a cast of zero to some type, it's far less likely that the arguments have been mistakenly transposed and no warning is emitted. This warning is enabled by-Wall. ๐ฅ-Waddressโ warns about suspicious uses of memory addresses. These include using the address of a function in a conditional expression, such asvoid func(void); if (func), and comparisons against the memory address of a string literal, such asif (x == "abc"). Such uses typically indicate a programmer error: the address of a function always evaluates to true, so their use in a conditional usually indicates that the programmer forgot the parentheses in a function call; and comparisons against string literals result in unspecified behavior and are not portable in C, so they usually indicate that the programmer intended to usestrcmp. This warning is enabled by-Wall. ๐-Wno-address-of-packed-memberโ do not warn when the address of a packed member of a struct or union is taken, which usually results in an unaligned pointer value. This is 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 likely to be expected. It also warns when the operands of a logical operator are the same: ๐
extern int a;
if (a < 0 && a < 0) { ... }
-Wlogical-not-parenthesesโ bestie, this one's out here catching the โจsuspiciousโจ stuff. It yells at you when you slap a logical not on the left-hand side operand of a comparison. It stays quiet if the right operand is considered a boolean expression, so don't worry about that case. Its whole purpose in life? Sniffing out code like this:
int a;
...
if (!a > 1) { ... }
You can hush the warning by wrapping the LHS into parentheses, like so:
if ((!a) > 1) { ... }
This warning is enabled by -Wall. ๐
-Waggregate-returnโ warns if any functions that return structures or unions are defined or called. (In languages where you can return an array, this also elicits a warning.) Not the vibe it wants, apparently. ๐ญ-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. lowkey alarming fr fr.-Wno-attributesโ do not warn if an unexpected__attribute__is used โ think unrecognized attributes, function attributes applied to variables, etc. Important though: this does not stop errors for incorrect use of supported attributes. no cap.-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 does not include a prototype is called with arguments whose promoted types do not match those expected by the function. When-Wextrais specified, it also warns when a built-in function that takes arguments is declared without a prototype. The-Wbuiltin-declaration-mismatchwarning is enabled by default. To avoid the warning, include the appropriate header to bring the prototypes of built-in functions into scope. ๐ซถ
For example, the call to memset below is diagnosed by the warning 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 is 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__. periodt. ๐-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 preceded by a declaration that specifies the argument types.) okay slay, it's flexible.-Wold-style-declaration(C and Objective-C only) โ warns for obsolescent usages, according to the C Standard, in a declaration. For example, warn if storage-class specifiers likestaticare not 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 is a previous prototype. Here's the cute lil nuance: a definition using()is not considered an old-style definition in C2X mode, because it is 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) โ 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. And it warns even if the definition itself provides a prototype. Use this option to detect global functions that do not have a matching prototype declaration in a header file. Heads up bestie: this option is not valid for C++, because all function declarations provide prototypes and a non-matching declaration declares an overload rather than conflict with an earlier declaration. For C++, use-Wmissing-declarationsto detect missing declarations instead. ๐-Wmissing-declarationsโ warns if a global function is defined without a previous declaration. It does so even if the definition itself provides a prototype. Use this option to detect global functions that are not 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. iykyk. โจ-Wmissing-field-initializersโ warns if a structure's initializer has some fields missing. For example, the following 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 the following modification does not trigger a warning:
struct s { int f, g, h; };
struct s x = { .f = 3, .g = 4 };
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 does not warn about the empty { } initializer, for example:
struct s { int f, g, h; };
s x = { };
This warning is included in -Wextra. To get other -Wextra warnings without this one, use -Wextra -Wno-missing-field-initializers. ๐
-Wno-multicharโ do not warn if a multicharacter constant ('FOOF') is used. Usually they indicate a typo in the user's code, as they have implementation-defined values, and should not be used in portable code. ๐-Wnormalized=[none|id|nfc|nfkc]โ okay so in ISO C and ISO C++, two identifiers are different if they are different sequences of characters. BUT โ sometimes when characters outside the basic ASCII character set are used, you can have two different character sequences that look the same. ๐ญ To avoid confusion, the ISO 10646 standard sets out some normalization rules which, when applied, ensure that two sequences that look the same are turned into the same sequence. GCC can warn you if you are using identifiers that have not been normalized, and this option controls that warning.
There are four levels of warning supported by GCC. The default is -Wnormalized=nfc, which warns about any identifier that is not in the ISO 10646 "C" normalized form, NFC. NFC is the recommended form for most uses. It is 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. That is, 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. It is hoped that future versions of the standards involved will correct this, which is why this option is not 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 are using some other normalization scheme (like "D"), because otherwise you can easily create bugs that are literally impossible to see. scary fr.
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 has 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 is not in NFKC if you use -Wnormalized=nfkc. This warning is comparable to warning about every identifier that contains the letter O because it might be confused with the digit 0, and so is not the default, but may be useful as a local coding convention if the programming environment cannot be fixed to display these characters distinctly. ๐ฆ
-Wno-attribute-warningโ do not warn about usage of functions declared withwarningattribute. 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-Werrorflag. ๐ธ-Wno-deprecatedโ do not warn about usage of deprecated features. it's giving "we know, we know". ๐-Wno-deprecated-declarationsโ do not warn about uses of functions, variables, and types marked as deprecated by using thedeprecatedattribute.-Wno-overflowโ do not warn about compile-time overflow in constant expressions.-Wno-odrโ warns about One Definition Rule violations during link-time optimization. Enabled by default. ๐ฅ-Wopenmp-simdโ warns 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) โ warns 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โ warns 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;
};
lowkey wasteful, highkey worth a warning. ๐
-Wnopacked-bitfield-compatโ bestie, the 4.1, 4.2 and 4.3 series of GCC literally ignore the "packed" attribute on bit-fields of type"char". Rude, right? It got fixed in GCC 4.4, but the glow-up came with consequences: the change can lead to differences in the structure layout. GCC will tell you when the offset of such a field has changed in GCC 4.4. For example, there is no longer a 4-bit padding between field"a"and"b"in 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) โ warns you if a structure field with explicitly specified alignment in a packed struct or union is misaligned. For example, a warning will be issued on"struct 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โ warns 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 is possible to rearrange the fields of the structure to reduce the padding and so make the structure smaller. Lowkey a free size-up, no cap. โจ-Wredundant-declsโ warns if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing. Like saying the same thing twice. We get it girl, we heard you the first time. ๐-Wrestrictโ warns 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. However, because the call writes the terminating NUL into"a[4]", the copies overlap and the call is diagnosed.
void foo (void)
{
char a[] = "abcd1234";
strcpy (a, a + 4);
...
}
The -Wrestrict option detects some instances of simple overlap even without optimization but works best at -O2 and above. It is included in -Wall. ๐ฅ
-Wnested-externs(C and Objective-C only) โ warns if an"extern"declaration is encountered within a function. Nested. In a function. Bestie what are you doing. ๐-Winlineโ warns if a function that is declared as inline cannot be inlined. Even with this option, the compiler does not warn about failures to inline functions declared in system headers.
The compiler uses a 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 has already been done in the current function. Therefore, seemingly insignificant changes in the source program can cause the warnings produced by -Winline to appear or disappear. It's giving โจchaosโจ.
-Wint-in-bool-contextโ warns for suspicious use of integer values where boolean values are expected, such as conditional expressions (?:) using non-boolean integer constants in boolean context, like"if (a <= b ? 2 : 3)". Or left shifting of signed integers in boolean context, like"for (a = 0; 1 << a; a++);". Likewise for all kinds of multiplications regardless of the data type. This warning is enabled by-Wall. ๐ซถ-Wno-int-to-pointer-castโ suppresses warnings from casts to pointer type of an integer of a different size. 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 casts 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 cannot be used. Found but unusable? Tragic. ๐ญ-Wlong-longโ warns if"long long"type is used. This is enabled by either-Wpedanticor-Wtraditionalin ISO C90 and C++98 modes. To inhibit the warning messages, use-Wno-long-long. Long long. Long long. Say it with me. ๐ฆ-Wvariadic-macrosโ warns if variadic macros are used in ISO C90 mode, or if the GNU alternate syntax is used in ISO C99 mode. This is enabled by either-Wpedanticor-Wtraditional. To inhibit the warning messages, use-Wno-variadic-macros. ๐ธ-Wno-varargsโ do not warn upon questionable usage of the macros used to handle variable arguments like"va_start". These warnings are enabled by default. ๐-Wvector-operation-performanceโ warns if vector operation is not implemented via SIMD capabilities of the architecture. Mainly useful for the performance tuning. Vector operation can be implemented"piecewise", which means that the scalar operation is performed on every vector element;"in parallel", which means that the vector operation is implemented using scalars of wider type, which normally is more performance efficient; and"as a single scalar", which means that vector fits into a scalar type. Three flavours, pick your fighter. โญ-Wvlaโ warns if a variable-length array is used in the code.-Wno-vlaprevents the-Wpedanticwarning of the variable-length array.-Wvla-larger-than=byte-sizeโ if this option is used, the compiler warns for declarations of variable-length arrays whose size is either unbounded, or bounded by an argument that allows the array size to exceed byte-size bytes. This is similar to how-Walloca-larger-than=byte-sizeworks, but with variable-length arrays.
Note that GCC may optimize small variable-length arrays of a known value into plain arrays, so this warning may not get triggered for such arrays. Slippery little things. ๐ง
-Wvla-larger-than=PTRDIFF_MAX is enabled by default but is typically only effective when -ftree-vrp is active (default for -O2 and above).
See also -Walloca-larger-than=byte-size.
-Wno-vla-larger-thanโ disable-Wvla-larger-than=warnings. The option is 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 by warnings such as-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 declared volatile. The volatile modifier does not inhibit all optimizations that may eliminate reads and/or writes to register variables. This warning is enabled by-Wall.-Wdisabled-optimizationโ warns if a requested optimization pass is disabled. This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC's optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time. It's not you, it's the optimizer's schedule. ๐ญ-Wpointer-sign(C and Objective-C only) โ warns for pointer argument passing or assignment with different signedness. This option is only supported for C and Objective-C. It is 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 are not protected against stack smashing. Not me leaving the door unlocked. ๐ช๐-Woverlength-stringsโ warns about string constants that are longer than the"minimum maximum"length specified in the C standard. Modern compilers generally allow string constants that are 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 does not count the trailing NUL. In C90, the limit was 509 characters; in C99, it was raised to 4095. C++98 does not specify a normative minimum maximum, so we do not diagnose overlength strings in C++.
This option is implied by -Wpedantic, and can be disabled with -Wno-overlength-strings. 509 to 4095 is a glow up fr fr. ๐ฅ
-Wunsuffixed-float-constants(C and Objective-C only) โ issue a warning for any floating constant that does not have a suffix. When used together with-Wsystem-headersit warns about such constants in system header files. This can be useful when preparing code to use with the"FLOAT_CONST_DECIMAL64"pragma from the decimal floating-point extension to C99.-Wno-lto-type-mismatchโ during the link-time optimization, do not 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) โ suppress warnings when a positional initializer is used to initialize a structure that has been marked with the"designated_init"attribute.
๐ Options That Control Static Analysis ๐
-fanalyzerโ this option enables an static analysis of program flow which looks for"interesting"interprocedural paths through the code, and issues warnings for problems found on them. ๐๐
okay so real talk bestie โ this analysis is so much more expensive than the other GCC warnings, like it's the designer bag of diagnostics, it costs, but it serves.
Turning this one on is basically enabling this whole little squad:
-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-possible-null-argument
-Wanalyzer-possible-null-dereference -Wanalyzer-null-argument
-Wanalyzer-null-dereference -Wanalyzer-shift-count-negative
-Wanalyzer-shift-count-overflow -Wanalyzer-stale-setjmp-buffer
-Wanalyzer-tainted-array-index
-Wanalyzer-unsafe-call-within-signal-handler
-Wanalyzer-use-after-free
-Wanalyzer-use-of-pointer-in-stale-stack-frame
-Wanalyzer-write-to-const -Wanalyzer-write-to-string-literal
heads up ๐ this option is only available if GCC was configured with analyzer support enabled. no analyzer support, no party, sorry.
๐ธ -Wanalyzer-too-complex ๐ธ
If -fanalyzer is on, the analyzer runs a bunch of heuristics to try and explore the control flow and data flow in your program, but complicated code can absolutely body those heuristics. It's giving "the vibes were immaculate but the graph was too big."
By default, the analysis just silently stops if the code is too complicated for the analyzer to fully explore and it hits an internal limit. Silently! Rude, honestly. The -Wanalyzer-too-complex option warns you when that happens, so you actually know your analysis ghosted you.
โจ -Wno-analyzer-double-fclose โจ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-double-fclose to disable it.
This diagnostic warns for paths through the code in which a "FILE *" can have "fclose" called on it more than once. Closing a file twice? That's not closure, bestie, that's a double-close.
๐ -Wno-analyzer-double-free ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-double-free to 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". Double free is the original villain arc.
๐ฆ -Wno-analyzer-exposure-through-output-file ๐ฆ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-exposure-through-output-file to disable it.
This diagnostic warns for paths through the code in which a security-sensitive value is written to an output file (such as writing a password to a log file). Do NOT log the password, I am begging ๐ญ
๐ธ -Wno-analyzer-file-leak ๐ธ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-file-leak to disable it.
This diagnostic warns for paths through the code in which a "<stdio.h>" "FILE *" stream object is leaked. It's giving "you opened it, you never closed it, and now it's just... out there."
๐
-Wno-analyzer-free-of-non-heap ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-free-of-non-heap to disable it.
This diagnostic warns for paths through the code in which "free" is called on a non-heap pointer (e.g. an on-stack buffer, or a global). Ma'am that memory was never malloc'd, put it down.
๐ซถ -Wno-analyzer-malloc-leak ๐ซถ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-malloc-leak to disable it.
This diagnostic warns for paths through the code in which a pointer allocated via an allocator is leaked: either "malloc", or a function marked with attribute "malloc". The allocation said "I'll be back" and then just... never came back. ๐
๐ -Wno-analyzer-mismatching-deallocation ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-mismatching-deallocation to disable it.
This diagnostic warns for paths through the code in which the wrong deallocation function is called on a pointer value, based on which function was used to allocate the pointer value. The diagnostic will warn about mismatches between "free", scalar "delete" and vector "delete[]", and those marked as allocator/deallocator pairs using attribute "malloc". You have to free it the way you birthed it, that's the rule.
โญ -Wno-analyzer-possible-null-argument โญ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-argument to disable it.
This diagnostic warns for paths through the code in which a possibly-NULL value is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value. You told the function it'd never get NULL and then you... maybe handed it NULL. ๐
๐ -Wno-analyzer-possible-null-dereference ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-possible-null-dereference to disable it.
This diagnostic warns for paths through the code in which a possibly-NULL value is dereferenced. Could be NULL, could be fine, but the analyzer is side-eyeing it.
๐ฅ -Wno-analyzer-null-argument ๐ฅ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-argument to disable it.
This diagnostic warns for paths through the code in which a value known to be NULL is passed to a function argument marked with "__attribute__((nonnull))" as requiring a non-NULL value. Not "possibly" this time โ we know. It's confirmed. It's over.
๐ -Wno-analyzer-null-dereference ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-null-dereference to disable it.
This diagnostic warns for paths through the code in which a value known to be NULL is dereferenced. That's the crash, that's the segfault, that's the whole thing. ๐
๐ -Wno-analyzer-shift-count-negative ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-negative to disable it.
This diagnostic warns for paths through the code in which a shift is attempted with a negative count. It is analogous to the -Wshift-count-negative diagnostic implemented in the C/C++ front ends, but is 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. (iykyk, it's just not the analyzer's main character moment.)
๐ฆ -Wno-analyzer-shift-count-overflow ๐ฆ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-shift-count-overflow to disable it.
This diagnostic warns for paths through the code in which a shift is attempted with a count greater than or equal to the precision of the operand's type. It is analogous to the -Wshift-count-overflow diagnostic implemented in the C/C++ front ends, but is 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 ๐ธ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-stale-setjmp-buffer to disable it.
This diagnostic warns for paths through the code in which "longjmp" is called to rewind to a "jmp_buf" relating to a "setjmp" call in a function that has returned.
When "setjmp" is called on a "jmp_buf" to record a rewind location, it records the stack frame. The stack frame becomes invalid when the function containing the "setjmp" call returns. Attempting 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-array-index ๐
This warning requires both -fanalyzer and -fanalyzer-checker=taint to enable it; use -Wno-analyzer-tainted-array-index to disable it.
This diagnostic warns for paths through the code in which a value that could be under an attacker's control is used as the index of an array access without being sanitized. Untrusted input driving your index? Absolutely not, sanitize it first.
๐ -Wno-analyzer-unsafe-call-within-signal-handler ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-unsafe-call-within-signal-handler to disable it.
This diagnostic warns for paths through the code in which a function known to be async-signal-unsafe (such as "fprintf") is called from a signal handler. Signal handlers are not the place, bestie, they have strict rules.
๐ซถ -Wno-analyzer-use-after-free ๐ซถ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-after-free to disable it.
This diagnostic warns for paths through the code in which a pointer is used after a deallocator is called on it: either "free", or a deallocator referenced by attribute "malloc". Using memory after you freed it is the ghost of a pointer and it will haunt you.
โญ -Wno-analyzer-use-of-pointer-in-stale-stack-frame โญ
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-use-of-pointer-in-stale-stack-frame to disable it.
This diagnostic warns for paths through the code in which a pointer is dereferenced that points to a variable in a stale stack frame. That variable left the building and the pointer is still texting it. ๐
๐ -Wno-analyzer-write-to-const ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-write-to-const to disable it.
This diagnostic warns for paths through the code in which the analyzer detects an attempt to write through a pointer to a "const" object. However, the analyzer does not prioritize detection of such paths, so false negatives are more likely relative to other warnings. You said const. That means const. Periodt. ๐
๐ -Wno-analyzer-write-to-string-literal ๐
This warning requires -fanalyzer, which enables it; use -Wno-analyzer-write-to-string-literal to disable it.
This diagnostic warns for paths through the code in which 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. Writing into a string literal is undefined behaviour and the vibes are rancid.
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. These are your little dials, your sliders, your knobs for how hard the analyzer goes. ๐ฅ
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. It's giving "let's summarize the meeting instead of reading every single message in the thread."
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). So it's picky about who gets summarized. As it should be. ๐
๐ง -fanalyzer-checker=name ๐ง
Restrict the analyzer to run just the named checker, and enable it. One checker, one job, no distractions.
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. So if taint isn't doing its thing, this is why โ you gotta invite it.
๐ -fno-analyzer-feasibility ๐
This option is intended for analyzer developers.
By default the analyzer verifies that there is a feasible control flow path for each diagnostic it emits: that the conditions that hold are not mutually exclusive. Diagnostics for which no feasible path can be found are rejected. This filtering can be suppressed with -fno-analyzer-feasibility, for debugging issues in this code. Debugging mode, not bestie mode.
๐ -fanalyzer-fine-grained ๐
This option is intended for analyzer developers.
(...and we're picking that thought right back up in the next part, hold on, don't go anywhere ๐)
okay so internally the analyzer builds this whole entire thing called an "exploded graph" โ and bestie it's literally just control flow graphs combined with data flow information. that's it. that's the graph. ๐
by default, an edge in this graph can contain the effects of a run of multiple statements within a basic block. but with -fanalyzer-fine-grained, every single statement gets its own edge. one statement, one edge, no sharing, periodt. โจ
-fanalyzer-show-duplicate-countโ this one is for analyzer developers, iykyk. if multiple diagnostics got detected as duplicates of each other, it emits a note when reporting the best diagnostic, and that note tells you the number of additional diagnostics that got suppressed by the deduplication logic. ๐ซถ-fno-analyzer-state-mergeโ also for analyzer developers, bestie, don't worry about it unless that's you. by default the analyzer tries to simplify analysis by merging sufficiently similar states at each program point as it builds its "exploded graph". with-fno-analyzer-state-mergethat merging can be suppressed, for debugging state-handling issues. ๐ฆ-fno-analyzer-state-purgeโ again, analyzer developers 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โ enables transitivity of constraints within the analyzer. that's the whole thing. slay. โจ-fanalyzer-verbose-edgesโ analyzer developer option, bestie. it enables more verbose, lower-level detail in the descriptions of control flow within diagnostic paths. ๐ธ-fanalyzer-verbose-state-changesโ also for the analyzer developers. it enables more verbose, lower-level detail in the descriptions of events relating to state machines within diagnostic paths. ๐-fanalyzer-verbosity=levelโ this one controls the complexity of the control flow paths that get emitted for analyzer diagnostics. the level can be one of these, and yes we're going through all of them:- 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. this option is overridden by-fdump-analyzer-stderr. ๐-fdump-analyzer-stderrโ dumps internal details about what the analyzer is doing tostderr. this option overrides-fdump-analyzer. take that, previous option. ๐-fdump-analyzer-callgraphโ dumps a representation of the call graph suitable for viewing with GraphViz tofile.callgraph.dot. ๐-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. so aesthetic. โจ-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. this is typically a large number of dump files, so like... be aware. ๐ญ-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.dotandfile.*.tg.dot. ๐-fdump-analyzer-jsonโ dumps a compressed JSON representation of analyzer internals tofile.analyzer.json.gz. the precise format is subject to change, ngl. ๐-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. two dumps, one option, iconic. ๐
โจ Options for Debugging Your Program โจ
to tell GCC to emit extra information for use by a debugger, in almost all cases you need only to add -g to your other options. that's it. that's the whole vibe. ๐
GCC allows you to use -g with -O. but bestie, the shortcuts taken by optimized code may occasionally be surprising: 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.
if you are not using some other optimization option, consider using -Og with -g. with no -O option at all, some compiler passes that collect information useful for debugging do not run at all, so that -Og may result in a better debugging experience. โจ
-gโ produces 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โ produces 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. ๐-gdwarf,-gdwarf-versionโ produces debugging information in DWARF format (if that is supported). the value of version may be either2,3,4or5; the default version for most targets is5(with the exception of VxWorks, TPF and Darwin/Mac OS X, which default to version2, and AIX, which defaults to version4). ๐
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. history is messy like that. ๐
-gstabsโ produces debugging information in stabs format (if that is supported), without GDB extensions. this is the format used by DBX on most BSD systems. on MIPS, Alpha and System V Release 4 systems this option produces stabs debugging output that is not understood by DBX. on System V Release 4 systems this option requires the GNU assembler. ๐ญ-gstabs+โ produces debugging information in stabs format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). the use of these extensions is likely to make other debuggers crash or refuse to read the program. ๐-gxcoffโ produces debugging information in XCOFF format (if that is supported). this is the format used by the DBX debugger on IBM RS/6000 systems. ๐ฆ-gxcoff+โ produces debugging information in XCOFF format (if that is supported), using GNU extensions understood only by the GNU debugger (GDB). the use of these extensions is likely to make other debuggers crash or refuse to read the program, and may cause assemblers other than the GNU assembler (GAS) to fail with an error. ๐-gvmsโ produces debugging information in Alpha/VMS debug format (if that is supported). this is the format used by DEBUG on Alpha/VMS systems. ๐-glevel,-ggdblevel,-gstabslevel,-gxcofflevel,-gvmslevelโ requests debugging information and also uses level to specify how much information. the default level is2. and now the levels, bestie, all of them:- Level
0produces no debug information at all. thus,-g0negates-g. โจ - Level
1produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. this includes descriptions of functions and external variables, and line number tables, but no information about local variables. - Level
3includes extra information, such as 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 is effective. periodt.
-gdwarf does not accept a concatenated debug level, to avoid confusion with -gdwarf-level. instead use an additional -glevel option to change the debug level for DWARF. don't try to be clever, just pass the extra flag. ๐
-fno-eliminate-unused-debug-symbolsโ by default, no debug information is produced for symbols that are not actually used. use this option if you want debug information for all symbols. all of them. every single one. ๐-femit-class-debug-alwaysโ bestie, normally GCC emits the debugging info for a C++ class in one single object file and calls it a day. This flag says "no, put it in every object file that uses the class." Only reach for this if your debugger literally cannot handle the way GCC normally does class debug info, because the price of admission is that your debugging information can balloon by as much as a factor of two. ๐-fno-merge-debug-stringsโ tells the linker to not merge together strings in the debugging information that are identical across different object files. Important caveat: merging isn't supported by all assemblers or linkers in the first place. Merging shrinks the debug info in the output file but costs you link processing time. And btw, merging is enabled by default, so this flag is the "actually, don't" version.-fdebug-prefix-map=old=newโ when you're compiling files that live in directory old, record the debugging information as if they lived in directory new instead. Iconic use case: swap a build-time path for an install-time path in the debug info. You can also flip an absolute path into a relative one by using.for new. This gives you more reproducible builds that are location independent, but you might need an extra command to tell GDB where the source files actually are. See also-ffile-prefix-map. ๐ซถ-fvar-trackingโ runs the variable tracking pass, which figures out where variables are stored at each position in the code. Then better debugging information gets generated (assuming the debug info format supports that info, ofc). It's on by default when you compile with optimization (-Os,-O,-O2, ...), debugging information (-g), and the debug info format supports it. โจ-fvar-tracking-assignmentsโ annotates assignments to user variables early in compilation, then tries to carry those annotations all the way to the end, all in the name of better debug info while optimizing. Pairing it with-gdwarf-4is recommended. Fun fact: it can be enabled even when var-tracking is disabled โ in that case the annotations get created and maintained, then discarded at the end. By default it's enabled together with-fvar-tracking, except when selective scheduling is enabled.-gsplit-dwarfโ if DWARF debugging information is enabled, split as much of it as possible into a separate output file with the.dwoextension. This lets the build system avoid linking files that have debug info in them. To actually be useful though, you need a debugger that can read.dwofiles. No cap. ๐ฆ-gdwarf32,-gdwarf64โ with DWARF debugging info enabled,-gdwarf32picks the 32-bit DWARF format and-gdwarf64picks the 64-bit one. The default is target specific, but on most targets it's-gdwarf32. The 32-bit format is smaller, but it can't support more than 2GiB of debug information in any of the DWARF debug information sections. The 64-bit format allows bigger debug info, but heads up: it might not be well supported by all consumers yet. ๐-gdescribe-diesโ adds description attributes to some DWARF DIEs that have no name attribute, like artificial variables, external references and call site parameter DIEs.-gpubnamesโ generates the DWARF.debug_pubnamesand.debug_pubtypessections.-ggnu-pubnamesโ generates.debug_pubnamesand.debug_pubtypessections in a format that's suitable for conversion into a GDB index. This one is only useful with a linker that can produce GDB index version 7.-fdebug-types-sectionโ when you're on 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 because the linker can then remove duplicates. But plot twist: not all DWARF consumers support.debug_typessections yet, and on some objects.debug_typesproduces larger instead of smaller debugging information. ๐ญ-grecord-gcc-switches,-gno-record-gcc-switchesโ this switch appends the command-line options used to invoke the compiler that may affect code generation onto theDW_AT_producerattribute in DWARF debugging information. 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 from a later DWARF standard version than the one selected with-gdwarf-version. On most targets, using non-conflicting DWARF extensions from later standard versions is allowed, so this is you saying "no thank you, keep it strict." ๐ธ-gno-strict-dwarfโ allows using extensions of later DWARF standard versions than the one selected with-gdwarf-version. The chill option. ๐ง-gas-loc-supportโ informs the compiler that the assembler supports.locdirectives. It may then use them so the assembler generates 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. It'll be enabled by default if, at GCC configure time, the assembler was found to support those directives.-gno-as-loc-supportโ forces GCC to generate DWARF2+ line number tables internally, if DWARF2+ line number tables are going to be generated at all.-gas-locview-supportโ informs the compiler that the assembler supports "view" assignment and reset assertion checking in.locdirectives. 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โ emits location column information into DWARF debugging information, rather than just file and line. Enabled by default.-gstatement-frontiers,-gno-statement-frontiersโ makes GCC create markers in the internal representation at the beginning of statements, then 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,-O,-O2, ...) and outputting DWARF 2 debug information 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 information consumers inspect state at certain points of the program, even when 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 causes 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 debug info consumers that don't know about these augmentations can still consume them โ they just won't get any benefit from them either. ๐
This is enabled by default when outputting DWARF 2 debug information 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, it may still be enabled, but it will force GCC to output internal line number tables, and if -ginternal-reset-location-views is not enabled, that will most certainly lead to silently mismatching location views. ๐ญ
There's a proposed representation for view numbers that is not backward compatible with the location list format introduced in DWARF 5, enabled with -gvariable-location-views=incompat5. This option may be removed in the future, and it's only provided as a reference implementation of the proposed representation. Debug information consumers aren't expected to support this extended format, and they'd be rendered unable to decode location lists that use it.
-ginternal-reset-location-views,-gno-internal-reset-location-viewsโ attempts to determine location views that can be omitted from location view lists. This requires the compiler to have very accurate insn length estimates, which isn't always the case, and it may cause incorrect view lists to be generated silently when using an assembler that doesn't support location view lists. The GNU assembler will flag any such error as a "view number mismatch". Only enabled on ports that define a reliable estimation function.-ginline-points,-gno-inline-pointsโ generates extended debug information for inlined functions. Location view tracking markers get inserted at inlined entry points so that address and view numbers can be computed and output in the debug info. It can be enabled independently of location views โ in that case the view numbers just won't be output โ but it can only be enabled along with statement frontiers, and it's only enabled by default if location views are enabled.-gz[=type]โ produces compressed debug sections in DWARF format, if that's supported. If type isn't given, the default type depends on the capabilities of the assembler and linker you're using. type can be one ofnone(don't compress debug sections),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. Otherwise, if the assembler doesn't support them,-gzis silently ignored when producing object files. ๐-femit-struct-debug-baseonlyโ emits debug information 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 substantially reduces the size of debugging information, but at a significant potential loss in type information to the debugger. See-femit-struct-debug-reducedfor a less aggressive option, and-femit-struct-debug-detailedfor more detailed control. This option works only with DWARF debug output. ๐
-femit-struct-debug-reducedโ bestie, this one is โจpickyโจ about which struct-like types get debug info. GCC only emits it 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 it lives in a system header. It shrinks your debug info a lot, but lowkey you might lose some type info in the debugger. Want something more aggressive? That's-femit-struct-debug-baseonly. Want the full control freak version?-femit-struct-debug-detailed. Heads up though: this only works with DWARF debug output. ๐ฆ-femit-struct-debug-detailed[=spec-list]โ the main-character version of the two options above, fr fr. You tell GCC exactly which struct-like types it should generate debug info for, and the whole point is to cut down on duplicate struct debug info across different object files in the same program. It's the detailed edition of-femit-struct-debug-reducedand-femit-struct-debug-baseonly, and ngl it handles most people's needs all by itself.
A specification looks like this, exactly:
[dir:|ind:][ord:|gen:](any|sys|base|none)
The optional first word narrows the spec to structs used directly (dir:) or indirectly (ind:). A struct type is used directly when it's the type of a variable or a member. Indirect uses come through pointers to structs โ like, when using an incomplete struct is valid, that use is indirect. The example, verbatim: struct one direct; struct two * indirect;.
The optional second word narrows it to ordinary structs (ord:) or generic structs (gen:). Generic structs areโฆ a whole thing to explain ๐. For C++, these are non-explicit specializations of template classes, or non-template classes within the above. Other languages have generics too, but -femit-struct-debug-detailed does not yet implement them.
The third word says which source files those structs must come from for GCC to emit debug info. none and any mean what you'd expect. base means the base of the name of the file where the type declaration appears has to match the base of the name of the main compilation file โ in practice, compiling foo.c means debug info gets generated for types declared in that file and foo.h, but not other header files. 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. ๐
The default is -femit-struct-debug-detailed=all.
And yeah โ this only works with DWARF debug output.
-fno-dwarf2-cfi-asmโ emit DWARF unwind info as a compiler-generated.eh_framesection instead of using GAS.cfi_*directives. Simple as that. ๐-fno-eliminate-unused-debug-typesโ normally, when producing DWARF output, GCC skips debug symbol output for types that are nowhere used in the source file being compiled. Sometimes you want the opposite though: GCC emitting debug info for every type declared in a compilation unit, whether or not it's actually used there. Classic scenario โ you're in the debugger and you want to cast a value to a type that isn't used in your program but is declared. More often than not though? This just wastes a significant amount of space. ๐ญ
โจ Options That Control Optimization โจ
Okay so these options control the various sorts of optimizations. Buckle up. ๐
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. It's giving "predictable and chill." ๐ธ
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. Trade-offs, bestie. That's the whole vibe.
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 information gained from all of the files when compiling each of them. Teamwork makes the dream work, no cap. ๐
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 -O0 or if an -O level is not set on the command line, even if individual optimization flags are specified. Similarly, -Og suppresses 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. Iconic little trick, iykyk. ๐ฅ
-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
-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โ Optimize even more. GCC performs nearly all supported optimizations that do not involve a space-speed tradeoff. Compared to-O, this option increases both compilation time and the performance of the generated code. It's giving glow-up. โจ
-O2 turns on all optimization flags specified by -O. 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-pre
-ftree-switch-conversion -ftree-tail-merge -ftree-vrp
Please note the warning under -fgcse about invoking -O2 on programs that use computed gotos. Not me being dramatic โ it's literally in the docs, 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.
-O3โ Optimize yet more.-O3turns on all optimizations specified by-O2and 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-loop-vectorize -ftree-partial-pre -ftree-slp-vectorize
-funswitch-loops -fvect-cost-model -fvect-cost-model=dynamic
-fversion-loops-for-strides
-O0โ Reduce compilation time and make debugging produce the expected results. This is the default. The cozy baseline. ๐งธ-Osโ Optimize for size.-Osenables all-O2optimizations except those that often increase code size:
-falign-functions -falign-jumps -falign-labels -falign-loops
-fprefetch-loop-arrays -freorder-blocks-algorithm=stc
It also enables -finline-functions, causes the compiler to tune for code size rather than execution speed, and performs further optimizations designed to reduce code size. Tiny and cute. ๐
-Ofastโ Disregard strict standards compliance. ๐-Ofastenables all-O3optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on-ffast-math,-fallow-store-data-racesand the Fortran-specific-fstack-arrays, unless-fmax-stack-var-sizeis specified, and-fno-protect-parens.
Bestie, please read that again: not valid for all standard-compliant programs. She's fast, she's reckless, she does NOT care about your standards. โ ๏ธ
-Ogโ Optimize the debugging experience.-Ogshould be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience. It is a better choice than-O0for producing debuggable code because some compiler passes that collect debug information are disabled at-O0. It's giving โจthe best of both worldsโจ.
Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect. Otherwise -Og enables all -O1 optimization flags except for those that may interfere with debugging:
-fbranch-count-reg -fdelayed-branch -fdse -fif-conversion
-fif-conversion2 -finline-functions-called-once
-fmove-loop-invariants -fssa-phiopt -ftree-bit-ccp -ftree-dse
-ftree-pta -ftree-sra
If you use multiple -O options, with or without level numbers, the last such option is the one that is effective. Last one wins, periodt. ๐
Options of the form -fflag specify machine-independent flags. Most flags 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 you typically use. You can figure out the other form by either removing no- or adding it. Easy math, bestie. ๐งฎ
The following options control specific optimizations. They are either activated by -O options or are related to ones that are. You can use the following flags in the rare cases when "fine-tuning" of optimizations to be performed is desired. That's your cue to get very specific about what you want. ๐
-fno-defer-popโ okay so some machines have to pop the args after a function call, right? This makes them pop those args the literal second each function returns. But at-O1and up,-fdefer-popis the default, which lets args just chill and pile up on the stack across several calls and then get popped all at once. Efficiency slay. ๐-fforward-propagateโ runs a forward propagation pass on RTL. What it does is try to smoosh two instructions together and see if the result can be simplified. And if loop unrolling is active? Then you get two passes, bestie, and the second one is scheduled after loop unrolling. This one is on by default at-O,-O2,-O3,-Os. โจ-ffp-contract=styleโ floating-point contraction, let's talk about it:-ffp-contract=offdisables floating-point expression contraction. periodt.-ffp-contract=fastenables floating-point expression contraction, like forming fused multiply-add operations if the target natively supports them. iconic behavior.-ffp-contract=onenables floating-point expression contraction if the language standard allows it. Ngl though โ this is currently not implemented and gets treated exactly equal to-ffp-contract=off. ๐ญ
The default is -ffp-contract=fast.
-fomit-frame-pointerโ omits the frame pointer in functions that genuinely don't need one. This skips the instructions to save, set up and restore that frame pointer, and on lots of targets it frees up an extra register too. ๐
On some targets this flag does literally nothing, because the standard calling sequence always uses a frame pointer so it can't be omitted. Not me finding out the hard way. ๐
And heads up: -fno-omit-frame-pointer does not guarantee the frame pointer is used in all functions. Several targets always omit it in leaf functions regardless.
Enabled by default at -O 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 (likestrlen,strchrorstrcpy) and their_FORTIFY_SOURCEcounterparts into faster alternatives. Enabled at levels-O2,-O3. ๐ฅ-fno-inlineโ do not expand any functions inline apart from the ones marked with thealways_inlineattribute. This is the default when you're not optimizing. Single functions can be exempted from inlining by marking them with thenoinlineattribute. ๐-finline-small-functionsโ integrates functions into their callers when the body is smaller than the expected function call code (so the overall size of the program gets smaller, cute). The compiler heuristically decides which functions are simple enough to be worth integrating this way. And this inlining applies to all functions, even the ones not declared inline. Enabled at levels-O2,-O3,-Os. โจ-findirect-inliningโ inlines the indirect calls too, the ones that get discovered to be known at compile time thanks to previous inlining. Lowkey 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โ considers all functions for inlining, even if they're not declared inline. The compiler heuristically decides which functions are worth integrating this way. And if all calls to a given function get integrated, and that function is declaredstatic, then it's normally not output as assembler code in its own right. Enabled at levels-O2,-O3,-Os. Also enabled by-fprofile-useand-fauto-profile. ๐-finline-functions-called-onceโ considers allstaticfunctions called once for inlining into their caller, even if they're not markedinline. If a call to a given function gets integrated, then the function is not output as assembler code in its own right. Enabled at levels-O1,-O2,-O3and-Os, but not-Og. ๐-fearly-inliningโ inlines functions marked byalways_inlineand functions whose body seems smaller than the function call overhead, and it does it early, before doing-fprofile-generateinstrumentation and the real inlining pass. Doing it this way makes profiling significantly cheaper and usually makes inlining faster on programs with large chains of nested wrapper functions. Enabled by default. ๐ธ-fipa-sraโ performs 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,-O3and-Os. ๐ซถ-finline-limit=nโ by default GCC limits the size of functions that can be inlined, and this flag gives you coarse control over that limit.nis the size of functions that can be inlined in number of pseudo instructions. โจ
Real talk though: inlining is actually controlled by a number of parameters, which you can specify individually using --param name=value. The -finline-limit=n option sets some of these parameters like so:
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: pseudo instruction represents, in this particular context, an abstract measurement of 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 an another. So like, don't read into it too hard.
-fno-keep-inline-dllexportโ this is a more fine-grained version of-fkeep-inline-functions, which applies only to functions 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. Not me keeping things around just in case. ๐-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. And if you want to force the compiler to check whether a variable is referenced, regardless of whether optimization is on or not, use the-fno-keep-static-constsoption.-fmerge-constantsโ attempts 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-constantsto inhibit this behavior. Enabled at levels-O,-O2,-O3,-Os. โญ-fmerge-all-constantsโ attempts to merge identical constants and identical variables. This option implies-fmerge-constants. On top of that, it also considers e.g. even constant initialized arrays or initialized constant variables with integral or floating-point types.
Okay bestie this is the important bit: 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โ performs 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โ performs more aggressive SMS-based modulo scheduling with register moves allowed. By setting this flag, certain anti-dependences edges are deleted, which triggers the generation of reg-moves based on the life-range analysis. This option is effective only with-fmodulo-schedenabled. ๐ฆ-fno-branch-count-regโ disables the optimization pass that scans for opportunities to use "decrement and branch" instructions on a count register, instead of instruction sequences that decrement a register, compare it against zero, and then branch based upon the result. This option is only meaningful on architectures that support such instructions, which include x86, PowerPC, IA-64 and S/390. And note that-fno-branch-count-regdoesn't remove the decrement and branch instructions from the generated instruction stream introduced by other optimization passes. ๐
The default is -fbranch-count-reg at -O1 and higher, except for -Og.
-fno-function-cseโ do not put function addresses in registers; make each instruction that calls a constant function contain the function's address explicitly. This option results in less efficient code, but some strange hacks that alter the assembler output may be confused by the optimizations performed when this option is not used. The default is-ffunction-cse. ๐-fno-zero-initialized-in-bssโ if the target supports a BSS section, GCC by default puts variables that are initialized to zero into BSS. This can save space in the resulting code. ๐
This option turns off that behavior, because some programs explicitly rely on variables going to the data section โ e.g., so that the resulting executable can find the beginning of that section and/or make assumptions based on that.
The default is -fzero-initialized-in-bss.
-fthread-jumpsโ performs optimizations that check to see if a jump branches to a location where another comparison subsumed by the first is found. If so, the first branch is 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-O2,-O3,-Os. โจ-fsplit-wide-typesโ when using a type that occupies multiple registers, such aslong longon a 32-bit system, split the registers apart and allocate them independently. This normally generates better code for those types, but may make debugging more difficult. Trade-offs, bestie. ๐ญ Enabled at levels-O,-O2,-O3,-Os.-fsplit-wide-types-earlyโ fully split wide types early, instead of very late. This option has no effect unless-fsplit-wide-typesis turned on. This is the default on some targets. ๐ซถ-fcse-follow-jumpsโ bestie, this one's about common subexpression elimination (CSE for short ๐ ). With it on, CSE will scan straight through jump instructions whenever the jump's target isn't reached by any other path. Like, picture CSE hitting anifstatement that has anelseclause โ it follows that jump when the condition tested comes out false. Iconic.
Enabled at levels -O2, -O3, -Os.
-fcse-skip-blocksโ lowkey the sibling of-fcse-follow-jumps, except this one makes CSE follow jumps that conditionally skip over blocks. So when CSE runs into a simpleifstatement with no else clause,-fcse-skip-blocksmakes it follow the jump around the body of thatif. slay.
Enabled at levels -O2, -O3, -Os.
-frerun-cse-after-loopโ literally just re-runs common subexpression elimination after the loop optimizations have done their thing. second pass energy โจ.
Enabled at levels -O2, -O3, -Os.
-fgcseโ runs a global common subexpression elimination pass. And not just that โ this pass also does global constant and copy propagation. multi-tasking queen ๐.
Note: when you're compiling a program that uses computed gotos (a GCC extension, iykyk), 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 this one's enabled, global common subexpression elimination tries to move loads that are only killed by stores into themselves. The way that works out: a loop containing a load/store sequence can get changed into a load outside the loop, plus a copy/store within the loop. chef's kiss ๐.
Enabled by default when -fgcse is enabled.
-fgcse-smโ flip this on and a store motion pass runs after global common subexpression elimination. This pass attempts to move stores out of loops. Team it up with-fgcse-lmand loops containing a load/store sequence can be changed into a load before the loop and a store after the loop. obsessed fr.
Not enabled at any optimization level.
-fgcse-lasโ with-fgcse-lasenabled, the global common subexpression elimination pass eliminates redundant loads that come after stores to the same memory location (both partial and full redundancies, bestie, we're thorough ๐ ).
Not enabled at any optimization level.
-fgcse-after-reloadโ when this is enabled, a redundant load elimination pass is performed after reload. The whole point of this pass is to clean up redundant spilling. tidy vibes ๐ง.
Enabled by -fprofile-use and -fauto-profile.
-faggressive-loop-optimizationsโ this option tells the loop optimizer to use language constraints to derive bounds for the number of iterations of a loop. It assumes that loop code doesn't invoke undefined behavior โ like, no causing signed integer overflows or out-of-bound array accesses, okay?? ๐ญ The bounds for the number of iterations get used to guide loop unrolling, 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. That prevents certain optimizations which depend on knowing the array bounds. nosy optimizations, blocked ๐.-fcrossjumpingโ performs the 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, so, no promises, bestie ๐.
Enabled at levels -O2, -O3, -Os.
-fauto-inc-decโ combines 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-Oand higher on architectures that support this.-fdceโ performs dead code elimination (DCE) on RTL. Enabled by default at-Oand higher. bye bye dead code ๐ฆ.-fdseโ performs dead store elimination (DSE) on RTL. Enabled by default at-Oand higher.-fif-conversionโ attempts to transform conditional jumps into branch-less equivalents. That includes conditional moves,min,max, set flags,absinstructions, and some tricks doable by standard arithmetics. The use of conditional execution on chips where it's available is controlled by-fif-conversion2. So cute, so efficient ๐.
Enabled at levels -O, -O2, -O3, -Os, but not with -Og.
-fif-conversion2โ uses conditional execution (where available) to transform conditional jumps into branch-less equivalents.
Enabled at levels -O, -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, which means two copies of the function. With this option, the base and complete variants get changed into thunks that call a common implementation. deduplication but make it C++ โจ.
Enabled by -Os.
-fdelete-null-pointer-checksโ assumes that programs can't safely dereference null pointers, and that no code or data element lives 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 can't be null.
Note though: 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.
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โ attempts to convert calls to virtual functions into 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โ attempts to convert calls to virtual functions into speculative direct calls. Based on analysis of the type inheritance graph, it figures out for a given call the set of likely targets. If that set is small โ preferably of size 1 โ it changes the call into a conditional deciding between direct and indirect calls. These speculative calls enable more optimizations, like inlining. And when they seem useless after further optimization, they get converted back into their original form. it's giving glow-up-then-glow-down ๐ฆ.-fdevirtualize-at-ltransโ streams 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. (trade-offs, bestie, we all have them ๐ )-fexpensive-optimizationsโ performs a number of minor optimizations that are relatively expensive. small but bougie ๐.
Enabled at levels -O2, -O3, -Os.
-freeโ attempts 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. ngl, very satisfying.
Enabled for Alpha, AArch64 and x86 at levels -O2, -O3, -Os.
-fno-lifetime-dseโ in C++, the value of an object is only affected by changes within its lifetime: when the constructor begins, the object has an indeterminate value, and any changes during the lifetime of the object are dead when the object is destroyed. Normally dead store elimination takes advantage of this. But if your code relies on the value of the object storage persisting beyond the lifetime of the object, you can use this flag to disable this optimization. To preserve stores before the constructor starts (e.g. because youroperator newclears the object storage) but still treat the object as dead after the destructor, you can use-flifetime-dse=1. The default behavior can be explicitly selected with-flifetime-dse=2. And-flifetime-dse=0is equivalent to-fno-lifetime-dse. options for daysss ๐-flive-range-shrinkageโ attempts to decrease register pressure through register live range shrinkage. This is helpful for fast processors with small or moderate size register sets. squeeze that register pressure out ๐.-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. main character algorithm fr ๐.-fira-region=regionโ use the 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. (worth it though, probably โจ)
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.
This option is enabled at level -O3 for some targets.
-fno-ira-share-save-slotsโ bestie this turns OFF sharing of the stack slots that hold call-used hard registers that gotta survive a call. So every hard register gets its own lil stack slot ๐ which meansโฆ yeah, function stack frames get bigger. it's giving "more room, more problems" fr fr.-fno-ira-share-spill-slotsโ same energy, different victim: this disables sharing of stack slots allocated for pseudo-registers ๐. Every pseudo-register that didn't snag a hard register gets its own separate stack slot, and guess what โ function stack frames are larger. periodt.-flra-rematโ turns on CFG-sensitive rematerialization in LRA โจ. Instead of loading values of spilled pseudos, LRA tries to rematerialize (aka recalculate) values whenever it's profitable. main character behavior ngl.
Enabled at levels -O2, -O3, -Os.
-fdelayed-branchโ if the target machine supports it, this attempts to reorder instructions so we can actually use those instruction slots chilling after delayed branch instructions ๐ฆ.
Enabled at levels -O, -O2, -O3, -Os, but not at -Og.
-fschedule-insnsโ if the target machine supports it, this tries to reorder instructions to kill execution stalls caused by required data not being ready yet ๐ญ. It's a lifesaver on machines with slow floating point or memory load instructions, because it lets other instructions get issued while we wait for the load or floating-point result to be needed. iconic.
Enabled at levels -O2, -O3.
-fschedule-insns2โ basically-fschedule-insnsbut it requests an additional pass of instruction scheduling after register allocation is done ๐ . Super 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โ disables instruction scheduling across basic blocks. That scheduling is normally enabled when we schedule before register allocation, i.e. with-fschedule-insnsor at-O2or higher ๐ธ.-fno-sched-specโ disables speculative motion of non-load instructions. Again, normally enabled when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher ๐.-fsched-pressureโ enables 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 it can improve the generated code and shrink its size by stopping register pressure from climbing above the number of available hard registers โ and thus preventing the spills that follow in register allocation. no cap, that's a glow-up.-fsched-spec-loadโ allows speculative motion of some load instructions โจ. Only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-spec-load-dangerousโ allows speculative motion of more load instructions ๐ณ. Note the name, bestie โ dangerous. Only makes sense when scheduling before register allocation, i.e. with-fschedule-insnsor at-O2or higher.-fsched-stalled-insns,-fsched-stalled-insns=nโ defines 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 no insns get moved prematurely.-fsched-stalled-insns=0means there's no limit on how many queued insns can be moved prematurely. And-fsched-stalled-insnswith no value is equivalent to-fsched-stalled-insns=1๐.-fsched-stalled-insns-dep,-fsched-stalled-insns-dep=nโ defines how many insn groups (cycles) get examined for a dependency on a stalled insn that's a candidate for premature removal from the queue of stalled insns ๐. This only does anything during the second scheduling pass, and only if-fsched-stalled-insnsis used.-fno-sched-stalled-insns-depis equivalent to-fsched-stalled-insns-dep=0. And-fsched-stalled-insns-depwith no 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, which results in faster schedules.
โ ๏ธ Heads up bestie: this option is experimental, because not all machine descriptions used by GCC model the CPU closely enough to avoid unreliable results from the algorithm.
This only makes sense when scheduling after register allocation, i.e. with -fschedule-insns2 or at -O2 or higher.
-fsched-group-heuristicโ enables the group heuristic in the scheduler ๐ . It favors the instruction that belongs to a schedule group. Enabled by default when scheduling is enabled, i.e. with-fschedule-insnsor-fschedule-insns2or at-O2or higher.-fsched-critical-path-heuristicโ enables the critical-path heuristic in the scheduler ๐. It 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โ enables the speculative instruction heuristic in the scheduler ๐ฆ. It 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โ enables the rank heuristic in the scheduler โญ. It 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โ enables the last-instruction heuristic in the scheduler ๐ธ. It favors the instruction that's 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โ enables the dependent-count heuristic in the scheduler ๐. It 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โ okay so modulo scheduling happens before traditional scheduling. If a loop is modulo scheduled, later scheduling passes might 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, round two ๐ . Selective scheduling runs instead of the second scheduler pass.-fsel-sched-pipeliningโ enables software pipelining of innermost loops during selective scheduling ๐. This option has no effect unless one of-fselective-schedulingor-fselective-scheduling2is turned on. iykyk.-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โ so some object formats, like ELF, allow interposing of symbols by the dynamic linker ๐. That means for symbols exported from the DSO, the compiler can't do interprocedural propagation, inlining and other optimizations, because it has to assume the function or variable in question might change. This feature is useful โ for example, to rewrite memory allocation functions by a debugging implementation โ but it's 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). Similarly, if interposition happens for variables, the constructor of the variable will be the same. The flag has no effect for functions explicitly declaredinline(where it's never allowed for interposition to change semantics) and for symbols explicitly declaredweak.-fshrink-wrapโ emit function prologues only before the parts of the function that actually need it, rather than at the top of the function ๐ซถ. This flag is enabled by default at-Oand higher.-fshrink-wrap-separateโ shrink-wrap separate parts of the prologue and epilogue separately, so those parts are only executed when needed ๐. This option is on by default, but has no effect unless-fshrink-wrapis also turned on and the target supports this.-fcaller-savesโ enables allocation of values to registers that get clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls โจ. That allocation only happens 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, then tries to find ways to combine them ๐ .
Enabled by default at -O1 and higher.
-fipa-raโ use caller save registers for allocation if those registers aren't used by any called function ๐. In that case you don't need to save and restore them around calls. This is only possible if the called functions are part of the same compilation unit as the current function and they're 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 the callee's register usage can't be known exactly (this happens on targets that don't expose prologues and epilogues in RTL).
-fconserve-stackโ attempts to minimize stack usage ๐ธ. The compiler tries 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โ performs reassociation on trees โจ. This flag is enabled by default at-Oand higher.-fcode-hoistingโ performs 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โ bestie, this one does partial redundancy elimination (PRE) on trees. it's on by default at-O2and-O3, slay โจ-ftree-partial-preโ makes PRE more aggressive ๐ on by default at-O3, she's a little extra and we love that for her-ftree-forwpropโ performs forward propagation on trees ๐ on by default at-Oand higher-ftree-freโ full redundancy elimination (FRE) on trees ๐ฅ the tea is that FRE and PRE are not the same: FRE only looks at expressions computed on all paths leading to the redundant computation. this analysis is faster than PRE, tho it exposes fewer redundancies (tragic but ok). on by default at-Oand higher-ftree-phipropโ hoisting of loads from conditional pointers, on trees ๐ฆ on by default at-Oand higher-fhoist-adjacent-loadsโ speculatively hoists loads from both branches of an if-then-else if the loads are from adjacent locations in the same structure AND the target architecture has a conditional move instruction ๐ on by default at-O2and higher-ftree-copy-propโ copy propagation on trees, which eliminates unnecessary copy operations ๐ on by default at-Oand higher-fipa-pure-constโ discovers which functions are pure or constant ๐ on by default at-Oand higher-fipa-referenceโ discovers which static variables do not escape the compilation unit ๐ช on by default at-Oand higher-fipa-reference-addressableโ discovers read-only, write-only and non-addressable static variables โจ on by default at-Oand higher-fipa-stack-alignmentโ reduces stack alignment on call sites if possible ๐ซถ on by default, no cap-fipa-ptaโ performs interprocedural pointer analysis and interprocedural modification and reference analysis. > heads up bestie, this option can cause excessive memory and compile-time usage on large compilation units ๐ it is not enabled by default at any optimization level, periodt.-fipa-profileโ interprocedural profile propagation. functions called only from cold functions get marked as cold ๐ฅถ also, functions executed once (like"cold","noreturn", static constructors or destructors) get identified. cold functions and loop less parts of functions executed once are then optimized for size. on by default at-Oand higher-fipa-modrefโ interprocedural mod/ref analysis ๐ง this one analyzes the side effects of functions (like which memory locations are modified or referenced) and enables better optimization across the function call boundary. on by default at-Oand higher-fipa-cpโ interprocedural constant propagation ๐ธ this optimization analyzes the program to figure out when values passed to functions are constants, then optimizes accordingly. it can substantially increase performance if the application has constants passed to functions ๐ฅ on by default at-O2,-Osand-O3. also enabled by-fprofile-useand-fauto-profile-fipa-cp-cloneโ performs function cloning to make interprocedural constant propagation stronger ๐ช when enabled, interprocedural constant propagation performs function cloning when an 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). on by default at-O3. also enabled by-fprofile-useand-fauto-profile-fipa-bit-cpโ when enabled, performs interprocedural bitwise constant propagation ๐ on by default at-O2and by-fprofile-useand-fauto-profile. it requires that-fipa-cpis enabled-fipa-vrpโ when enabled, performs interprocedural propagation of value ranges ๐ on by default at-O2. it requires that-fipa-cpis enabled-fipa-icfโ performs Identical Code Folding for functions and read-only variables ๐ช this optimization reduces code size and may disturb unwind stacks by replacing a function by an equivalent one with a different name. it works more effectively with link-time optimization enabled.
ngl, even though the behavior is similar to the Gold Linker's ICF optimization, GCC ICF works on different levels, so the optimizations are not the same โ there are equivalences that are found only by GCC and equivalences found only by Gold ๐ฏ
on by default at -O2 and -Os
-flive-patching=levelโ controls GCC's optimizations to produce output suitable for live-patching ๐ง
okay so here's the lore: if the compiler's optimization uses a function's body or information extracted from its body to optimize/change another function, that latter one 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 functions, 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โ detects paths that trigger erroneous or undefined behavior due to dereferencing a null pointer ๐ isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. on by default at-O2and higher, and it depends on-fdelete-null-pointer-checksalso being enabled-fisolate-erroneous-paths-attributeโ detects paths that trigger erroneous or undefined behavior due to a null value being used in a way forbidden by areturns_nonnullornonnullattribute ๐ซ isolates those paths from the main control flow and turns the statement with erroneous or undefined behavior into a trap. this is not currently enabled, but may be enabled by-O2in the future (mysterious of her, honestly)-ftree-sinkโ performs forward store motion on trees ๐ on by default at-Oand higher-ftree-bit-ccpโ performs sparse conditional bit constant propagation on trees and propagates pointer alignment information ๐ง this pass only operates on local scalar variables and is on by default at-O1and higher, except for-Og. it requires that-ftree-ccpis enabled-ftree-ccpโ performs sparse conditional constant propagation (CCP) on trees โญ this pass only operates on local scalar variables and is on by default at-Oand higher-fssa-backpropโ propagates information about uses of a value up the definition chain in order to simplify the definitions ๐ for example, this pass strips sign operations if the sign of a value never matters. on by default at-Oand higher-fssa-phioptโ performs pattern matching on SSA PHI nodes to optimize conditional code ๐ฏ this pass is on by default at-O1and higher, except for-Og-ftree-switch-conversionโ performs conversion of simple initializations in a switch to initializations from a scalar array ๐ธ on by default at-O2and higher-ftree-tail-mergeโ looks for identical code sequences ๐ฏ when found, it replaces one with a jump to the other. this optimization is known as tail merging or cross jumping. on by default at-O2and higher. the compilation time in this pass can be limited usingmax-tail-merge-comparisonsparameter andmax-tail-merge-iterationsparameter โฑ๏ธ-ftree-dceโ performs dead code elimination (DCE) on trees ๐ on by default at-Oand 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 ๐ on by default at-O2and higher if-Osis not also specified-ffinite-loopsโ assumes that a loop with an exit will eventually take the exit and not loop indefinitely ๐ this allows the compiler to remove loops that otherwise have no side-effects, not considering eventual endless looping as such. on by default at-O2for C++ with-std=c++11or higher-ftree-dominator-optsโ performs a variety of simple scalar cleanups (constant/copy propagation, redundancy elimination, range propagation and expression simplification) based on a dominator tree traversal โจ this also performs jump threading (to reduce jumps to jumps). on by default at-Oand higher ๐-ftree-dseโ bestie, this one does dead store elimination (DSE) on trees. And what even is a dead store, you ask? It's when you write to some memory location and then, like, immediately overwrite it with another store before anything ever reads it. The first store was giving absolutely nothing. So it gets yeeted. ๐ Enabled by default at-Oand higher, no cap.-ftree-chโ this performs loop header copying on trees. It's lowkey iconic because it makes code motion optimizations way more effective, and it also saves you one whole jump. Enabled by default at-Oand higher. But it is not enabled for-Os, because it usually makes your code bigger and-Ossaid "we're not doing that here." ๐-ftree-loop-optimizeโ does loop optimizations on trees. Enabled by default at-Oand higher. Simple. Slay. โจ-ftree-loop-linear-floop-strip-mine-floop-blockโ these three do loop nest optimizations. Same thing as-floop-nest-optimize, fr fr. But heads up: to actually use this code transformation, GCC has to be configured with--with-islto enable the Graphite loop transformation infrastructure. No--with-isl, no vibe. ๐ซถ-fgraphite-identityโ enables the identity transformation for graphite. For every SCoP we generate the polyhedral representation and then transform it right back to gimple. Using-fgraphite-identityyou can check out the costs or the benefits of the wholeGIMPLE -> GRAPHITE -> GIMPLEglow-up journey. Some minimal optimizations also get performed by the code generator isl, like index splitting and dead code elimination in loops. It's giving "look how far we came just to end up here" ๐-floop-nest-optimizeโ enables the isl based loop nest optimizer. It's a generic loop nest optimizer built on the Pluto optimization algorithms, and it calculates a loop structure optimized for data-locality and parallelism. This option is experimental. You've been warned, bestie. ๐-floop-parallelize-allโ uses the Graphite data dependence analysis to sniff out 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 parallelizing them is actually profitable. It's just out here parallelizing with reckless abandon. Main character energy, honestly. ๐ฅ-ftree-coalesce-varsโ while transforming your program out of the SSA representation, this attempts to reduce copying by coalescing versions of different user-defined variables, instead of just the compiler's little temporaries. โ ๏ธ Heads up though: this may severely limit your ability to debug an optimized program compiled with-fno-var-tracking-assignments. In its negated form, this flag prevents SSA coalescing of user variables. Enabled by default if optimization is enabled, and it does very little otherwise. Like, barely any vibes when optimization's off.-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 them better. Enabled by default if vectorization is enabled. ๐ฆ-ftree-loop-distributionโ performs loop distribution. This can improve cache performance on big loop bodies and allow further loop optimizations like parallelization or vectorization to take place. For example, the loop:
DO I = 1, N
A(I) = B(I) + C
D(I) = E(I) * F
ENDDO
is transformed to:
DO I = 1, N
A(I) = B(I) + C
ENDDO
DO I = 1, N
D(I) = E(I) * F
ENDDO
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. 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
is transformed to:
DO I = 1, N
A(I) = 0
ENDDO
DO I = 1, N
B(I) = A(I) + I
ENDDO
and the initialization loop is transformed into a call to memset zero. Enabled by default at -O3. It's also enabled by -fprofile-use and -fauto-profile. ๐
-floop-interchangeโ performs loop interchange outside of graphite. This can improve cache performance on loop nests and allow further loop optimizations, like vectorization, to take place. For example, this 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];
is 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];
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 the RTL level โ think function calls, operations that expand into nontrivial sequences of insns. With-funswitch-loopsit also moves operands of conditions that are invariant out of the loop, so we can get away with just trivial invariantness analysis in loop unswitching. The pass also includes store motion. Moving things around, as one does. ๐ง-ftree-loop-ivcanonโ creates a canonical counter for the number of iterations in loops where figuring out that number 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 uses of the final value get replaced by that computation โ provided it's sufficiently cheap. This reduces data dependencies and may allow further simplifications. Enabled by default at-Oand higher. ๐ธ-fivoptsโ performs induction variable optimizations (strength reduction, induction variable merging and induction variable elimination) on trees. Say that five times fast, bestie. ๐ญ- *
-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, and only for loops that are CPU-intensive rather than constrained by, like, memory bandwidth. This option implies-pthread, so it's only supported on targets that have support for-pthread. ๐ซถ -ftree-ptaโ performs function-local points-to analysis on trees. Enabled by default at-O1and higher, except for-Og. ๐-ftree-sraโ performs scalar replacement of aggregates. This pass replaces structure references with scalars to prevent committing structures to memory too early. Enabled by default at-O1and higher, except for-Og. ๐-fstore-mergingโ performs merging of narrow stores to consecutive memory addresses. This pass merges contiguous stores of immediate values narrower than a word into fewer wider stores to reduce the number of instructions. Enabled by default at-O2and higher as well as-Os. Fewer instructions, same energy. ๐-ftree-terโ performs temporary expression replacement during the SSA->normal phase. Single use/single def temporaries are replaced at their use location with their defining expression. This results in non-GIMPLE code, but it gives the expanders much more complex trees to work on, which results in better RTL generation. Enabled by default at-Oand higher. It's giving "messy on purpose, gorgeous in practice." ๐-ftree-slsrโ performs straight-line strength reduction on trees. It recognizes related expressions involving multiplications and replaces them with less expensive calculations when possible. Enabled by default at-Oand higher. ๐-ftree-vectorizeโ performs vectorization on trees. This flag enables-ftree-loop-vectorizeand-ftree-slp-vectorizeif they're not explicitly specified. โจ-ftree-loop-vectorizeโ performs loop vectorization on trees. Enabled by default at-O3and by-ftree-vectorize,-fprofile-use, and-fauto-profile. ๐ฅ-ftree-slp-vectorizeโ performs basic block vectorization on trees. Enabled by default at-O3and by-ftree-vectorize,-fprofile-use, and-fauto-profile. ๐ฆ- *
-fvect-cost-model=model* โ alters the cost model used for vectorization. The model argument should be one ofunlimited,dynamic,cheaporvery-cheap.- With the
unlimitedmodel, the vectorized code-path is assumed to be profitable. ๐ธ - With the
dynamicmodel, a runtime check guards the vectorized code-path so it only gets enabled for iteration counts that will likely execute faster than running the original scalar loop. - The
cheapmodel disables vectorization of loops where doing so would be cost prohibitive โ for example due to required runtime checks for data dependence or alignment โ but otherwise it's equal to thedynamicmodel. - The
very-cheapmodel only allows vectorization if the vector code would entirely replace the scalar code that is being vectorized. For example, if each iteration of a vectorized loop would only be able to handle exactly four iterations of the scalar loop, thevery-cheapmodel would only allow vectorization if the scalar iteration count is known to be a multiple of four.
- With the
The default cost model depends on other optimization flags and is either dynamic or cheap. No cap. ๐
- *
-fsimd-cost-model=model* โ alters the cost model used for vectorization of loops marked with the OpenMPsimddirective. The model argument should be one ofunlimited,dynamic,cheap. All values of model have the same meaning as described in-fvect-cost-model, and by default a cost model defined with-fvect-cost-modelis used. ๐ -ftree-vrpโ this one runs Value Range Propagation on trees, bestie ๐. It's lowkey cousins with the constant propagation pass, except instead of propagating values it propagates ranges of values, which is honestly so much more slay. The payoff? The optimizers get to yeet unnecessary range checks like array bound checks and null pointer checks ๐๏ธโจ. It's on by default at-O2and higher. One tiny caveat: null pointer check elimination only happens if-fdelete-null-pointer-checksis enabled, iykyk.-fsplit-pathsโ splits paths that lead to loop backedges ๐ฆ. This can level up dead code elimination and common subexpression elimination. Enabled by default at-O3and above, no cap.-fsplit-ivs-in-unrollerโ ok so this lets values of induction variables in later iterations of the unrolled loop be expressed using the value in the first iteration ๐ธ. The whole point is it breaks long dependency chains, which makes the scheduling passes way more efficient. Chef's kiss.
A combo of -fweb and CSE is often enough to get the same effect, but ngl 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. Tragic.
This optimization is enabled by default.
-fvariable-expansion-in-unrollerโ with this on, the compiler makes multiple copies of some local variables while unrolling a loop, which can give you superior code ๐. This optimization is enabled by default for PowerPC targets, but disabled by default everywhere else.-fpartial-inliningโ inlines parts of functions, not the whole thing โจ. Heads up though: this option only does anything when inlining itself is turned on by the-finline-functionsor-finline-small-functionsoptions. Enabled at levels-O2,-O3,-Os.-fpredictive-commoningโ performs the predictive commoning optimization, which is just a fancy way of saying it reuses computations (especially memory loads and stores) that were performed in previous iterations of loops ๐๐ . This option is 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 so loops that access large arrays go faster ๐. Real talk though: this option may generate better or worse code โ results are highly dependent on the structure of the loops in your source. 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 notprintfoffprintf) ๐. This transformation lets GCC optimize or even fully eliminate branches based on the known return value of those functions when they're 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. And yes, -fprintf-return-value is enabled by default ๐.
-fno-peephole-fno-peephole2โ disable any machine-specific peephole optimizations ๐ซถ. The difference between-fno-peepholeand-fno-peephole2is all in how they're implemented inside the compiler; some targets use one, some use the other, and a few chaotic ones use both ๐.
-fpeephole is enabled by default. -fpeephole2 is enabled at levels -O2, -O3, -Os.
-fno-guess-branch-probabilityโ do not guess branch probabilities using heuristics, periodt โ.
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 that __builtin_expect info into account. The interactions between the heuristics and __builtin_expect can get genuinely complex, and in some cases it's actually useful to disable the heuristics so the effects of __builtin_expect are easier to understand ๐.
It's also possible to specify the 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 so there are fewer taken branches and better code locality ๐. Enabled at levels-O,-O2,-O3,-Os.-freorder-blocks-algorithm=algorithm โ pick which algorithm does the basic block reordering ๐ . The algorithm argument 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 issimpleat levels-O,-Os, andstcat levels-O2,-O3.-freorder-blocks-and-partitionโ on top of reordering basic blocks in the compiled function to reduce the number of taken branches, this one partitions hot and cold basic blocks into separate sections of the assembly and.ofiles, to improve paging and cache locality performance ๐ฅ.
This optimization is automatically turned off in the presence of exception handling or unwind tables (on targets using setjump/longjump or target specific scheme), for linkonce sections, for functions with a user-defined section attribute, and on any architecture that does not support named sections. When -fsplit-stack is used, this option is not enabled by default (to avoid linker errors), but it may be enabled explicitly (if using a working linker) ๐ง.
Enabled for x86 at levels -O2, -O3, -Os.
-freorder-functionsโ reorder functions in the object file to improve code locality โจ. It's implemented by using special subsections.text.hotfor the most frequently executed functions and.text.unlikelyfor unlikely executed functions. Reordering is done by the linker, so the object file format must support named sections and the linker must place them in a reasonable way.
Heads up bestie: this option isn't effective unless you either provide profile feedback (see -fprofile-arcs for details) or manually annotate functions with hot or cold attributes ๐.
Enabled at levels -O2, -O3, -Os.
-fstrict-aliasingโ allow the compiler to assume the strictest aliasing rules applicable to the language being compiled ๐. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside 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:
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 (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;
}
The -fstrict-aliasing option is enabled at levels -O2, -O3, -Os.
-falign-functions-falign-functions=n-falign-functions=n:m-falign-functions=n:m:n2-falign-functions=n:m:n2:m2 โ align 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, because vibes need numbers: -falign-functions=32 aligns functions to the next 32-byte boundary, -falign-functions=24 aligns to the next 32-byte boundary only if this can be done by skipping 23 bytes or less, and -falign-functions=32:7 aligns 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โ with this 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 โ align all branch targets to a power-of-two boundary.-falign-labels,-falign-labels=n,-falign-labels=n:m,-falign-labels=n:m:n2,-falign-labels=n:m:n2:m2โ Align all branch targets to a power-of-two boundary, bestie, and the parameters work exactly like the-falign-functionsones (go look up above, iykyk). Fun fact:-fno-align-labelsand-falign-labels=1are literally the same thing โ both mean labels get zero alignment, periodt.
But wait, there's a vibe check: if -falign-loops or -falign-jumps apply and their values are bigger than this one, then their values win. Theirs. Not yours. ๐
And if n isn't specified or is 0? Then we use a machine-dependent default which is very likely to be 1, aka no alignment at all. The biggest n you're allowed to pass is 65536.
Turned on at levels -O2, -O3. โจ
-falign-loops,-falign-loops=n,-falign-loops=n:m,-falign-loops=n:m:n2,-falign-loops=n:m:n2:m2โ Align loops to a power-of-two boundary. ๐ If those loops get executed a whole bunch of times, that pays you back for any execution of the dummy padding instructions, so it's giving investment.
If -falign-labels is greater than this value, then its value is used instead. (Yeah, labels can steal the spotlight here. ๐)
The parameters are analogous to the -falign-functions option. -fno-align-loops and -falign-loops=1 are equivalent, and they both mean 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โ Align branch targets to a power-of-two boundary โ specifically for branch targets where the only way to reach them is by jumping. ๐ฆ And the slay here is that in this case, no dummy operations need be executed at all. Zero waste, we love to see 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-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 during dead code elimination. That allocation stays. It lives there now. ๐-fallow-store-data-racesโ Okay so this one lets the compiler do optimizations that may introduce new data races on stores, without proving the variable can't be concurrently accessed by other threads. It does not affect optimization of local data. And it's safe to use if you know global data won't be accessed by multiple threads. ๐งต
Examples of optimizations this turns on 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. Heads up: 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. It's a legacy icon that just vibes in the corner. ๐
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 its own individual pseudo register. This lets the register allocation pass operate on pseudos directly, but it also strengthens several other optimization passes, like CSE, the loop optimizer, and the trivial dead code remover. ๐ช
But it can make debugging impossible, since variables no longer stay in a "home register". ๐ญ So like, pick your fighter.
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 โ exceptmainand those merged by attributeexternally_visibleโ become static functions, and in effect get optimized way 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. Bestie, please. ๐ซถ
-flto[=n]โ THE big one. 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. It's giving "we were always one file, actually". โจ
To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time. For example:
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 to GCC 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 a single internal image, and compiles the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the interprocedural analyses and optimizations in GCC to work across the two files as if they were a single one. Which means, for example, that the inliner is able to inline functions in bar.o into functions in foo.o and vice-versa. ๐ค
Another (simpler) way to enable link-time optimization is:
gcc -o myprog -flto -O2 foo.c bar.c
The above generates bytecode for foo.c and bar.c, merges them together into a single GIMPLE representation and optimizes them as usual to produce myprog.
The important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link step. GCC automatically performs link-time optimization if any of the objects involved were compiled with the -flto command-line option. You can always override the automatic decision to do link-time optimization by passing -fno-lto to the link command. ๐
To make whole program optimization effective, it is necessary to make certain whole program assumptions. The compiler needs to know what functions and variables can be accessed by libraries and runtime outside of 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 allow the compiler to 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 that 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. Therefore, 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. So flexible, we stan. ๐ฆ
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. So do both. Both is the move. ๐
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. No negotiating, bestie. ๐ซ
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. ๐
...and like, diagnostic options such as -Wstringop-overflow get passed through to the link stage too, and their setting matches whatever the compile-step was set to, at function granularity. ๐
Heads up though: this only matters for diagnostics that get emitted during optimization. And also, code transforms like inlining can literally lead to warnings being turned on or off for regions of code that aren't consistent with the setting at compile time. ๐ so wild.
When you need to pass options to the assembler via -Wa or -Xassembler, bestie, please make sure to either compile those 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, slay. โจ
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. ๐ซถ But 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 it.
If LTO encounters objects with C linkage declared with incompatible types in separate translation units to be linked together (which is undefined behavior according to ISO C99 6.2.7), a non-fatal diagnostic may be issued. The behavior is still undefined at run time though โ the diagnostic is just a heads up. Similar diagnostics may be raised for other languages.
Another feature of LTO is that it's 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's possible to extract and use them in an LTO link if you're 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's 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 the 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. ๐ fr fr, keep your versions matched.
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. ๐ธ
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. โญ
-flto-partition=algโ picks the partitioning algorithm the link-time optimizer uses. The value is either1to1to specify a partitioning mirroring the original source files, orbalancedto specify partitioning into equally sized chunks (whenever possible), ormaxto create a new partition for every symbol where possible. Specifyingnoneas an algorithm disables partitioning and streaming completely. The default value isbalanced. While1to1can be used as a workaround for various code ordering issues, themaxpartitioning is intended for internal testing only. 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 intermediate language written to LTO object files, and is only meaningful in conjunction with LTO mode (-flto). GCC currently supports two LTO compression algorithms. For zstd, valid values are0(no compression) to19(maximum compression), while zlib supports values from0to9. Values outside this range are clamped to either the minimum or maximum of the supported values. If the option is not given, a default balanced compression setting is used. โจ-fuse-linker-pluginโ enables the use of a linker plugin during link-time optimization. This option 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. This 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 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 -O, -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. ๐
Enabled at levels -O, -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โ with-fprofile-useall portions of programs not executed during train run are optimized agressively for size rather than speed. In some cases it is not practical to train all possible hot paths in the program. (For example, program may contain functions specific for a given hardware and trianing may not cover all hardware configurations program is run on.) With-fprofile-partial-trainingprofile 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 train run is not representative but also leads to significantly bigger code. ๐ฆ-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: ๐
and the option parade keeps going, bestie โ hold onto your iced coffee ๐ซถ
-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
Okay so before you can use this option, you have to generate profiling information first. Like, actually run your program and collect the receipts. No receipts, no vibes-based optimization, bestie ๐
By default, GCC throws an error message if the feedback profiles don't match the source code. Like, it notices and it says something. You can downgrade that whole situation into a warning by using -Wno-error=coverage-mismatch. โ ๏ธ But heads up: this may result in poorly optimized code. Also by default, GCC drops a warning message if the feedback profiles don't exist at all (peep -Wmissing-profile). So it's gonna tell you either way, fr fr.
If path is specified, GCC looks at the path to find the profile feedback data files. See -fprofile-dir. ๐๏ธ
-fauto-profile & -fauto-profile=path
Turn on sampling-based feedback-directed optimizations, plus this whole stack of optimizations below โ many of which are genuinely only worth it when you've got profile feedback to work with:
-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 you just... don't give it one, it defaults to fbdata.afdo in the current directory. Defaults really said "I got you" ๐ซถ
To actually produce an AutoFDO profile data file you have to run your program with the perf utility on a supported GNU/Linux target system. Want the tea? See <https://perf.wiki.kernel.org/>. โจ
For example:
perf record -e br_inst_retired:near_taken -b -o perf.data \
-- your_program
Then you use the create_gcov tool to convert that raw profile data into a format GCC can actually read. You also have to hand this tool the unstripped binary for your program โ yes, the one with all its debug info still attached, no skimping. See <https://github.com/google/autofdo>.
For example:
create_gcov --binary=your_program.unstripped --profile=perf.data \
--gcov=profile.afdo
floating-point era โจ (the speed vs. correctness trade-off)
The following options control compiler behavior regarding floating-point arithmetic. These options trade off between speed and correctness. All must be specifically enabled โ they do NOT just turn themselves on, okay? You have to ask. ๐
-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. Same deal 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. Like, do the homework first ๐
- *
-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=standard is not implemented for languages other than C. On the x86, it has no effect if -mfpmath=sse or -mfpmath=sse+387 is 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 -O option 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. So like... know what you're signing up for, bestie.
-fno-math-errnoโ Do not set"errno"after calling math functions that are executed with a single instruction, e.g.,"sqrt". A program that relies on IEEE exceptions for math error handling may want to use this flag for speed while maintaining IEEE arithmetic compatibility.
This option is 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 do not require the guarantees of these specifications.
The default is -fmath-errno.
On Darwin systems, the math library never sets "errno". There is therefore no reason for the compiler to consider the possibility that it might, and -fno-math-errno is the default. ๐
-funsafe-math-optimizationsโ Allow optimizations for floating-point arithmetic that (a) assume that 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.
This option is 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 do not require the guarantees of these specifications. 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 computation result. NOTE: re-ordering may change the sign of zero as well as ignore NaNs and inhibit or create underflow or overflow (and thus cannot be used on code that relies on rounding behavior like"(x + 2**52) - 2**52"). May also reorder floating-point comparisons and thus may not be used when ordered comparisons are required. This option requires that both-fno-signed-zerosand-fno-trapping-mathbe in effect. Moreover, 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 example"x / y"can be replaced with"x * (1/y)", which is useful if"(1/y)"is subject to common subexpression elimination. Note that 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 that arguments and results are not NaNs or +-Infs.
This option is 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 do not 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 one relies 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. Like, never never. ๐ค
The default is -ftrapping-math.
-frounding-mathโ Disable transformations and optimizations that assume default floating-point rounding behavior. This is round-to-zero for all floating point to integer conversions, and round-to-nearest for all other arithmetic truncations. This option should be specified 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". ๐ฎ
okay keep scrolling, there's SO much more and we are not even close to done ๐ฆ
-fsignaling-nansโ okay so this one tells the compiler to just assume that IEEE signaling NaNs might throw user-visible traps while floating-point ops are happening. Turning it on kills off any optimizations that could change how many exceptions you'd see with signaling NaNs. It also implies-ftrapping-math. โจ
It makes the preprocessor macro __SUPPORT_SNAN__ get defined.
Default is -fno-signaling-nans.
Bestie, this one is experimental โ right now it does not guarantee that it disables every single GCC optimization that messes with signaling NaN behavior. No cap. ๐
-fno-fp-int-builtin-inexactโ this says don't let the built-in functionsceil,floor,roundandtrunc(plus theirfloatandlong doublevariants) generate code that raises theinexactfloating-point exception for noninteger arguments. ISO C99 and C11 actually allow those functions to raiseinexact, but ISO/IEC TS 18661-1:2014 โ the C bindings to IEEE 754-2008, as integrated into ISO C2X โ does not allow it. ๐
Default is -ffp-int-builtin-inexact, which lets the exception be raised, unless C2X or a later C standard is selected. This option does nothing unless -ftrapping-math is in effect.
Even if you use -fno-fp-int-builtin-inexact, if those functions generate a call to a library function then the inexact exception may still be raised if the library implementation doesn't follow TS 18661.
-fsingle-precision-constantโ treats floating-point constants as single precision instead of quietly converting them into double-precision constants. ๐-fcx-limited-rangeโ when it's on, this option is basically declaring that you don't need a range reduction step when doing complex division. Also, no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. Default is-fno-cx-limited-range, but it gets 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's no checking whether the result of a complex multiplication or division isNaN + I*NaN, with an attempt to rescue the situation in that case. ๐ฆ
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. ๐
-fbranch-probabilitiesโ after running a program compiled with-fprofile-arcs, you can compile it a second time using-fbranch-probabilitiesto improve optimizations based on how many 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 info in that 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. ๐ฅ
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're only used in one place: in reorg.c, 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 gets 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 the 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 tells 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โ attempts 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, though, it can make debugging impossible, since variables no longer stay in a "home register". ๐ญ
Enabled by default with -funroll-loops.
-fschedule-fusionโ performs a target dependent pass over the instruction stream to schedule instructions of the same type together, because the target machine can execute them more efficiently if they're adjacent to each other in the instruction flow. โก
Enabled at levels -O2, -O3, -Os.
-ftracerโ performs tail duplication to enlarge superblock size. This transformation simplifies the control flow of the function, letting other optimizations do a better job.
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). Heads up: this option makes code larger, and it 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 information 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 a 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.-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 the 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, creates another version of the loop that assumes the stride is always one. Like, 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's 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 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 out the call-used registers when a function returns, and it's giving โจsecurity eraโจ. Two glow-ups in one: it either mitigates Return-Oriented Programming (ROP) attacks or stops info from leaking out through registers. The possible values of choice are exactly the same ones as for the"zero_call_used_regs"attribute. The default isskip. And bestie, if you wanna control this for just one specific function instead of the whole vibe, use the function attribute"zero_call_used_regs". ๐ซถ--param name=valueโ okay so here's the tea โ: in some places GCC uses a bunch of random constants to control how much optimization happens. Example: GCC won't inline functions that contain more than a certain number of instructions. And you can tweak some of those constants straight from the command line with this option. The names of the specific parameters and what their values even mean are tied to the compiler's internals, and they are subject to change without notice in future releases โ so lowkey don't build your whole personality on them. ๐ญ
Wanna know the minimal, maximal and default value of a parameter? Hit it with --help=param -Q. Iconic.
In each case the value is an integer, and the following choices of name are recognized for all targets:
predictable-branch-outcomeโ if a branch is predicted to be taken with a probability lower than this threshold (in percent), then it's considered well predictable. ๐ฏmax-rtl-if-conversion-insnsโ RTL if-conversion tries to yeet conditional branches around a block and replace them with conditionally executed instructions. This parameter is the max number of instructions in a block that even gets considered for if-conversion. The compiler also uses other heuristics to decide whether if-conversion is likely to be profitable, no cap.max-rtl-if-conversion-predictable-costโ RTL if-conversion will try to remove conditional branches around a block and swap in conditionally executed instructions. These parameters give the maximum permissible cost for the sequence that if-conversion would generate, depending on whether the branch is statically determined to be predictable or not. Units for this parameter are the same as for the GCC internalseq_costmetric. The compiler will try to provide a reasonable default 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. Bigger values = more aggressive optimization = compilation time goes up with probably only a tiny improvement in executable size. it's giving diminishing returns ๐min-crossjump-insnsโ the minimum number of instructions that have to match at the end of two blocks before cross-jumping them is even attempted. This value gets ignored when all the 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 into a block that jumps to a computed goto. To dodge O(N^2) behavior in a bunch 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 block with no more thanmax-goto-duplication-insnsget unfactored.max-delay-slot-insn-searchโ the maximum number of instructions to consider while hunting for an instruction to fill a delay slot. If more than this arbitrary number of instructions get searched, the time savings from filling the delay slot are minimal, so just stop searching. Bigger values = more aggressive optimization = compilation time up, probably tiny improvement in execution time. ๐max-delay-slot-live-searchโ when trying to fill delay slots, the max number of instructions to consider while searching for a block with valid live register info. Bumping this arbitrarily chosen value = more aggressive optimization = more compilation time. This parameter should be removed once the delay slot code gets rewritten to maintain the control-flow graph. (rip to it fr)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 specified, the optimization justโฆ doesn't happen. ๐max-gcse-insertion-ratioโ if the ratio of expression insertions to deletions is larger than this value for any expression, then RTL PRE inserts or removes the expression, and thus leaves partially redundant computations sitting in the instruction stream.max-pending-list-lengthโ the max number of pending dependencies scheduling allows before flushing the current state and starting over. Large functions with few branches or calls can create excessively large lists that needlessly eat memory and resources. ๐max-modulo-backtrack-attemptsโ the max number of backtrack attempts the scheduler should make when modulo scheduling a loop. Larger values can make compilation time go up exponentially. bestie that's not a vibe, that's a threat ๐จmax-inline-insns-singleโ several parameters control the tree inliner used in GCC. This number sets the max number of instructions (counted in GCC's internal representation) in a single function that the tree inliner considers for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++).max-inline-insns-autoโ when you use-finline-functions(which is included in-O3), a whole lot of functions that would otherwise never be considered for inlining by the compiler get investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied (--param max-inline-insns-auto).max-inline-insns-smallโ this is the bound applied to calls which are considered relevant with-finline-small-functions.max-inline-insns-sizeโ this is the bound applied to calls which are optimized for size. A little growth may be desirable to anticipate optimization oppurtunities exposed by inlining.uninlined-function-insnsโ number of instructions accounted by the inliner for function overhead, like the function prologue and epilogue.uninlined-function-timeโ extra time accounted by the inliner for function overhead, like the time needed to execute the function prologue and epilogue.inline-heuristics-hint-percentโ the scale (in percents) applied toinline-insns-single,inline-insns-single-O2,inline-insns-autowhen the inline heuristics hint that inlining is very profitable (i.e. it'll enable later optimizations). ๐uninlined-thunk-insns,uninlined-thunk-timeโ same as--param uninlined-function-insnsand--param uninlined-function-time, but applied to function thunks.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. slay ๐large-function-insnsโ the limit specifying 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 non-linear algorithms used by the back end. ๐ญlarge-function-growthโ specifies maximal growth of a large function caused by inlining, in percents. For example, parameter value100limits large function growth to 2.0 times the original size.large-unit-insnsโ the limit specifying 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 function A that is inline and B that just calls A three times. If B is small relative to A, the growth of the unit is 300% and yet such inlining is very sane. For very large units consisting of small inlineable functions, however, the overall unit growth limit is needed to avoid exponential explosion of code size. Thus for smaller units, the size is increased to--param large-unit-insnsbefore applying--param inline-unit-growth. ๐งlazy-modulesโ maximum number of concurrently open C++ module files when lazy loading.inline-unit-growthโ specifies maximal overall growth of the compilation unit caused by inlining. For example, parameter value20limits 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. ๐ฅถipa-cp-unit-growthโ specifies maximal overall growth of the compilation unit caused by interprocedural constant propagation. For example, parameter value10limits unit growth to 1.1 times the original size.ipa-cp-large-unit-insnsโ the size of translation unit that the IPA-CP pass considers large.large-stack-frameโ the limit specifying large stack frames. While inlining, the algorithm is trying not to grow past this limit too much.large-stack-frame-growthโ specifies maximal growth of large stack frames caused by inlining, in percents. For example, parameter value1000limits large stack frame growth to 11 times the original size. ๐ซmax-inline-insns-recursive,max-inline-insns-recursive-autoโ specifies the maximum number of instructions an out-of-line copy of a self-recursive inline function can grow into by performing recursive inlining.
okay bestie we're STILL in the --param zone and honestly? we live here now ๐
quick lil callback to the entry that started this whole thing:
--param max-inline-insns-recursive applies to functions declared inline. For functions that are not declared inline, recursive inlining happens only when -finline-functions (which is included in -O3) is enabled; --param max-inline-insns-recursive-auto applies instead. two params, two vibes, one recursion party ๐
--param max-inline-recursive-depth,--param max-inline-recursive-depth-autoโ sets the maximum recursion depth used for recursive inlining. Same split as above:--param max-inline-recursive-depthapplies to functions declaredinline, and for functions that are not declaredinline, recursive inlining only happens when-finline-functions(included in-O3) is enabled, in which case--param max-inline-recursive-depth-autoapplies instead. ๐--param min-inline-recursive-probabilityโ lowkey a whole philosophy moment: recursive inlining is only profitable for functions with deep recursion on average, and it can hurt functions with little recursion depth by increasing the prologue size or the complexity of the function body for other optimizers. ๐ญ When profile feedback is available (peep-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). math girlies rise ๐--param early-inlining-insnsโ specifies the growth the early inliner can make. In effect it increases the amount of inlining for code that has a large abstraction penalty. the early bird gets the inline โจ--param max-early-inliner-iterationsโ the iteration limit 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. early inliner says "not my problem, ask late inlining" ๐--param comdat-sharing-probabilityโ the probability (in percent) that a C++inlinefunction with comdat visibility gets shared across multiple compilation units. ๐ค--param modref-max-bases,--param modref-max-refs,--param modref-max-accessesโ the maximal number of base pointers, references and accesses stored for a single function by mod/ref analysis. three params, one storage closet ๐๏ธ--param modref-max-testsโ the maximum 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. it's giving "please be bigger than your friends" energy ๐--param modref-max-depthโ the maximum depth of the DFS walk used by modref escape analysis. Setting it to0disables the analysis completely. zero means GONE, no cap ๐--param modref-max-escape-pointsโ the maximum number of escape points tracked by modref per SSA-name. ๐โโ๏ธ๐จ--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 based on the function assembler name and filename, which makes old profile data more tolerant to source changes such as function reordering etc. grandma profile data stays valid, we love to see it ๐ซถ--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. gotta clear the bar to get the glow-up ๐--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. ๐ฅ--param gcse-unrestricted-costโ the cost, roughly measured as the cost of a single typical machine instruction, at which GCSE optimizations do not constrain the distance an expression can travel. This is currently supported only in the code hoisting pass. The lesser the cost, the more aggressive code hoisting is. Specifying0allows all expressions to travel unrestricted distances. free-range expressions, roaming the countryside ๐ฆ--param max-hoist-depthโ the depth of search in the dominator tree for expressions to hoist. This is used to avoid quadratic behavior in the hoisting algorithm. A value of0does not limit the search, but may slow down compilation of huge functions. no limit = no chill on your compile times bestie โณ--param max-tail-merge-comparisonsโ the maximum amount of similar bbs to compare a bb with. This is used to avoid quadratic behavior in tree tail merging. ๐งฌ--param max-tail-merge-iterationsโ the maximum amount of iterations of the pass over the function. This is used to limit compilation time in tree tail merging. โฑ๏ธ--param store-merging-allow-unalignedโ allow the store merging pass to introduce unaligned stores if it is legal to do so. chaotic but legal, we stan ๐--param max-stores-to-mergeโ the maximum number of stores to attempt to merge into wider stores in the store merging pass. ๐ฆ๐ฆโก๏ธ๐ฆ--param max-store-chains-to-trackโ the maximum number of store chains to track at the same time in the attempt to merge them into wider stores in the store merging pass. ๐--param max-stores-to-trackโ the maximum number of stores to track at the same time in the attempt to merge them into wider stores in the store merging pass. yes it's basically the sibling of the last one, no I will not be merging them, the manpage said what it said ๐ โโ๏ธ--param max-unrolled-insnsโ the maximum number of instructions a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled. ๐ข--param max-average-unrolled-insnsโ the maximum number of instructions biased by probabilities of their execution that a loop may have to be unrolled. If a loop is unrolled, this parameter also determines how many times the loop code is unrolled. probability-weighted, because of course it is โจ--param max-unroll-timesโ the maximum number of unrollings of a single loop. ๐--param max-peeled-insnsโ the maximum 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. ๐ get it? peeled? I'll see myself out--param max-peel-timesโ the maximum number of peelings of a single loop. ๐๐--param max-peel-branchesโ the maximum number of branches on the hot path through the peeled sequence. ๐ถ๏ธ--param max-completely-peeled-insnsโ the maximum number of insns of a completely peeled loop. ๐โจ--param max-completely-peel-timesโ the maximum number of iterations of a loop to be suitable for complete peeling. ๐--param max-completely-peel-loop-nest-depthโ the maximum depth of a loop nest suitable for complete peeling. ๐ช--param max-unswitch-insnsโ the maximum number of insns of an unswitched loop. ๐--param max-unswitch-levelโ the maximum number of branches unswitched in a single loop. ๐ฟ--param lim-expensiveโ the minimum cost of an expensive expression in the loop invariant motion. ๐ธ--param min-loop-cond-split-probโ when FDO profile information is available,min-loop-cond-split-probspecifies the minimum threshold for probability of a semi-invariant condition statement to trigger loop split. thresholds, but make it FDO ๐--param iv-consider-all-candidates-boundโ a bound on the number of candidates for induction variables, below which all candidates are considered for each use in induction variable optimizations. If there are more candidates than this, only the most relevant ones are considered, to avoid quadratic time complexity. ๐--param iv-max-considered-usesโ the induction variable optimizations give up on loops that contain more induction variable uses. it's giving "I'm tired, I'm going home" ๐ญ--param 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. โ๏ธ--param avg-loop-niterโ the average number of iterations of a loop. ๐--param dse-max-object-sizeโ the maximum size (in bytes) of objects tracked bytewise by dead store elimination. Larger values may result in larger compilation times. โณ--param dse-max-alias-queries-per-storeโ the maximum number of queries into the alias oracle per store. Larger values result in larger compilation times and may result in more removed dead stores. trade-off queen ๐--param scev-max-expr-sizeโ a bound on the size of expressions used in the scalar evolutions analyzer. Large expressions slow the analyzer. ๐--param scev-max-expr-complexityโ a bound on the complexity of the expressions in the scalar evolutions analyzer. Complex expressions slow the analyzer. ๐--param max-tree-if-conversion-phi-argsโ the maximum number of arguments in a PHI supported by TREE if conversion, unless the loop is marked with thesimdpragma. ๐ณ--param vect-max-version-for-alignment-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alignment in the vectorizer. ๐--param vect-max-version-for-alias-checksโ the maximum number of run-time checks that can be performed when doing loop versioning for alias in the vectorizer. ๐ต๏ธโโ๏ธ--param vect-max-peeling-for-alignmentโ the maximum number of loop peels to enhance access alignment for the vectorizer. A value of-1means no limit. minus one = infinite vibes ๐--param max-iterations-to-trackโ the maximum number of iterations of a loop the brute-force algorithm for analysis of the number of iterations of the loop tries to evaluate. ๐งฎ--param hot-bb-count-fractionโ the denominator n of the fraction 1/n of the maximal execution count of a basic block in the entire program that a basic block needs to at least have in order to be considered hot. The default is10000, which means a basic block is considered hot if its execution count is greater than 1/10000 of the maximal execution count.0means it is never considered hot. Used in non-LTO mode. the hotness threshold, literally ๐ฅ๐
and that's the tea for this chunk โ more --param chaos incoming, don't you dare leave ๐ซถ
okay so we're still deep in the --param zone, bestie, and this next stretch is so compiler-internals coded ๐ buckle up, the numbers are real and you need every single one of them.
hot-bb-count-ws-permilleโ the number of most-executed permilles (that's a range from0to1000, slay) of the profiled execution of the whole entire program that a basic block's execution count has to be part of for it to count as hot ๐ฅ. default is990, which literally means a basic block is hot if its count lands in the upper 990 permilles โ that's 99.0% โ of the profiled execution of the whole program.0means it's never considered hot, periodt. used in LTO mode.hot-bb-frequency-fractionโ the denominator n of the fraction1/nof the entry block's execution frequency that a basic block in that function needs to at least have to be considered hot ๐ . default is1000, so a block is hot if it runs more often than1/1000of the entry block's frequency.0means never hot, nope.unlikely-bb-count-fractionโ the denominator n of the fraction1/nof the total profiled runs of the program below which a basic block's execution count must fall for it to be flagged unlikely executed ๐. default is20, so a block is unlikely executed if it shows up in fewer than1/20โ that's 5% โ of the program's runs.0means it's always considered unlikely executed.max-predicted-iterationsโ the max number of loop iterations we predict statically โจ. this hits different when a function has one loop with a known bound and another with an unknown bound: the known count gets predicted correctly, while the unknown one averages out to roughly10. so that unbounded loop looks artificially cold next to the other one ๐ฅถ.builtin-expect-probabilityโ controls the probability of the expression having the specified value. it takes a percentage (like0 ... 100) as input ๐ฏ.builtin-string-cmp-inline-lengthโ the max length of a constant string for a builtin string cmp call that's eligible for inlining ๐ง.align-thresholdโ picks the fraction of the maximal execution frequency of a basic block in a function that gets used to align that basic block ๐.align-loop-iterationsโ a loop expected to iterate at least the selected number of iterations gets aligned, no cap ๐.tracer-dynamic-coverage,tracer-dynamic-coverage-feedbackโ this value limits superblock formation once the given percentage of executed instructions is covered, which caps unnecessary code size expansion ๐. thetracer-dynamic-coverage-feedbackone is used only when profile feedback is available โ and fr fr, the real profiles (as opposed to the statically estimated ones) are way less balanced, which lets the threshold go to a larger value.tracer-max-code-growthโ stop tail duplication once code growth hits the given percentage ๐. it's a pretty artificial limit, since most of those duplicates get eliminated later in cross jumping anyway, so you can set it way higher than the code growth you actually want.tracer-min-branch-ratioโ stop reverse growth when the reverse probability of the best edge drops below this threshold (in percent) ๐.tracer-min-branch-probability,tracer-min-branch-probability-feedbackโ stop forward growth if the best edge's probability is lower than this threshold. just like withtracer-dynamic-coverage, there are two of these:tracer-min-branch-probability-feedbackis for compiling with profile feedback andtracer-min-branch-probabilityis for compiling without it. the feedback one needs to be more conservative (higher) to actually make the tracer effective ๐.stack-clash-protection-guard-sizeโ specifies the size of the OS-provided stack guard as2raised to num bytes. higher values might cut down the number of explicit probes, but a value larger than the OS-provided guard leaves your code vulnerable to stack clash style attacks ๐.stack-clash-protection-probe-intervalโ stack clash protection means probing the stack space as it gets allocated. this param controls the max distance between probes into the stack, as2raised to num bytes. again: higher values may reduce explicit probes, but anything larger than the OS-provided guard leaves code vulnerable to stack clash style attacks ๐จ.max-cse-path-lengthโ the max number of basic blocks on a path that CSE considers ๐ค๏ธ.max-cse-insnsโ the max number of instructions CSE processes before it flushes ๐ฝ.ggc-min-expandโ GCC runs a garbage collector to manage its own memory allocation, and this param sets the minimum percentage by which the GC's heap is allowed to expand between collections ๐. tuning it might improve compilation speed; it has no effect on code generation.
the default is 30% + 70% * (RAM/1GB) with an upper bound of 100% when RAM >= 1GB. if "getrlimit" is available, the notion of "RAM" is the smallest of actual RAM and "RLIMIT_DATA" or "RLIMIT_AS". if GCC can't calculate RAM on a particular platform, the lower bound of 30% is used. setting this parameter and ggc-min-heapsize to zero makes a full collection happen at every opportunity โ it's extremely slow, but it can be useful for debugging ๐.
ggc-min-heapsizeโ the minimum size of the GC's heap before it even bothers collecting garbage ๐๏ธ. the first collection happens after the heap expands byggc-min-expand%beyondggc-min-heapsize. same deal: tuning it may improve compilation speed, and it has no effect on code generation.
the default is the smaller of RAM/8, RLIMIT_RSS, or a limit that tries to make sure RLIMIT_DATA or RLIMIT_AS aren't 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 particular platform, the lower bound is used. setting this parameter very large effectively disables garbage collection. setting this parameter and ggc-min-expand to zero makes a full collection occur at every opportunity.
max-reload-search-insnsโ the max number of instructions reload should look backward for an equivalent register ๐. increasing it means more aggressive optimization: compilation time goes up, with probably slightly better performance ๐ .max-cselib-memory-locationsโ the max number of memory locations cselib should take into account. increasing values mean more aggressive optimization, so compilation time increases with 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 โฑ๏ธ. increasing values mean more thorough searches, making compilation time go up with probably, like, 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 ๐ซ.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 must have for the scheduler to save its state across it ๐พ.sched-mem-true-dep-costโ the 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 ๐. 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 are considered for renaming in the selective scheduler ๐ท๏ธ.sms-min-scโ the minimum value of the stage count that the swing modulo scheduler generates ๐๏ธ.max-last-value-rtlโ the max size, measured as the number of RTLs, that can be recorded in an expression in the 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 down the compiler's memory usage and boosts its speed โก. this sets the max value of a shared integer constant.ssp-buffer-sizeโ the minimum size of buffers (like, arrays) that receive stack smashing protection when-fstack-protectionis used ๐ก๏ธ.
This default, before Ubuntu 10.10, was "8". Right now it's "4", which bumps up the number of functions protected by the stack protector. ๐
min-size-for-stack-sharingโ the minimum size of variables that get to take part in stack slot sharing when we're 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 struct that get treated in a field-sensitive way during pointer analysis.prefetch-latencyโ estimates, on average, how many instructions get executed before a prefetch finishes. The distance prefetched ahead is proportional to this constant. Heads up: raising this number may also mean less streams get prefetched (peepsimultaneous-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 drop software prefetch hints for strides that are non-constant. In some cases this can be a win, though the whole non-constant-stride thing makes it hard to predict when there's a clear benefit to issuing these hints.
Set it to 1 if prefetch hints should be issued for non-constant strides. Set it to 0 if prefetch hints should only go out for strides that are known to be constant and below prefetch-minimum-stride.
prefetch-minimum-strideโ the 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 in that case there may be conflicts between the hardware prefetchers and the software prefetchers. If the hardware prefetchers have a max stride they can handle, that should be used here to improve how the software prefetchers get used.
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.
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 for interchange to actually be profitable. ๐min-insn-to-prefetch-ratioโ the minimum ratio between the number of instructions and the number of prefetches to enable prefetching in a loop.prefetch-min-insn-to-mem-ratioโ the minimum ratio between the number of instructions and the number of memory references to enable prefetching in a loop.use-canonical-typesโ whether the compiler should use the "canonical" type system. This should always be1, which uses a more efficient internal mechanism for comparing types in C++ and Objective-C++. But if bugs in the canonical type system are causing compilation failures, set this value to0to disable canonical types. ๐ญswitch-conversion-max-branch-ratioโ switch initialization conversion refuses to create arrays that are bigger thanswitch-conversion-max-branch-ratiotimes the number of branches in the switch.max-partial-antic-lengthโ the max length of the partial antic set computed during the tree partial redundancy elimination optimization (-ftree-pre) when optimizing at-O3and above. For some sorts of source code, the enhanced partial redundancy elimination optimization can run away and eat all the memory available on the host machine. This parameter sets a limit on the length of the sets that get computed, which prevents that runaway behavior. Setting a value of0for this parameter allows an unlimited set length. ๐rpo-vn-max-loop-depthโ the max loop depth that is 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 do not.sccvn-max-alias-queries-per-accessโ the max number of alias-oracle queries we perform when looking for redundancies for loads and stores. If this limit gets hit, the search is aborted and the load or store is not considered redundant. The number of queries is algorithmically limited to the number of stores on all paths from the load to the function entry.ira-max-loops-numโ IRA uses regional register allocation by default. If a function contains more loops than the number given by this parameter, only at most the given number of the most frequently-executed loops form regions for regional register allocation.ira-max-conflict-table-sizeโ okay so even though IRA uses a sophisticated algorithm to compress the conflict table, the table can still need excessive amounts of memory for huge functions. If the conflict table for a function could be more than the size in MB given by this parameter, the register allocator instead uses a faster, simpler, and lower-quality algorithm that doesn't need to build a pseudo-register conflict table. ๐ซถira-loop-reserved-regsโ IRA can be used to evaluate more accurate register pressure in loops for decisions to move loop invariants (peep-O3). The number of available registers reserved for some other purposes is given by this parameter. The default of the parameter is the best found from numerous experiments. ๐ฅlra-inheritance-ebb-probability-cutoffโ LRA tries to reuse values reloaded in registers in subsequent insns. This optimization is called inheritance. EBB is used as a region to do this optimization. The parameter defines a minimal fall-through edge probability, in percentage, used to add BB to inheritance EBB in LRA. The default value was chosen from numerous runs of SPEC2000 on x86-64.loop-invariant-max-bbs-in-loopโ loop invariant motion can be very expensive, both in compilation time and in the amount of needed compile-time memory, with very large loops. Loops with more basic blocks than this parameter won't have loop invariant motion optimization performed on them.loop-max-datarefs-for-datadepsโ building data dependencies is expensive for very large loops. This parameter limits the number of data references in loops that are considered for data dependence analysis. These large loops are not handled by the optimizations using loop data dependencies.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 the function. Setting the parameter to zero makes it unlimited.max-vartrack-expr-depthโ sets a maximum number of recursion levels when attempting to map variable names or debug temporaries to value expressions. This trades compilation time for more complete debug information. If this is set too low, value expressions that are available and could be represented in debug information may end up not being used. Setting this higher may enable the compiler to find more complex debug expressions, but compile time and memory use may grow. ๐ธmax-debug-marker-countโ sets a threshold on the number of debug markers (like 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, such stmts get dropped from the inlined copy of a function, and from its RTL expansion.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. ๐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.ipa-sra-max-replacementsโ the max pieces of an aggregate that IPA-SRA tracks. As a consequence, it's also the max number of replacements of a formal parameter.sra-max-scalarization-size-Ospeed,sra-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 max size, in storage units, of aggregate which is considered for replacement when compiling for speed (sra-max-scalarization-size-Ospeed) or size (sra-max-scalarization-size-Osize) respectively. ๐sra-max-propagationsโ the max number of artificial accesses that Scalar Replacement of Aggregates (SRA) will track, per one local variable, in order to facilitate copy propagation.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 as opposed to save/restore code sequence pairs. This option only applies when using-fgnu-tm. ๐graphite-max-nb-scop-paramsโ okay so Graphite's loop transforms can go full exponential on you if you let them, so the number of parameters in a Static Control Part (SCoP) is bounded. Set it to zero and the bound justโฆ lifts. ๐ And what even is a parameter here? It's a variable whose value you don't know at compile time and that's defined outside a SCoP. That's it, that's the vibe.loop-block-tile-sizeโ loop blocking and strip mining (the transforms you turn on with-floop-blockor-floop-strip-mine) strip mine every loop in the loop nest by a given number of iterations. Wanna change the strip length? That's literally this parameter. ๐ipa-jump-function-lookupsโ says how many statements get visited during jump function offset discovery. ngl, it does exactly what it says on the tin.ipa-cp-value-list-sizeโ IPA-CP is out here trying to track all the possible values and types passed to a function's parameter so it can propagate them and do devirtualization. This parameter is the max number of values and types it'll store per one formal parameter of a function. Bestie's got a memory limit, respect it. โจipa-cp-eval-thresholdโ IPA-CP scores its own cloning profitability heuristics, and then only actually does the cloning opportunities whose scores beatipa-cp-eval-threshold. It's giving "you must be this profitable to ride". ๐ขipa-cp-max-recursive-depthโ maximum depth of recursive cloning for a self-recursive function. Yes, recursion, we love her. ๐ธipa-cp-min-recursive-probabilityโ recursive cloning happens only when the probability of the call actually being executed exceeds this parameter. Lowkey a bouncer at the club. ๐ซถipa-cp-recursion-penaltyโ the percentage penalty that recursive functions get hit with when they're evaluated for cloning.ipa-cp-single-call-penaltyโ the percentage penalty that functions containing a single call to another function get hit with when they're evaluated for cloning.ipa-max-agg-itemsโ IPA-CP can also propagate a number of scalar values passed in an aggregate, and this parameter controls the maximum number of such values per one parameter. ๐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 that candidate's profitability score. Extra credit, slay. โญipa-max-loop-predicatesโ the maximum number of different predicates IPA will use to describe when loops in a function have known properties.ipa-max-aa-stepsโ while analyzing function bodies, IPA-CP uses alias analysis to track values pointed to by function parameters. But it's not about to spend forever on giant functions, so after examiningipa-max-aa-stepsstatements that modify memory, it gives up and considers all memory clobbered. ๐ญ dramatic but fair.ipa-max-switch-predicate-boundsโ maximal number of boundary endpoints of case ranges of a switch statement. If a switch exceeds this limit, IPA-CP will not construct the cloning cost predicate (the thing used to estimate cloning benefit) for the default case of that 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, that expression gets treated as a complicated one and is not handled by IPA analysis. Too messy, no thank you. ๐lto-partitionsโ specify the desired number of partitions produced during WHOPR compilation. And fr fr, the number of partitions should exceed the number of CPUs used for compilation. ๐lto-min-partitionโ size of the minimal partition for WHOPR (in estimated instructions). This exists so you don't waste effort splitting very small programs into too many partitions. Iconic efficiency behavior.lto-max-partitionโ 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. ๐lto-max-streaming-parallelismโ maximal number of parallel processes used for LTO streaming. Go off, multicore. ๐ฅcxx-max-namespaces-for-diagnostic-helpโ the maximum number of namespaces to consult for suggestions when C++ name lookup fails for an identifier. Yes bestie, the compiler is trying to help you find your typo. ๐sink-frequency-thresholdโ the maximum relative execution frequency (in percents) of the target block relative to a statement's original block, which is what allows statement sinking of a statement. Bigger numbers = more aggressive statement sinking. And a small positive adjustment gets applied for statements with memory operands, because those are even more profitable to sink. โจ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.case-values-thresholdโ the smallest number of different values for which it's 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 one gets used when you're 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 one gets used when you're optimizing for speed. ๐๏ธtree-reassoc-widthโ set 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. ๐sched-pressure-algorithmโ pick between the two available implementations of-fsched-pressure. Algorithm1is the original implementation and is the more likely one to prevent instructions from being reordered. Algorithm2was designed as 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. Seehaifa-sched.cin the GCC sources for more details. ๐ง And the default choice? Depends on the target.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.asan-globalsโ enable buffer overflow detection for global objects. This kind of protection is enabled by default if you're 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 the--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 the--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. ๐จ
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โ turns on hwasan checks for memory writes โ๏ธ. Instrumenting writes is on by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. Wanna stop checking writes? Then--param hwasan-instrument-writes=0.hwasan-instrument-mem-intrinsicsโ turns on hwasan instrumentation of builtin functions ๐ง. Also enabled by default for both-fsanitize=hwaddressand-fsanitize=kernel-hwaddress. To turn the builtin instrumentation off, it's--param hwasan-instrument-mem-intrinsics=0.use-after-scope-direct-emission-thresholdโ if a local variable's size in bytes is smaller than or equal to this number, GCC just poisons (or unpoisons) the shadow memory directly instead of going through run-time callbacks. No middleman, no cap ๐ .tsan-distinguish-volatileโ emit special instrumentation for accesses to volatiles. Yes, volatiles get their own lil treatment โจ.tsan-instrument-func-entry-exitโ emit instrumentation calls to__tsan_func_entry()and__tsan_func_exit(). In and out, bestie ๐ช๐ซถ.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 allowed on a finite state automaton jump thread path.max-fsm-thread-pathsโ the maximum number of new jump thread paths to create for a finite state automaton.parloops-chunk-sizeโ the chunk size of theomp schedulefor loops parallelized by parloops ๐.parloops-scheduleโ the schedule type ofomp schedulefor loops parallelized by parloops:static,dynamic,guided,auto,runtime. Pick your fighter ๐ .parloops-min-per-threadโ the minimum number of iterations per thread of an innermost parallelized loop where the parallelized variant is preferred over the single-threaded one. Heads up though: for a parallelized loop nest, the minimum number of iterations of the outermost loop per thread is two.max-ssa-name-query-depthโ the maximum depth of recursion when 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 maximum number of may-defs analyzed 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 maximum number of assertions to add along the default edge of a switch statement during VRP.evrp-modeโ specifies the mode Early VRP should operate in.unroll-jam-min-percentโ the minimum percentage of memory references that have to be optimized away before the unroll-and-jam transformation is considered profitable ๐ธ.unroll-jam-max-unrollโ the maximum number of times the outer loop should be unrolled by the unroll-and-jam transformation.max-rtl-if-conversion-unpredictable-costโ the maximum permissible cost for the sequence that would be generated by the RTL if-conversion pass for a branch that's considered unpredictable ๐ฒ.max-variable-expansions-in-unrollerโ if-fvariable-expansion-in-unrolleris used, this is the maximum number of times that an individual variable will be expanded during loop unrolling.tracer-min-branch-probability-feedbackโ stop forward growth if the probability of the best edge drops below this threshold (in percent). Only used when profile feedback is available ๐.partial-inlining-entry-probabilityโ the maximum probability of the entry BB of a split region (in percent, relative to the entry BB of the function) for partial inlining to actually happen.max-tracked-strlensโ the maximum number of strings for which thestrlenoptimization pass will track string lengths ๐งต.gcse-after-reload-partial-fractionโ the threshold ratio for performing partial redundancy elimination after reload.gcse-after-reload-critical-fractionโ the threshold ratio of critical-edge execution count that permits performing redundancy elimination after reload.max-loop-header-insnsโ the maximum number of insns in a loop header duplicated by the copy loop headers pass.vect-epilogues-nomaskโ enable loop epilogue vectorization using a smaller vector size โจ.vect-partial-vector-usageโ controls when the loop vectorizer considers using partial vector loads and stores instead of 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 has an effect on targets that support partial vector loads and stores โ so if your target doesn't, it's giving nothing ๐.avoid-fma-max-bitsโ the maximum 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</scheduler>.sms-dfa-historyโ the number of cycles the swing modulo scheduler considers when checking conflicts using DFA.max-inline-insns-recursive-autoโ the maximum number of instructions a non-inline function can grow to via recursive inlining.graphite-allow-codegen-errorsโ whether codegen errors should be ICEs when-fchecking๐ญ.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 during spilling a non-reload pseudo.max-pow-sqrt-depthโ the maximum depth of sqrt chains to use when synthesizing exponentiation by a real constant.max-dse-active-local-storesโ the maximum number of active local stores in RTL dead store elimination.asan-instrument-allocasโ enable asanallocas/VLAsprotection ๐ก๏ธ.max-iterations-computation-costโ a bound on the cost of an expression that computes the number of iterations.max-isl-operationsโ the maximum number of isl operations;0means unlimited โ.graphite-max-arrays-per-scopโ the maximum number of arrays per scop.max-vartrack-reverse-op-sizeโ max size of a loc list for which reverse ops should be added.tracer-dynamic-coverage-feedbackโ the percentage of a function, weighted by execution frequency, that must be covered by trace formation. Used when profile feedback is available.max-inline-recursive-depth-autoโ the maximum depth of recursive inlining for non-inline functions.fsm-scale-path-stmtsโ the scale factor to apply to the number of statements in a threading path when comparing against the number of (scaled) blocks.fsm-maximum-phi-argumentsโ the maximum number of arguments a PHI may have before the FSM threader refuses to try threading through its block ๐ซ.uninit-control-dep-attemptsโ the maximum number of nested calls to search for control dependencies during uninitialized variable analysis.sra-max-scalarization-size-Osizeโ the maximum size, in storage units, of an aggregate that should be considered for scalarization when compiling for size ๐.fsm-scale-path-blocksโ the scale factor to apply to the number of blocks in a threading path when comparing against the number of (scaled) statements.sched-autopref-queue-depthโ hardware autoprefetcher scheduler model control flag. It's the number of lookahead cycles the model looks into; at' 'only enable the instruction sorting heuristic. (Yes, that's a literal space character. Iconic honestly.)loop-versioning-max-inner-insnsโ the maximum number of instructions an inner loop can have before the loop versioning pass decides it's too big to copy.loop-versioning-max-outer-insnsโ the maximum number of instructions an outer loop can have before the loop versioning pass decides it's too big to copy โ and this is discounting any instructions in inner loops that directly benefit from versioning.ssa-name-def-chain-limitโ the maximum number ofSSA_NAMEassignments to follow when determining a property of a variable, like its value. This caps the number of iterations or recursive calls GCC performs when optimizing certain statements, or when determining their validity before issuing diagnostics ๐ต๏ธ.store-merging-max-sizeโ the maximum 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โ the maximum number of VALUEs handled during a singlefind_base_termcall.analyzer-max-enodes-per-program-pointโ the maximum number of exploded nodes per program point within the analyzer, before it terminates analysis of that point ๐.analyzer-max-constraintsโ the maximum 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 maximum depth of exploded nodes that should show up in a dot dump before switching to a less verbose format.analyzer-max-recursion-depthโ the maximum number of times a callsite can appear in a call stack within the analyzer, before it terminates analysis of a call that would recurse deeper ๐.analyzer-max-svalue-depthโ the maximum depth of a symbolic value, before approximating the value as unknown.analyzer-max-infeasible-edgesโ the maximum 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 makes it count as hot ๐ฅ. This parameter is used only in GIMPLE FE.analyzer-bb-explosion-factorโ the maximum number of 'after supernode' exploded nodes the analyzer will tolerate per supernode before it just throws its hands up and terminates the analysis. ๐ranger-logical-depthโ the maximum depth of logical expression evaluation that the ranger will look through when it's evaluating outgoing edge ranges.openacc-kernelsโ picks the mode for handling OpenACCkernelsconstructs. With--param=openacc-kernels=decompose, OpenACCkernelsconstructs get decomposed into parts โ a sequence of compute constructs โ and each one is then handled individually. (This is work in progress, bestie.) With--param=openacc-kernels=parloops, OpenACCkernelsconstructs are handled by the parloops pass, en bloc. That one is the current default. โจ
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. It also uses 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โ the number of Newton iterations for calculating the reciprocal forfloattype. The precision of division is proportional to this param when division approximation is enabled. The default value is1.aarch64-double-recp-precisionโ the number of Newton iterations for calculating the reciprocal fordoubletype. The precision of division is proportional to this param when division approximation is enabled. The default value is2.aarch64-autovec-preferenceโ force an ISA selection strategy for auto-vectorization. Accepts values from0to4, inclusive.0โ use the default heuristics.1โ use only Advanced SIMD for auto-vectorization.2โ use only SVE for auto-vectorization.3โ use both Advanced SIMD and SVE. Prefer Advanced SIMD when the costs are deemed equal.4โ use both Advanced SIMD and SVE. Prefer SVE when the costs are deemed equal.
The default value is 0.
aarch64-loop-vect-issue-rate-nitersโ the tuning for some AArch64 CPUs tries to take both latencies and issue rates into account when deciding whether a loop should be vectorized using SVE, vectorized using Advanced SIMD, or not vectorized at all. If this parameter is set to n, GCC will not use this heuristic for loops that are known to execute in fewer than n Advanced SIMD iterations. ๐
โจ Program Instrumentation Options โจ
GCC supports a whole bunch of command-line options that control adding run-time instrumentation to the code it normally generates. Like, one purpose of instrumentation is collecting profiling statistics โ for finding program hot spots, doing code coverage analysis, or profile-guided optimizations. ๐
Another class of program instrumentation is adding run-time checking to detect programming errors like invalid pointer dereferences or out-of-bounds array accesses, plus deliberately hostile attacks such as 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. iykyk. ๐
-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. fr fr.
You can use the function attribute no_instrument_function to suppress profiling of individual functions when compiling with these options.
-fprofile-arcsโ add code so that program flow arcs are instrumented. During execution the program 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. The 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).
--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. ๐ฅ - 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.
- Compile the source files with
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โ produce 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 convert 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 โ set 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, thus 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 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 variable VAR
-fprofile-generate,-fprofile-generate=path โ enable options usually used for instrumenting application to produce 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 โ register 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-arcsor-ftest-coverageis 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 systems with limited resources which do not support constructors and destructors. The linker could collect the input sections in a continuous memory block and define start and end symbols. The runtime support could dump the profiling information registered in this linker set during program termination to a serial line for example. ๐ฆ
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 = .);
}
-fprofile-note=pathโ bestie, if you hand it apath, GCC drops the.gcnofile riiight into thatpathlocation ๐ . But heads up: if you pair this option with multiple source files, the.gcnofile will be overwritten ๐ญ. One note file, many sources, chaos. You've been warned.-fprofile-prefix-path=pathโ this one is the โจglow-upโจ companion toprofile-generate=profile_dirandprofile-use=profile_dir, and its whole job is telling GCC where the base directory of your built source tree lives ๐ . Why do you care? Because by defaultprofile_dirgets filled with files carrying mangled absolute paths of every object file in the project ๐. And that is not the vibe when the directory you used to build the instrumented binary is a different directory than the one you use to build the optimized-with-profile-feedback binary โ because then the profile data just... won't be found during the optimized build ๐. So in those setups you use-fprofile-prefix-path=pathwithpathpointing at the base directory of the build, which strips off the irrelevant part of the path and keeps all file names relative to the main build directory ๐. Slay.-fprofile-update=methodโ changes up the update method for an app that's been instrumented for profile-feedback-based optimization. The method argument should be one ofsingle,atomicorprefer-atomic.singleโ perfect for single-threaded applications ๐ง.atomicโ this one stops profile corruption by emitting thread-safe code ๐ฅ.prefer-atomicโ gets transformed into eitheratomic(when the target supports it) orsingleotherwise. And guess what, the GCC driver automatically picksprefer-atomicwhen-pthreadshows up on the command line ๐.
Warning: When an application does not properly join all threads (or creates an detached thread), a profile file can be still corrupted. ๐ฑ
-fprofile-filter-files=regexโ instruments only functions from files whose name matches any of the regular expressions (separated by semi-colons) ๐ฏ. For example,-fprofile-filter-files=main\.c;module.*\.cwill instrument onlymain.cand all C files starting with 'module' ๐ธ.-fprofile-exclude-files=regexโ the inverse energy ๐: instruments only functions from files whose name does not match any of the regular expressions (separated by semi-colons). For example,-fprofile-exclude-files=/usr/.*will prevent instrumentation of all files that are located in the/usr/folder ๐ซ.-fprofile-reproducible=[multithreaded|parallel-runs|serial]โ controls the level of reproducibility of the profile gathered by-fprofile-generateโจ. This makes it possible to rebuild a program with the same outcome, which is useful for, like, distribution packages ๐ฆ.- With
-fprofile-reproducible=serialthe profile gathered by-fprofile-generateis reproducible provided the trained program behaves the same at each invocation of the train run, it is not multi-threaded, and profile data streaming is always done in the same order ๐ซถ. Note that profile streaming happens at the end of the program run but also beforeforkfunction is invoked ๐. - Okay real talk: it's quite common that execution counts of some part of programs depend, for example, on the length of temporary file names or on memory space randomization (which may affect hash-table collision rate) ๐ตโ๐ซ. Such non-reproducible parts of programs may be annotated by
"no_instrument_function"function attribute. Andgcov-dumpwith-lcan be used to dump the gathered data and verify that they are indeed reproducible ๐. - With
-fprofile-reproducible=parallel-runsthe collected profile stays reproducible regardless of the order of streaming of the data into gcda files ๐. This setting makes it possible to run multiple instances of an instrumented program in parallel (such as with"make -j"). But it reduces the quality of gathered data, in particular of indirect call profiling ๐.
- With
-fsanitize=addressโ enables AddressSanitizer, a fast memory error detector ๐ต๏ธ. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This option enables-fsanitize-address-use-after-scope. See<https://github.com/google/sanitizers/wiki/AddressSanitizer>for more details. The run-time behavior can be influenced using theASAN_OPTIONSenvironment variable ๐๏ธ. When set to"help=1", the available options are shown at startup of the instrumented program. See<https://github.com/google/sanitizers/wiki/AddressSanitizerFlags#run-time-flags>for a list of supported options. The option cannot be combined with-fsanitize=threador-fsanitize=hwaddress๐ซ. Note that the only target-fsanitize=hwaddressis currently supported on is AArch64.-fsanitize=kernel-addressโ enables AddressSanitizer for the Linux kernel ๐ง. See<https://github.com/google/kasan>for more details.-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 a low memory overhead โก. Memory access instructions are instrumented to detect out-of-bounds and use-after-free bugs. This option enables-fsanitize-address-use-after-scope. See<https://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html>for more details. The run-time behavior can be influenced using theHWASAN_OPTIONSenvironment variable ๐๏ธ. When set to"help=1", the available options are shown at startup of the instrumented program. The option cannot be combined with-fsanitize=threador-fsanitize=address, and is currently only available on AArch64 ๐ .-fsanitize=kernel-hwaddressโ enables Hardware-assisted AddressSanitizer for compilation of the Linux kernel ๐ง. Similar to-fsanitize=kernel-addressbut using an alternate instrumentation method, and similar to-fsanitize=hwaddressbut with instrumentation differences necessary 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 to the-fsanitize=hwaddress. Instrumenting the stack and alloca calls are not on by default but are still possible 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 ๐. The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread. Note: by default the check is disabled at run time ๐ด. To enable it, add"detect_invalid_pointer_pairs=2"to the environment variableASAN_OPTIONS. Using"detect_invalid_pointer_pairs=1"detects an invalid operation only when both pointers are non-null.-fsanitize=pointer-subtractโ instruments subtraction with pointer operands ๐. The option must be combined with either-fsanitize=kernel-addressor-fsanitize=address. The option cannot be combined with-fsanitize=thread. Note: by default the check is disabled at run time ๐ด. To enable it, add"detect_invalid_pointer_pairs=2"to the environment variableASAN_OPTIONS. Using"detect_invalid_pointer_pairs=1"detects an invalid operation only when both pointers are non-null.-fsanitize=threadโ enables ThreadSanitizer, a fast data race detector ๐. Memory access instructions are instrumented to detect data race bugs. See<https://github.com/google/sanitizers/wiki#threadsanitizer>for more details. The run-time behavior can be influenced using theTSAN_OPTIONSenvironment variable ๐๏ธ; see<https://github.com/google/sanitizers/wiki/ThreadSanitizerFlags>for a list of supported options. The option cannot be combined with-fsanitize=address,-fsanitize=leak๐ซ.
Note that sanitized atomic builtins cannot throw exceptions when operating on invalid memory addresses with non-call exceptions (-fnon-call-exceptions).
-fsanitize=leakโ enables LeakSanitizer, a memory leak detector ๐ง. This option only matters for linking of executables, and the executable is linked against a library that overridesmallocand other allocator functions. See<https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>for more details. The run-time behavior can be influenced using theLSAN_OPTIONSenvironment variable ๐๏ธ. The option cannot be combined with-fsanitize=thread๐ซ.-fsanitize=undefinedโ enables UndefinedBehaviorSanitizer, a fast undefined behavior detector ๐. Various computations are instrumented to detect undefined behavior at runtime. See<https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html>for more details. The run-time behavior can be influenced using theUBSAN_OPTIONSenvironment variable ๐๏ธ. Current suboptions are:-fsanitize=shiftโ this option enables checking that the result of a shift operation is not undefined ๐ค. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc. This option has two suboptions,-fsanitize=shift-baseand-fsanitize=shift-exponent.-fsanitize=shift-exponentโ this option enables checking that the second argument of a shift operation is not 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 a shift operation is not undefined. Note that what exactly is considered undefined differs slightly between C and C++, as well as between ISO C90 and C99, etc.-fsanitize=integer-divide-by-zeroโ detects integer division by zero as well asINT_MIN / -1division โ.-fsanitize=unreachableโ with this option, the compiler turns the__builtin_unreachablecall into a diagnostics message call instead ๐ข. When reaching the__builtin_unreachablecall, the behavior is undefined.-fsanitize=vla-boundโ this option instructs the compiler to check that the size of a variable length array is positive โ .
-fsanitize=nullโ pointer checking time ๐ . Build your app with this turned on and it will throw an error message at you when it tries to dereference aNULLpointer, or if a reference (possibly an rvalue reference) is bound to aNULLpointer, or if a method gets invoked on an object pointed to by aNULLpointer.-fsanitize=returnโ return statement checking โจ. Programs built with this one turned on will error out when the end of a non-void function is reached without actually returning a value. C++ only, bestie.-fsanitize=signed-integer-overflowโ signed integer overflow checking ๐ฅ. We check that the result of+,*, and both unary and binary-does not overflow in the signed arithmetics. Heads up tho: integer promotion rules must be taken into account. Meaning this next one is not an overflow:
signed char a = SCHAR_MAX;
a++;
-fsanitize=boundsโ instruments array bounds ๐. Various out of bounds accesses get detected. Not instrumented: flexible array members, flexible array member-like arrays, and initializers of variables with static storage.-fsanitize=bounds-strictโ 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.-fsanitize=alignmentโ checks alignment of pointers when they get 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โ instruments 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 legitimate way of obtaining infinities and NaNs. It's giving "on purpose, actually."-fsanitize=float-cast-overflowโ floating-point type to integer conversion checking ๐ฆ. We check that the result of the conversion does not overflow. Unlike other similar options,-fsanitize=float-cast-overflowis not enabled by-fsanitize=undefined. Also, this option does not work well withFE_INVALIDexceptions enabled.-fsanitize=nonnull-attributeโ instruments calls, checking whether null values are not passed to arguments marked as requiring a non-null value by thenonnullfunction attribute ๐ซถ.-fsanitize=returns-nonnull-attributeโ instruments return statements in functions marked with thereturns_nonnullfunction attribute, to detect returning null values from those functions ๐.-fsanitize=boolโ instruments loads from bool ๐. If a value other than 0/1 is loaded, a run-time error is issued.-fsanitize=enumโ instruments loads from an enum type ๐. If a value outside the range of values for the enum type is loaded, a run-time error is issued.-fsanitize=vptrโ instruments 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โ instruments pointer arithmetics ๐. If the pointer arithmetics overflows, a run-time error is issued.-fsanitize=builtinโ instruments arguments to selected builtin functions ๐. If an invalid value is passed to such arguments, a run-time error is issued. E.g. passing0as the argument to__builtin_ctzor__builtin_clzinvokes undefined behavior and is diagnosed by this option.
While -ftrapv causes traps for signed overflows to be emitted, -fsanitize=undefined gives a diagnostic message ๐ข. This currently works only for the C family of languages.
-fno-sanitize=allโ this one disables all previously enabled sanitizers ๐. And no,-fsanitize=allis not allowed, because some sanitizers cannot be used together. Periodt.-fasan-shadow-offset=numberโ forces GCC to use a custom shadow offset in AddressSanitizer checks ๐ฏ. Useful for experimenting with different shadow memory layouts in Kernel AddressSanitizer.-fsanitize-sections=s1,s2,...โ sanitize global variables in selected user-defined sections โจ.simay contain wildcards.-fsanitize-recover[=opts]โ-fsanitize-recover=controls error recovery mode for the sanitizers mentioned in the comma-separated list of opts. Enabling this option for a sanitizer component causes it to attempt to continue running the program as if no error happened. Which 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 is reported, and then the program 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 to halt_on_error=0 for ThreadSanitizer and UndefinedBehaviorSanitizer, while the default value for AddressSanitizer is halt_on_error=1. This can be overridden through setting the halt_on_error flag in the corresponding environment variable.
Syntax without an explicit opts parameter is deprecated. It is 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 ๐. The option sets-fstack-reuseto none.-fsanitize-undefined-trap-on-errorโ instructs the compiler to report undefined behavior using__builtin_traprather than alibubsanlibrary routine ๐ชค. The advantage? Thelibubsanlibrary is not needed and is not linked in, so this is usable even in freestanding environments. Slay.-fsanitize-coverage=trace-pcโ enables coverage-guided fuzzing code instrumentation ๐. Inserts a call to__sanitizer_cov_trace_pcinto every basic block.-fsanitize-coverage=trace-cmpโ enables dataflow guided fuzzing code instrumentation ๐ฌ. Inserts a call to__sanitizer_cov_trace_cmp1,__sanitizer_cov_trace_cmp2,__sanitizer_cov_trace_cmp4or__sanitizer_cov_trace_cmp8for integral comparison with both operands variable, or__sanitizer_cov_trace_const_cmp1,__sanitizer_cov_trace_const_cmp2,__sanitizer_cov_trace_const_cmp4or__sanitizer_cov_trace_const_cmp8for integral comparison with one operand constant,__sanitizer_cov_trace_cmpfor__sanitizer_cov_trace_cmpdfor float or double comparisons, and__sanitizer_cov_trace_switchfor switch statements.-fcf-protection=[full|branch|return|none|check]โ enables code instrumentation of control-flow transfers to increase program security by checking that target addresses of control-flow transfer instructions (such as indirect function call, function return, indirect jump) are valid ๐ก๏ธ. This prevents diverting the flow of control to an unexpected target. It's intended to protect against such threats as Return-oriented Programming (ROP), and similarly call/jmp-oriented programming (COP/JOP).
The value branch tells the compiler to implement checking of validity of control-flow transfer at the point of indirect branch instructions, i.e. call/jmp instructions. The value return implements checking of validity at the point of returning from a function. The value full is an alias for specifying both branch and return. The value none turns off instrumentation.
The value check is used for the final link with link-time optimization (LTO) ๐. An error is issued if LTO object files are compiled with different -fcf-protection values. The value check is ignored at the compile time.
The macro __CET__ is defined when -fcf-protection is used. The first bit of __CET__ is set to 1 for the value branch, and the second bit of __CET__ is set to 1 for the return.
You can also use the nocf_check attribute to identify which functions and calls should be skipped from instrumentation โจ.
Currently the x86 GNU/Linux target provides an implementation based on Intel Control-flow Enforcement Technology (CET) which works for i686 processor or newer.
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โ okay bestie, this is the bodyguard era ๐ก๏ธ. It emits extra code to check for buffer overflows, like stack smashing attacks. How? By adding a guard variable to functions with vulnerable objects โ which includes functions that callalloca, and functions with buffers larger than or equal to 8 bytes. The guards get initialized when a function is entered and 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 are considered, so optimized-away variables or variables allocated in registers don't count.-fstack-protector-allโ like-fstack-protectorexcept that all functions are protected. No favorites, everyone gets a bodyguard. ๐-fstack-protector-strongโ like-fstack-protectorbut it includes additional functions to be protected โ those that have local array definitions, or have references to local frame addresses. And same as before: only variables that are 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. If you didn't say the magic word, no protection for you. ๐-fstack-checkโ generates code to verify that you do not go beyond the boundary of the stack. You should specify this flag if you are 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 is only one stack. ๐ง
Heads up: this switch does not actually cause checking to be done โ the operating system or the language runtime has to do that. The switch just causes generation of code to ensure that they see the stack being extended. It's giving "I set up the vibe, you do the work". ๐
You can additionally specify a string parameter:
nomeans no checkinggenericmeans force the use of old-style checkingspecificmeans 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 it comes with the following drawbacks, and bestie, there are three:
- 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 is 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. Not the slay we wanted.
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. But ngl, 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. So it prevents allocations from jumping over any stack guard page provided by the operating system. ๐ฅ
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 three are a lil trio ๐. They generate code to ensure that the stack does not 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 is 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, as it is no longer necessary to calculate a good stack size to use for each thread. This is currently 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 one is only available when compiling C++ code, so C girlies sit this out. ๐ It turns on (or off, if using-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 has not 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. ๐
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โ when used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, it causes debug versions of the runtime functions for the vtable verification feature to be called. This flag also causes the compiler to log information about which vtable pointers it finds for each class. This information is written to a file namedvtv_set_ptr_data.login the directory named by the environment variableVTV_LOGS_DIRif that is defined, or the current working directory otherwise. ๐ฆ
Note: This feature appends data to the log file. If you want a fresh log file, be sure to delete any existing one. fr fr, don't skip this step. ๐
-fvtv-countsโ this is a debugging flag. When used in conjunction with-fvtable-verify=stdor-fvtable-verify=preinit, this causes the compiler to 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 this information for each compilation unit. The compiler writes this information to a file namedvtv_count_data.login the directory named by the environment variableVTV_LOGS_DIRif that is defined, or the current working directory otherwise. It also counts the size of the vtable pointer sets for each class, and writes this information tovtv_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โ generates instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site. (On some platforms,__builtin_return_addressdoes not work beyond the current function, so the call site information 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 may be looked 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. This means that 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. 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 may be given the attribute no_instrument_function, in which case this instrumentation is not done. This can be used, for example, for the profiling functions listed above, high-priority interrupt routines, and any functions from which the profiling functions cannot safely be called (perhaps signal handlers, if the profiling routines generate output or allocate memory). ๐ง
-finstrument-functions-exclude-file-list=file,file,...โ okay so this one sets the list of functions that are excluded from instrumentation (go read the description of-finstrument-functionsif you need the lore, bestie). If the file that contains a function definition matches with one of file, then that function does not get instrumented. And how does the matching work? On substrings ๐ if the file parameter is a substring of the file name, it's considered a match. Periodt.
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 instead it sets the list of function names to be excluded from instrumentation. The function name you're matching against is its user-visible name, likevector<int> blah(const vector<int> &), not the internal mangled name (e.g.,_Z4blahRSt6vectorIiSaIiEE) ๐. Matching is done on substrings: if the sym parameter is a substring of the function name, it's 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]โ generateNNOPs right at the beginning of each function, with the function entry point before the *M*th NOP ๐. IfMis omitted, it defaults to0so 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 interfacegen_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 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 is run on each C source file before actual compilation, no cap ๐ซถ.
If you use the -E option, nothing is done except preprocessing. Some of these options make sense only 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.
-D nameโ predefine name as a macro, with definition1.-D name=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 ๐ธ.
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.
-U nameโ cancel any previous definition of name, either built in or provided with a-Doption. Gone. Deleted. Not me erasing your macro ๐ญ-include fileโ 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 is 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 โจ.
-imacros fileโ exactly like-include, except that any output produced by scanning file is thrown away ๐๏ธ. Macros it defines remain defined. This allows you to acquire all the macros from a header without also processing its declarations, which is lowkey iconic.
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, bestie, don't panic ๐-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.
This implies that the choice of angle brackets or double quotes in an #include directive does not in itself determine whether that header appears in -MM dependency output ๐
-MF fileโ when used with-Mor-MM, specifies a file to write the dependencies to. If no-MFswitch is given the preprocessor sends the rules to the same place it would send preprocessed output.
When used with the driver options -MD or -MMD, -MF overrides the default dependency output file.
If file is -, then the dependencies are written to stdout โจ
-MGโ in conjunction with an option such as-Mrequesting dependency generation,-MGassumes missing header files are generated files and adds them to the dependency list without raising an error. The dependency filename is taken directly from the#includedirective without prepending any path.-MGalso suppresses preprocessed output, as a missing header file renders this useless.
This feature is used in automatic updating of makefiles ๐
-Mno-modulesโ disable dependency generation for compiled module interfaces. That's it, that's the whole vibe ๐ฆ-MPโ this option instructs CPP to add a phony target for each dependency other than the main file, causing each to depend on nothing. These dummy rules work around errorsmakegives if you remove header files without updating theMakefileto match.
This is typical output:
test.o: test.c test.h
test.h:
-MT targetโ change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as.c, and appends the platform's usual object suffix. The result is the target.
An -MT option sets the target to be exactly the string you specify. If you want multiple targets, you can specify them as a single argument to -MT, or use multiple -MT options ๐
For example, -MT '$(objpfx)foo.o' might give
$(objpfx)foo.o: foo.c
-MQ targetโ same as-MT, but it quotes any characters which are special to Make.-MQ '$(objpfx)foo.o'gives
$$(objpfx)foo.o: foo.c
The default target is automatically quoted, as if it were given with -MQ.
-MDโ-MDis equivalent to-M -MF file, except that-Eis not implied. The driver determines file based on whether an-ooption is given. If it is, the driver uses its argument but with a suffix of.d, otherwise it takes the name of the input file, removes any directory components and suffix, and applies a.dsuffix.
If -MD is used in conjunction with -E, any -o switch is understood to specify the dependency output file, but if used without -E, each -o is understood to specify a target object file.
Since -E is not implied, -MD can be used to generate a dependency output file as a side effect of the compilation process โจ
-MMDโ like-MDexcept mention only user header files, not system header files. Simple. Clean. Iconic ๐
okay bestie we're still deep in preprocessor territory and it's giving very much "the compiler's inner monologue" energy. buckle up. ๐
-fpreprocessedโ tells the preprocessor "bestie, this file is already preprocessed, chill." ๐ It suppresses stuff like macro expansion, trigraph conversion, escaped newline splicing, and the processing of most directives. It does still recognize and remove comments, so you can hand a file that was preprocessed with-Cstraight to the compiler with zero problems. In this mode, the integrated preprocessor is little more than a tokenizer for the front ends. And heads up:-fpreprocessedis implicit if your input file has one of the extensions.i,.iior.miโ those are literally the extensions GCC uses for preprocessed files created by-save-temps. โจ-fdirectives-onlyโ when preprocessing, handle directives, but do not expand macros. The way this behaves depends on the-Eand-fpreprocessedoptions. ๐- With
-E, preprocessing is limited to the handling of directives such as#define,#ifdef, and#error. Other preprocessor operations, such as macro expansion and trigraph conversion, are not performed. Also,-dDgets implicitly enabled. ๐ซถ - With
-fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros such as__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. that's it, that's the whole vibe. ๐-fextended-identifiersโ accept universal character names and extended characters in identifiers. This one is enabled by default for C99 (and later C standard versions) and C++. ๐ธ-fno-canonical-system-headersโ when preprocessing, do not shorten system header paths with canonicalization. no glow-ups for your paths today. ๐-fmax-include-depth=depthโ sets the maximum depth of the nested#include. The default is200. ๐-ftabstop=widthโ sets the distance between tab stops. This helps the preprocessor report correct column numbers in warnings or errors, even if tabs appear on the line. If the value is less than1or greater than100, the option is ignored. The default is8. โญ-ftrack-macro-expansion[=level]โ tracks the locations of tokens across macro expansions. This lets the compiler emit a diagnostic about the current macro expansion stack when a compilation error happens inside a macro expansion. Using this option makes the preprocessor and the compiler consume more memory. The level parameter picks how precise the token location tracking is, so you can dial the memory consumption down if you need to. ๐ง- Value
0of level de-activates this option. - Value
1tracks token locations in a degraded mode for the sake of 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. - When this option is given no argument, the default parameter value is
2.
- Value
ngl, note that -ftrack-macro-expansion=2 is activated by default. so it's already on, bestie. ๐
-fmacro-prefix-map=old=newโ when preprocessing files residing in directory old, expand the__FILE__and__BASE_FILE__macros as if the files resided in directory new instead. You can use this to change an absolute path to a relative path by using.for new, which can result in more reproducible builds that are location independent. ๐ This option also affects__builtin_FILE()during compilation. See also-ffile-prefix-map. ๐-fexec-charset=charsetโ sets the execution character set, used for string and character constants. The default isUTF-8. charset can be any encoding supported by the system'siconvlibrary routine. ๐-fwide-exec-charset=charsetโ sets 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 corresponds to the width ofwchar_tand the big-endian or little-endian byte order being used for code generation. As with-fexec-charset, charset can be any encoding supported by the system'siconvlibrary routine; however, you will have problems with encodings that do not fit exactly inwchar_t. ๐ญ-finput-charset=charsetโ sets the input character set, used for translation from the character set of the input file to the source character set used by GCC. If the locale does not specify, or GCC cannot get this information from the locale, the default isUTF-8. This can be overridden by either the locale or this command-line option. Currently the command-line option takes precedence if there's a conflict. charset can be any encoding supported by the system'siconvlibrary routine. ๐ฆ-fpch-depsโ when using precompiled headers, this flag causes the dependency-output flags to also list the files from the precompiled header's dependencies. If not specified, only the precompiled header is listed and not the files that were used to create it, because those files are not consulted when a precompiled header is used. ๐-fpch-preprocessโ this option allows use of a precompiled header together with-E. It inserts a special#pragma,#pragma GCC pch_preprocess "filename", in the output to mark the place where the precompiled header was found, and 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 is switched on by -save-temps.
bestie, do not write this #pragma in your own code. it is safe to edit the filename if the PCH file is available in a different location, though. The filename may be absolute or it may be 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 this option is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory, when it's present in the preprocessed input, 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 this can be inhibited with the negated form-fno-working-directory. If the-Pflag is present in the command line, this option has no effect, since no#linedirectives are emitted whatsoever. ๐ซ-A predicate=answerโ makes an assertion with the predicate predicate and answer answer. This form is preferred to the older form-A predicate(answer), which is still supported, because it does not use shell special characters. โจ-A -predicate=answerโ cancels an assertion with the predicate predicate and answer answer. ๐-Cโ do not discard comments. All comments are passed through to the output file, except for comments in processed directives, which are deleted along with the directive. โ ๏ธ
you should be prepared for side effects when using-C; it causes the preprocessor to treat comments as tokens in their own right. For example, comments appearing at the start of what would be a directive line have the effect of turning that line into an ordinary source line, since the first token on the line is no longer a#. ๐ฑ
-CCโ do not discard comments, including during macro expansion. This is like-C, except that comments contained within macros are also passed through to the output file where the macro is expanded. ๐ธ
In addition to the side effects of the -C option, the -CC option causes all C++-style comments inside a macro to be converted to C-style comments. This is to prevent later use of that macro from inadvertently commenting out the remainder of the source line. ๐
The -CC option is generally used to support lint comments.
-Pโ inhibits generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which 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 details. ๐
note that 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 are defined by ISO C 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. See the -std and -ansi options. ๐
-remapโ enables special code to work around file systems which only permit very short file names, such as MS-DOS. ๐พ-Hโ prints 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 are 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 those 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
and boom, every single predefined macro just shows up. ๐
ngl bestie, if you use-dMwithout-E, then-dMgets interpreted as a synonym for-fdump-rtl-machinstead. so like. keep-Ethere or you're getting something completely different. ๐
-dDโ basically-dMbut with two lil differences: 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, except it only emits the macro names, not their expansions. lowkey minimal of it.-dIโ outputs#includedirectives in addition to the result of preprocessing. ๐-dUโ like-dDexcept only macros that are expanded, or whose definedness is tested in preprocessor directives, get output. the output is delayed until the use or test of the macro happens, and#undefdirectives are also output for macros that were tested but undefined at that time. iconic behavior fr fr.-fdebug-cppโ okay so this one is only useful for debugging GCC itself. when used from CPP or with-E, it dumps debugging information about location maps, and 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. that's it. that's the whole vibe.-Wp,optionโ you can use-Wp,optionto bypass the compiler driver and pass option directly through to the preprocessor. if option contains commas, it gets split into multiple options at the commas. but (and this is the important part bestie) 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. periodt. ๐-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. and if you wanna pass an option that takes an argument, you gotta use-Xpreprocessortwice โ once for the option and once for the argument. yes really, twice. ๐-no-integrated-cppโ perform preprocessing as a separate pass before compilation. by default, GCC does 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โ adjusts GCC to expect large source files, at the expense of slower compilation and higher memory usage. so like. trade-off city.
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 ๐ธ
okay so you can also pass options to the assembler, bestie. here's how:
-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. and again โ if you wanna pass an option that takes an argument, you must use-Xassemblertwice, once for the option and once for the argument. same deal as before, no cap. ๐
๐ Options for Linking ๐
these options come into play when the compiler links object files into an executable output file. and they are meaningless if the compiler is not doing a link step. like, literally nothing. so don't stress about them otherwise. โจ
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. that's the whole note. three icons, one rule. ๐-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 building 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 the 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 the object files in an 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 a static library instead. alternatively it is possible to use H.J. Lu's binutils with support for mixed objects. iykyk. ๐ซถ
-fuse-ld=bfdโ use the bfd linker instead of the default linker.-fuse-ld=goldโ use the gold linker instead of the default linker.-fuse-ld=lldโ use the LLVM lld linker instead of the default linker.-fuse-ld=moldโ use the Modern Linker (mold) instead of the default linker. yes mold. slay. ๐ฅ-llibrary-l libraryโ search the library named library when linking. (the second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) ๐
the -l option is passed directly to the linker by GCC. refer to your linker documentation for exact details. the general description below applies to the GNU linker.
the linker searches a standard list of directories for the library. the directories searched include several standard system directories plus any that you specify with -L.
static libraries are archives of object files, and have file names like liblibrary.a. some targets also support shared libraries, which typically have names like liblibrary.so. if both static and shared libraries are found, the linker gives preference to linking with the shared library unless the -static option is used.
it makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. if bar.o refers to functions in z, those functions may not be loaded. order matters bestie, fr fr. ๐
-lobjcโ you need this special case of the-loption in order to link an Objective-C or Objective-C++ program. ๐-nostartfilesโ do not use the standard system startup files when linking. the standard system libraries are used normally, unless-nostdlib,-nolibc, or-nodefaultlibsis used. โจ-nodefaultlibsโ do not use the standard system libraries when linking. only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as-static-libgccor-shared-libgcc, are ignored. the standard startup files are used normally, unless-nostartfilesis used.
the compiler may generate calls to memcmp, memset, memcpy and memmove. these entries are usually resolved by entries in libc. these entry points should be supplied through some other mechanism when this option is specified. ๐
-nolibcโ do not use the C library or system libraries tightly coupled with it when linking. still link with the startup files,libgccor toolchain-provided language support libraries such aslibgnat,libgfortranorlibstdc++, unless options preventing their inclusion are used as well. this typically removes-lcfrom the link command line, as well as system libraries that normally go with it and become meaningless when absence of a C library is assumed โ for example-lpthreador-lmin some configurations. this is intended for bare-board targets when there is indeed no C library available. ๐ฆ-nostdlibโ do not use the standard system startup files or libraries when linking. no startup files and only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as-static-libgccor-shared-libgcc, are ignored. that's the big one. ๐
So like, bestie, your compiler is out here potentially generating calls to memcmp, memset, memcpy and memmove, okay? And those entries are usually resolved by entries in libc. But when this option is specified, you gotta supply those entry points through some other mechanism. No cap.
One of the standard libraries that gets bypassed by -nostdlib and -nodefaultlibs is libgcc.a โ and that's a whole library of internal subroutines that GCC uses to overcome shortcomings of particular machines, or just like, special needs for some languages. It's giving โจsupport systemโจ.
In most cases you literally need libgcc.a, even when you're trying to avoid other standard libraries. In other words: when you specify -nostdlib or -nodefaultlibs, you should usually specify -lgcc as well. That's how you ensure you have no unresolved references to internal GCC library subroutines. (An example of such an internal subroutine is __main, which is used to make sure C++ constructors get called. ๐ซถ)
-eentry โ--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. ๐-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 specify this linker option. Consistency is the vibe check here, fr fr.-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. For predictable results, you must also specify the same set of options used for compilation (-fpie,-fPIE, or model suboptions) when you specify this linker option. Iconic behaviour, but you have to keep it consistent. ๐-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 it should be used consistently for both compilation and linking. Don't half-send it, bestie. ๐งต-rโ Produce a relocatable object as output. This is also known as partial linking.-rdynamicโ Pass the flag-export-dynamicto the ELF linker, on targets that support it. This instructs the linker to add all symbols, not only used ones, to the dynamic symbol table. This option is needed for some uses ofdlopen, or to allow obtaining backtraces from within a program. ๐ฆ-sโ Remove all symbol table and relocation information from the executable. Poof. Gone. Stripped. ๐-staticโ On systems that support dynamic linking, this overrides-pieand prevents linking with the shared libraries. On other systems, this option has no effect. Lowkey a flex on shared libraries.-sharedโ Produce a shared object which can then be linked with other objects to form an executable. Not all systems support this option. 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 providelibgccas a shared library, these options force the use of either the shared or static version, respectively. If no shared version oflibgccwas built when the compiler was configured, these options have no effect.
There are several situations in which an application should use the shared libgcc instead of the static version. The most common of these is when the application wishes to throw and catch exceptions across different shared libraries. In that case, each of the libraries as well as the application itself should use the shared libgcc.
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 the right thing to do. โจ
If, instead, you use the GCC driver to create shared libraries, you may find that they are not always linked with the shared libgcc. 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 allows exceptions to propagate through such shared libraries, without incurring relocation costs at library load time. ๐ฅ
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 is linked with the shared libgcc.
-static-libasanโ When the-fsanitize=addressoption is used to link a program, the GCC driver automatically links againstlibasan. Iflibasanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibasan. The-static-libasanoption directs the GCC driver to linklibasanstatically, without necessarily linking other libraries statically. ๐-static-libtsanโ When the-fsanitize=threadoption is used to link a program, the GCC driver automatically links againstlibtsan. Iflibtsanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibtsan. The-static-libtsanoption directs the GCC driver to linklibtsanstatically, without necessarily linking other libraries statically. ๐งต-static-liblsanโ When the-fsanitize=leakoption is used to link a program, the GCC driver automatically links againstliblsan. Ifliblsanis available as a shared library, and the-staticoption is not used, then this links against the shared version ofliblsan. The-static-liblsanoption directs the GCC driver to linkliblsanstatically, without necessarily linking other libraries statically. ๐ง-static-libubsanโ When the-fsanitize=undefinedoption is used to link a program, the GCC driver automatically links againstlibubsan. Iflibubsanis available as a shared library, and the-staticoption is not used, then this links against the shared version oflibubsan. The-static-libubsanoption directs the GCC driver to linklibubsanstatically, without necessarily linking other libraries statically. ๐จ-static-libstdc++โ When theg++program is used to link a C++ program, it normally automatically links againstlibstdc++. Iflibstdc++is available as a shared library, and the-staticoption is not used, then this links against the shared version oflibstdc++. That is normally fine. However, it is sometimes useful to freeze the version oflibstdc++used by the program without going all the way to a fully static link. The-static-libstdc++option directs theg++driver to linklibstdc++statically, without necessarily linking other libraries statically. ๐ง-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. ๐ซ-Tscript โ Use script as the linker script. This option is supported by most systems using the GNU linker. On some targets, such as bare-board targets without an operating system, the-Toption may be required when linking to avoid references to undefined symbols. ๐-Xlinkeroption โ Pass option as an option to the linker. You can use this to supply system-specific linker options that GCC does not recognize.
If you want to pass an option that takes a separate argument, you must use -Xlinker twice โ once for the option and once for the argument. For example, to pass -assert definitions, you must write:
-Xlinker -assert -Xlinker definitions
It does not work to write:
-Xlinker "-assert definitions"
because this passes the entire string as a single argument, which is not what the linker expects. ๐ญ
When using the GNU linker, it is 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.
-Wl,option โ Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. 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. ๐
-usymbol โ Pretend the symbol symbol is 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. ๐ช-zkeyword โ-zis passed directly on to the linker along with the keyword keyword. See the section in the documentation of your linker for permitted values and their meanings. Iykyk. ๐
โจ Options for Directory Search โจ
These options specify directories to search for header files, for libraries, and for parts of the compiler: ๐
-Idir โ-iquotedir โ-isystemdir โ-idirafterdir โ 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$SYSROOTis replaced by the sysroot prefix; see--sysrootand-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:
- 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 you gave with
-iquoteget searched in left-to-right order, literally the order they show up on the command line. ๐ - Directories you passed with
-Iget scanned left-to-right. periodt. - Directories you passed with
-isystemget scanned left-to-right too. - Then the standard system directories get scanned.
- And finally, directories you passed with
-idirafterget scanned left-to-right. last but not least bestie ๐ซถ
You can use -I to override a system header file by swapping in your own version, because these directories get searched before the standard system header directories. ๐ BUT โ and this is the important part โ you should not use this option to add directories that hold vendor-supplied system header files. Use -isystem for that, okay? no cap.
The -isystem and -idirafter options also mark the directory as a system directory, so it gets the exact same special treatment that the standard system directories get. โจ
Now this one is a lil tricky: if a standard system include directory, or a directory given with -isystem, is also specified with -I, then the -I option is ignored. ๐ญ The directory is still searched โ but as a system directory, at its normal position in the system include chain. Why? To make sure GCC's procedure to fix buggy system headers, and the ordering for the "#include_next" directive, don't get inadvertently changed. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options instead.
-I-โ Split the include path. This option has been deprecated. 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 you specify additional directories with -I options after the -I-, those directories get searched for all #include directives.
On top of that, -I- inhibits the use of the directory of the current file directory as the first search directory for "#include "file"". And there is literally no way to override this effect of -I-. ๐
-iprefix prefixโ Specifyprefixas the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, you should include the final/. ๐-iwithprefix dir-iwithprefixbefore dirโ Appenddirto the prefix specified previously with-iprefix, and add the resulting directory to the include search path.-iwithprefixbeforeputs it in the same place-Iwould;-iwithprefixputs it where-idirafterwould. ๐-isysroot dirโ This option is like the--sysrootoption, but it 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. so exclusive, we love that for you ๐-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 hands off bestie, it's not for us ๐-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. no shortcuts, no glow-ups, just vibes โจ--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. so they split the work, main character energy fr fr
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. โจ
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. iykyk ๐
-fstack-reuse=reuse-levelโ This option controls stack space reuse for user declared local/auto variables and compiler generated temporaries.reuse_levelcan beall,named_vars, ornone.allenables stack reuse for all local variables and temporaries,named_varsenables the reuse only for user defined local variables with names, andnonedisables stack reuse completely. The default value isall. The option is needed when the program extends the lifetime of a scoped local variable or a compiler generated temporary beyond the end point defined by the language. When a lifetime of a variable ends, and if the variable lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. Legacy code extending local lifetime is likely to break with the stack reuse optimization. ๐ญ
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?
}
The lifetime of a compiler generated temporary is well defined by the C++ standard. When a lifetime of a temporary ends, and if the temporary lives in memory, the optimizing compiler has the freedom to reuse its stack space with other temporaries or scoped local variables whose live range does not overlap with it. However some of the legacy code relies on the behavior of older compilers in which temporaries' stack space is not reused, the aggressive stack reuse can lead to runtime errors. This option is used to control the temporary stack reuse optimization. ๐
-ftrapvโ This option generates traps for signed overflow on addition, subtraction, multiplication operations. The options-ftrapvand-fwrapvoverride each other, so using-ftrapv -fwrapvon the command-line results in-fwrapvbeing effective. Note that only active options override, so using-ftrapv -fwrapv -fno-wrapvon the command-line results in-ftrapvbeing effective. ๐ฅ
so order matters and active options are the ones that count โ don't get caught lacking bestie ๐
-fwrapvโ bestie, this one tells the compiler: assume signed arithmetic overflow for addition, subtraction and multiplication just wraps around using twos-complement representation. Cute, right? It enables some optimizations and disables others. And here's the tea:-ftrapvand-fwrapvoverride each other, so if you put-ftrapv -fwrapvon the command-line,-fwrapvis the one that wins. But โ and this is important โ only active options override, so-ftrapv -fwrapv -fno-wrapvon the command-line means-ftrapvis the one that's effective. ๐-fwrapv-pointerโ this instructs the compiler to assume that pointer arithmetic overflow on addition and subtraction wraps around using twos-complement representation. This flag disables some optimizations which assume pointer overflow is invalid. โจ-fstrict-overflowโ this option implies-fno-wrapv -fno-wrapv-pointerand when negated implies-fwrapv -fwrapv-pointer. That's it, that's the whole vibe. ๐ฆ-fexceptionsโ Enable exception handling. Generates 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, although it does not affect execution. If you do not 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 do not normally require it. However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don't use exception handling. ๐ซถ-fnon-call-exceptionsโ Generate code that allows trapping instructions to throw exceptions. Note that 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. ๐-fdelete-dead-exceptionsโ Consider that instructions that may throw exceptions but don't otherwise contribute to the execution of the program can be optimized away. This option is enabled by default for the Ada compiler, as permitted by the Ada language specification. Optimization passes that cause dead exceptions to be removed are enabled independently at different optimization levels. ๐-funwind-tablesโ Similar to-fexceptions, except that it just generates any needed static data, but 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. no cap ๐-fasynchronous-unwind-tablesโ Generate unwind table in DWARF format, if supported by target machine. The table is exact at each instruction boundary, so it can be used for stack unwinding from asynchronous events (such as debugger or garbage collector). ๐ธ-fno-gnu-uniqueโ okay so on systems with 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 are unique even in the presence ofRTLD_LOCAL; this is 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. But this causesdlcloseto be ignored for affected DSOs; if your program relies on reinitialization of a DSO viadlcloseanddlopen, you can use-fno-gnu-unique. the way that one sentence just kept goingโฆ iconic ๐ญ-fpcc-struct-returnโ Returnshortstructandunionvalues 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).
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โ Returnstructandunionvalues in registers when possible. This is more efficient for small structures than-fpcc-struct-return. โญ
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 energy fr fr ๐
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โ Allocate to anenumtype only as many bytes as it needs for the declared range of possible values. Specifically, theenumtype is equivalent to the smallest integer type that has enough room. tiny enum, big slay ๐
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โ Override 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, which do not allocate storage. ๐
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.
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 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 we're rooting for you ๐ซถ
-fno-identโ Ignore the#identdirective. bye bestie ๐-finhibit-size-directiveโ Don't output a.sizeassembler directive, or anything else that would cause trouble if the function is split in the middle, and the two halves are placed at locations far apart in memory. This option is used when compilingcrtstuff.c; you should not need to use it for anything else. ๐-fverbose-asmโ Put extra commentary information in the generated assembly code to make it more readable. This option is generally only of use to those who actually need to read the generated assembly code (perhaps while debugging the compiler itself). ๐ญ
-fno-verbose-asm, the default, causes the extra information to be omitted and is useful when 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 and hence the precise format of the comments is subject to change. iykyk ๐
-frecord-gcc-switchesโ okay so this one literally records the command line you used to invoke the compiler straight into the object file that's being created. Iconic. But bestie, heads up: it's only implemented on some targets, and the exact format of the recording is dependent on the target and the binary file format โ it usually takes the form of a section containing ASCII text. This switch is related to-fverbose-asm, except that one only records info in the assembler output file as comments, so it never reaches the object file. Also peep-grecord-gcc-switchesfor another way of storing compiler options into the object file.-fpicโ generate position-independent code (PIC) that's suitable for use in a shared library, if it's supported for the target machine. This kind of code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (and no, 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 saying-fpicdoes not work; in that case, recompile with-fPICinstead. (Those maximums are 8k on the SPARC, 28k on AArch64 and 32k on the m68k and RS/6000. The x86 has no such limit, main character energy.)
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 you use these 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 leads to more efficient code by eliminating PLT stubs and exposing GOT loads to optimizations. On architectures such as 32-bit x86 where PLT stubs expect the GOT pointer in a specific register, this gives more register allocation freedom to the compiler. 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 for switch statements, 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 do not require a GOT and this option is not needed.-fno-bit-testsโ do not use bit tests for switch statements, 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.
-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 ๐ญ.
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 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.
-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, always generate them instead of using descriptors. Otherwise, for targets that do not need them โ like, for example, HP-PA or IA-64 โ do nothing.
A trampoline is a small piece of 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. Therefore, it requires the stack to be made executable in order for the program to work properly.
-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. ๐ซถ
-fvisibility=[default|internal|hidden|protected]โ set 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. Periodt.
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. ๐
For those of you adding visibility support to code that already exists, bestie, you're gonna wanna know about #pragma GCC visibility โ it's lowkey a lifesaver ๐
. The way it works is you wrap the declarations you wanna set visibility for, like with #pragma GCC visibility push(hidden) and #pragma GCC visibility pop. Wrap it, set it, pop it. Iconic.
But fr fr, keep in mind that symbol visibility is part of the API interface contract โ so all new code should always specify visibility when it's not the default. Like, declarations that are only meant for use inside the local DSO should always be explicitly marked as hidden, so you dodge those PLT indirection overheads โ and making it abundantly clear also helps readability and self-documentation of the code. Self-documenting code is main character energy, no cap. ๐
Heads up though: because of ISO C++ specification requirements,operator newandoperator deletemust always be of default visibility. That's not a vibe, that's a rule.
Also be aware that headers from outside your project โ especially system headers and headers from any other library you use โ might not be expecting to be compiled with anything other than default visibility. You may need to explicitly say #pragma GCC visibility push(default) before including any such headers. Protect your peace. ๐ซถ
extern declarations are not affected by -fvisibility, so a lot of code can be recompiled with -fvisibility=hidden with zero modifications. Slay. But โ and this is the catch โ that means calls to extern functions with no explicit visibility go through the PLT, so it's more effective to use __attribute ((visibility)) and/or #pragma GCC visibility to tell the compiler which extern declarations should be treated as hidden. Do the extra step, babe, it's worth it. โจ
Now, -fvisibility does affect C++ vague linkage entities. Which means, for instance, that an exception class thrown between DSOs must be explicitly marked with default visibility so that the type_info nodes are unified between the DSOs. Cross-DSO drama avoidance, honestly.
There's a whole overview of these techniques, their benefits, and how to use them at <http://gcc.gnu.org/wiki/Visibility>.
-fstrict-volatile-bitfieldsโ okay so use this one if accesses to volatile bit-fields (or other structure fields, though the compiler usually honors those types anyway) should use a single access of the width of the field's type, aligned to 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 asunsigned short(assuming short is 16 bits on those targets, obviously) 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 don't contain any portion of the bit-field, or memory-mapped registers unrelated to the one being updated. ๐ฌ Not it.
In some cases โ like 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's correctly aligned for the target machine. In that case GCC falls back to generating multiple accesses rather than code that will fault or truncate the result at run time. It's giving "we tried, but safety first."
Note: due to restrictions of the C/C++11 memory model, write accesses are not allowed to touch non bit-field members. It's therefore recommended to define all bits of the field's type as bit-field members. Fr fr, do this.
The default value of this option is determined by the application binary interface for the target processor.
-fsync-libcallsโ this option controls whether any out-of-line instance of the__syncfamily of functions may be used to implement the C++11__atomicfamily of functions.
The default value of this option is enabled, so the only useful form of the option is -fno-sync-libcalls. This option is used in the implementation of the libatomic runtime library. That's it, that's the whole thing. ๐ฆ
๐ ๏ธ GCC Developer Options ๐ ๏ธ
Okay so this section? It's describing 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, options that print statistics like memory use and execution time, and options that print information about GCC's configuration โ like where it searches for libraries. You should rarely need to use any of these options for ordinary compilation and linking tasks. This is the backstage pass section, bestie. ๐๏ธโจ
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, a phase letter, and a pass name. The base dump file name is the name of the output file produced by the compiler if explicitly specified and not an executable; otherwise it's 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're 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.
Dumps and callgraphs, let's go ๐
-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 thesumarker is specified, the callgraph is decorated with stack usage information; it's equivalent to-fstack-usage. When thedamarker 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โ-fdump-rtl-btl1and-fdump-rtl-btl2enable dumping after the two branch target load optimization passes.-fdump-rtl-bypassโ dump after jump bypassing and control flow optimizations.-fdump-rtl-combineโ dump after the RTL instruction combination pass.-fdump-rtl-compgotosโ dump after duplicating the computed gotos.-fdump-rtl-ce1-fdump-rtl-ce2-fdump-rtl-ce3โ-fdump-rtl-ce1,-fdump-rtl-ce2, and-fdump-rtl-ce3enable dumping after the three if conversion passes.-fdump-rtl-cprop_hardregโ dump after hard register copy propagation.-fdump-rtl-csaโ dump after combining stack adjustments.-fdump-rtl-cse1-fdump-rtl-cse2โ-fdump-rtl-cse1and-fdump-rtl-cse2enable dumping after the two common subexpression elimination passes.-fdump-rtl-dceโ dump after the standalone dead code elimination passes.-fdump-rtl-dbrโ dump after delayed branch scheduling.-fdump-rtl-dce1-fdump-rtl-dce2โ-fdump-rtl-dce1and-fdump-rtl-dce2enable dumping after the two dead store elimination passes.-fdump-rtl-ehโ dump after finalization of EH handling code.-fdump-rtl-eh_rangesโ dump after conversion of EH handling range regions.-fdump-rtl-expandโ dump after RTL generation.-fdump-rtl-fwprop1-fdump-rtl-fwprop2โ-fdump-rtl-fwprop1and-fdump-rtl-fwprop2enable dumping after the two forward propagation passes.-fdump-rtl-gcse1-fdump-rtl-gcse2โ-fdump-rtl-gcse1and-fdump-rtl-gcse2enable dumping after global common subexpression elimination.-fdump-rtl-init-regsโ dump after the initialization of the registers.-fdump-rtl-initvalsโ dump after the computation of the initial value sets.-fdump-rtl-into_cfglayoutโ dump after converting to cfglayout mode.-fdump-rtl-iraโ dump after iterated register allocation.-fdump-rtl-jumpโ dump after the second jump optimization.-fdump-rtl-loop2โ-fdump-rtl-loop2enables dumping after the rtl loop optimization passes.-fdump-rtl-machโ dump after performing the machine dependent reorganization pass, if that pass exists.-fdump-rtl-mode_swโ dump after removing redundant mode switches.-fdump-rtl-rnregโ dump after register renumbering.-fdump-rtl-outof_cfglayoutโ dump after converting from cfglayout mode.-fdump-rtl-peephole2โ dump after the peephole pass.-fdump-rtl-postreloadโ dump after post-reload optimizations.-fdump-rtl-pro_and_epilogueโ dump after generating the function prologues and epilogues.-fdump-rtl-sched1-fdump-rtl-sched2โ-fdump-rtl-sched1and-fdump-rtl-sched2enable dumping after the basic block scheduling passes.
-fdump-rtl-reeโ dumps everything right after sign/zero extension elimination happens ๐-fdump-rtl-seqabstrโ dumps after common sequence discovery, bestie ๐-fdump-rtl-shortenโ dumps after branch shortening, so you can see those little branches get cute and compact ๐ธ-fdump-rtl-siblingโ dumps after sibling call optimizations ๐-fdump-rtl-split1,-fdump-rtl-split2,-fdump-rtl-split3,-fdump-rtl-split4,-fdump-rtl-split5โ these five enable dumping after five rounds of instruction splitting. five. rounds. the dedication is real ๐ญ-fdump-rtl-smsโ dumps after modulo scheduling. heads up tho: this pass only runs on some architectures, so don't come for me if your dump is empty ๐ซถ-fdump-rtl-stackโ dumps after conversion from GCC's "flat register file" registers to the x87's stack-like registers. this one's x86 variants only, so if you're on literally anything else, nothing happens ๐-fdump-rtl-subreg1,-fdump-rtl-subreg2โ-fdump-rtl-subreg1and-fdump-rtl-subreg2enable 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, glow-up complete ๐-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 they always produce empty files. yes bestie, always. empty. it's giving ghost town ๐ป-da,-fdump-rtl-allโ produce all the dumps listed above. the whole buffet ๐
โจ the little -d letters โจ
-dAโ annotates the assembler output with miscellaneous debugging info ๐-dDโ dumps all macro definitions, at the end of preprocessing, on top of the normal output ๐-dHโ produces a core dump whenever an error occurs. yes fr fr, an actual core dump. dramatic queen behavior but make it on purpose ๐ฅ-dpโ annotates the assembler output with a comment saying which pattern and alternative is used. the length and cost of each instruction get printed too ๐-dPโ dumps the RTL in the assembler output as a comment before each instruction. also turns on-dpannotation, two-for-one ๐ซถ-dxโ just generates RTL for a function instead of compiling it. usually used with-fdump-rtl-expand๐ฑ
๐ฆ more dump options ๐ฆ
-fdump-debugโ dumps debugging information generated during the debug generation phase ๐-fdump-earlydebugโ dumps debugging information generated during the early debug generation phase ๐ค๏ธ-fdump-noaddrโ when doing debugging dumps, suppresses address output. this makes it way more feasible to usediffon debugging dumps for compiler invocations with different compiler binaries and/or different text / bss / data / heap / stack / dso start locations. iykyk ๐-freport-bugโ collects and dumps debug information into a temporary file if an internal compiler error (ICE) occurs. cute little safety net for when things go ๐-fdump-unnumberedโ when doing debugging dumps, suppresses instruction numbers and address output. same energy as above: it makes usingdiffon debugging dumps for compiler invocations with different options way more feasible, especially with and without-gโจ-fdump-unnumbered-linksโ when doing debugging dumps (see the-doption above), suppresses instruction numbers for the links to the previous and next instructions in a sequence ๐
๐ ipa dumps ๐
-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 made by appending a switch-specific suffix to the source file name, and the file gets created in the same directory as the output file. the following dumps are possible:allโ enables all inter-procedural analysis dumps ๐cgraphโ dumps info about call-graph optimization, unused function removal, and inlining decisions ๐ณinlineโ dump after function inlining ๐ซ
also, 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. the receipts, bestie ๐งพ
by default, the dump contains messages about successful optimizations (equivalent to -optimized) together with low-level details about the analysis.
๐ language dumps ๐
-fdump-langโ dumps 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 exactly like 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 info. this option is applicable to C++ only. (yes, Elrond. iconic reference, no notes ๐ง)rawโ dump the raw internal tree data. this option is applicable to C++ only.
๐ the rest of the dump fam ๐
-fdump-passesโ prints on stderr the list of optimization passes that are turned on and off by the current command-line options. the vibe check for your flags ๐-fdump-statistics-optionโ enable and control dumping of pass statistics in a separate file. the file name is made 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, options is 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 since 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โ enable more detailed dumps (not honored by every dump option). also include information from the optimization passes ๐ฌstatsโ enable dumping various statistics about the pass (not honored by every dump option) ๐blocksโ enable showing basic block boundaries (disabled in raw dumps) ๐งฉgraphโ for each of the other indicated dump files (-fdump-rtl-pass), dump a representation of the control flow graph suitable for viewing with GraphViz tofile.passid.pass.dot. each function in the file is pretty-printed as a subgraph, so that GraphViz can render them all in a single plot.
this option currently only works for RTL dumps, and the RTL is always dumped in slim form ๐ธ๏ธ
vopsโ enable showing virtual operands for every statement ๐linenoโ enable showing line numbers for statements ๐ขuidโ enable showing the unique ID ("DECL_UID") for each variable ๐verboseโ enable showing the tree dump for each statement ๐ฃ๏ธehโ enable showing the EH region number holding each statement ๐scevโ enable showing scalar evolution analysis details ๐optimizedโ enable showing optimization information (only available in certain passes) ๐ฅmissedโ enable showing missed optimization information (only available in certain passes) ๐noteโ enable other detailed optimization information (only available in certain passes) ๐allโ turn on all options, exceptraw,slim,verboseandlinenoโ ๏ธoptallโ turn on all optimization options, i.e.,optimized,missed, andnote๐
to figure out what tree dumps are available, or to find the dump for a pass of interest, follow the steps below, bestie ๐ช
- Invoke GCC with
-fdump-passesand in the stderr output look for a code that corresponds to the pass you are 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. ๐ญ
-fopt-info,-fopt-info-options,-fopt-info-options=filenameโ controls optimization dumps from various optimization passes. If the-optionsform is used, options is a list of-separated option keywords to select the dump details and optimizations. bestie this is the whole toolkit ๐
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, no cap โจ
The following options control which kinds of messages should be emitted:
optimizedโ print 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. ๐missedโ print information about missed optimizations. Individual passes control which information to include in the output. the "aw bestie you almost had it" report ๐noteโ print verbose information about optimizations, such as certain transformations, more detailed messages about decisions etc. ๐ฌallโ print detailed optimization information. This includesoptimized,missed, andnote. the whole buffet ๐
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. ๐ง (devs only, 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".
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. one filename only, the rest get ghosted ๐
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. do NOT let it overwrite your receipts ๐ญ
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. order? irrelevant. she ate either way ๐
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, the loop one is just standing there ๐ซถ
-fsave-optimization-recordโ write aSRCFILE.opt-record.json.gzfile 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. fr fr, don't build your whole pipeline on this โ ๏ธ
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. ๐ช
-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. turn the dial up, get more lore ๐
-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. dev tools, not a vibe for everyday users ๐-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 from1.-fdisable-rtl-pass,-fdisable-rtl-pass=range-listโ disable RTL 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 from1. range-list is a comma-separated list of function ranges or assembler names. Each range is a number pair separated by a colon. The range is inclusive in both ends. If the range is trivial, the number pair can be simplified as 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 the pass names can be dumped by using option-fdump-passes.-fdisable-tree-pass,-fdisable-tree-pass=range-listโ disable tree pass pass. See-fdisable-rtlfor the description of option arguments.-fenable-ipa-passโ enable 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 from1.-fenable-rtl-pass,-fenable-rtl-pass=range-listโ enable RTL pass pass. See-fdisable-rtlfor option argument description and examples.-fenable-tree-pass,-fenable-tree-pass=range-listโ enable tree pass pass. See-fdisable-rtlfor the description of option arguments.
Here are some examples showing uses of these options.
# 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โ enable internal consistency checking. The default depends on the compiler configuration.-fchecking=2enables further internal consistency checking that might affect code generation. ๐-frandom-seed=stringโ this option provides a seed that GCC uses in place of random numbers in generating certain symbol names that have to be different in every compiled file. It is also used to place unique stamps in coverage data files and the object files that produce them. You can use the-frandom-seedoption to produce reproducibly identical object files. ๐
The string can either be a number (decimal, octal or hex) or an arbitrary string (in which case it's converted to a number by computing CRC32). same seed, same output, periodt โจ
The string should be different for every file you compile.
-save-tempsโ okay so this one keeps the "temporary" intermediate files forever instead of ghosting them at the end ๐พ. They get named as auxiliary output files, exactly like-dumpbaseand-dumpdirsay. And bestie, when you pair it with-x,-save-tempsis actually smart enough to not overwrite an input source file that has the same extension as an intermediate file ๐ซถ. Wanna grab that intermediate file anyway? Just rename the source file before you run-save-temps. easy.-save-temps=cwdโ literally just-save-temps -dumpdir ./. same energy, one flag โจ-save-temps=objโ this is-save-temps -dumpdir outdir/, where outdir/ is the directory of the output file you named after-o, directory separators and all. No-o? Then-save-temps=objjust acts like-save-temps=cwd. iconic behavior honestly ๐-time[=file]โ reports the CPU time each subprocess ate during the compilation sequence โฑ๏ธ. For C source files that's the compiler proper and the assembler (plus the linker if linking happens).
No output file specified? The output looks like this:
# cc1 0.12 0.01
# as 0.00 0.01
First number on each line = "user time", aka time spent actually running the program itself. Second number = "system time", aka time spent running operating system routines on the program's behalf. Both in seconds, no cap.
Specify an output file and the output gets appended to that named file instead, looking like this:
0.12 0.01 cc1 <options>
0.00 0.01 as <options>
Now "user time" and "system time" come before the program name, and the options passed to the program get shown too, so later you can tell exactly what file was being compiled and with which options ๐
-fdump-final-insns[=file]โ dumps the final internal representation (RTL) to file ๐๏ธ. If you leave the optional argument out (or if file is.), the dump file name is made by appending.gkdto the dump base name โ go check-dumpbasefor that.-fcompare-debug[=opts]โ if no error happens during compilation, it runs the compiler a second time, adding opts and-fcompare-debug-secondto the arguments of that second compilation ๐. It dumps the final internal representation in both compilations and prints an error if they differ. double trouble, but make it diagnostics.
Equal sign omitted? The default -gtoggle is used.
The environment variable GCC_COMPARE_DEBUG, if it's defined, non-empty and nonzero, implicitly enables -fcompare-debug. If GCC_COMPARE_DEBUG is defined to a string starting with a dash, that string is used for opts โ otherwise the default -gtoggle is used.
-fcompare-debug=, with the equal sign but no 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 ๐.
Wanna 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 (not preprocessing, assembly or linking, just so we're clear). Want only a warning instead? Setting GCC_COMPARE_DEBUG to -w%n-fcompare-debug not overridden will do it.
-fcompare-debug-secondโ this option is implicitly passed to the compiler for that second compilation that-fcompare-debugasked for, along with options to silence warnings, and it omits other options that would make the compiler produce output to files or to standard output as a side effect ๐คซ. Dump files and preserved temporary files get renamed to include the extra.gkextension during the second compilation, so they don't overwrite the ones from the first. thoughtful!
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 ๐.
-gtoggleโ turns off generation of debug info if leaving out this option would generate it, or turns it on at level 2 otherwise ๐. Where you put this argument in the command line does not matter โ it takes effect after all other options are processed, and it only does so once, no matter how many times you give it. Mainly intended to be used with-fcompare-debug๐.-fvar-tracking-assignments-toggleโ toggles-fvar-tracking-assignments, in the exact same way-gtoggletoggles-g. matchy matchy โจ-Qโ makes the compiler print out each function name as it's compiled, and print some statistics about each pass when it finishes ๐.-ftime-reportโ makes the compiler print some statistics about the time each pass consumed when it finishes โณ.-ftime-report-detailsโ records the time consumed by infrastructure parts separately for each pass ๐.-fira-verbose=nโ controls the verbosity of the dump file for the integrated register allocator ๐๏ธ. Default value is5. If the value n is greater than or equal to10, the dump output gets sent tostderrusing the same format as n minus10.-flto-reportโ prints a report with internal details on how the link-time optimizer is working ๐. The contents of this report vary from version to version. It's meant to be useful to GCC developers when processing object files in LTO mode (via-flto). Disabled by default, so you gotta ask for it.-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 ๐ซถ.-fprofile-reportโ makes the compiler print some statistics about the consistency of the (estimated) profile and the effect of individual passes ๐.-fstack-usageโ makes the compiler output stack usage info for the program, per-function ๐ฅ. The dump filename is made by appending.suto the auxname. auxname comes from the name of the output file if it was explicitly specified and it's not an executable โ otherwise it's the basename of the source file. Each 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 the function manipulates the stack statically: a fixed number of bytes get allocated for the frame on function entry and released on function exit, and no stack adjustments are otherwise made inside the function. The second field is that fixed number of bytes.
The qualifier dynamic means the function manipulates the stack dynamically: on top of the static allocation described above, stack adjustments happen in the body of the function, for example to push/pop arguments around function calls. If the qualifier bounded is also there, the amount of those adjustments is bounded at compile time and the second field is an upper bound on the total amount of stack the function uses. If bounded is not there, the amount of those adjustments is not bounded at compile time and the second field only represents the bounded part ๐ญ.
-fstatsโ emits statistics about front-end processing at the end of the compilation ๐. Only supported by the C++ front end, and the info is generally only useful to the G++ development team. iykyk.-fdbg-cnt-listโ prints the name and the counter upper bound for all debug counters ๐ข.-fdbg-cnt=counter-value-listโ sets the internal debug counter lower and upper bound. counter-value-list is a comma-separated list of
name:lower_bound1-upper_bound1 [:lower_bound2-upper_bound2...]
tuples, which sets the name of the counter and a list of closed intervals. The lower_bound is 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 the second, third, fourth, tenth and eleventh invocation ๐ฏ. And for dbg_cnt(tail_call), true is returned for the first 10 invocations.
-print-file-name=libraryโ prints the full absolute name of the library file library that would be used when linking โ and does nothing else ๐ . With this option GCC doesn't compile or link anything; it just prints the file name.-print-multi-directoryโ prints the directory name corresponding to the multilib selected by any other switches present in the command line ๐. That directory is supposed to exist inGCC_EXEC_PREFIX.-print-multi-libโ prints the mapping from multilib directory names to the compiler switches that enable them ๐บ๏ธ. The directory name is separated from the switches by;, and each switch starts with an@instead of the-, with no spaces between multiple switches. This is supposed to ease shell processing, bestie.-print-multi-os-directoryโ prints 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โ prints 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 ascppinstead ๐.-print-libgcc-file-nameโ same as-print-file-name=libgcc.a.
Super 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โ prints the name of the configured installation directory and a list of program and library directoriesgccsearches โ and doesn'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 /.
-print-sysrootโ prints the target sysroot directory that gets used during compilation. ๐ It's the sysroot you specified either at configure time or with the--sysrootoption, possibly with an extra suffix that depends on your compilation options. If no target sysroot is specified, bestie, this option prints literally nothing. Silence. Crickets. ๐ฆ-print-sysroot-headers-suffixโ prints the suffix that gets added to the target sysroot when it's searching for headers, or it throws an error if the compiler wasn't configured with such a suffix โ and it does nothing else. Just that one job. ๐-dumpmachineโ prints the compiler's target machine (likei686-pc-linux-gnu) โ and don't do anything else. That's the whole assignment. โจ-dumpversionโ prints 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). So like, it's giving "how much detail did your build config feel like today". ๐-dumpfullversionโ prints 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 half measures, periodt. ๐-dumpspecsโ prints the compiler's built-in specs โ and don't do anything else. (This one gets used when GCC itself is being built, iykyk.) ๐ง
## Machine-Dependent Options ๐ป
Every target machine GCC supports can have its own little set of options โ like, so you can compile for a specific processor variant or ABI, or control the optimizations that are special to that machine. By convention, machine-specific option names all start with -m. ๐ท๏ธ
Some configurations of the compiler also support extra target-specific options, usually so it plays nice 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. The permissible values areilp32for a SysV-like data model whereint,long intand pointers are 32 bits, andlp64for a 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. Don't mix, bestie, it will NOT end well. ๐ญ
-mbig-endianโ generate big-endian code. This is the default when GCC is configured for anaarch64_be-*-*target.-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 won't impose any restrictions on the assembler. ๐-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. So smol. ๐-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. โจ-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. So don't even try it, it's giving doomed crossover episode. ๐-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 a canary at guard. The 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, because this is entirely for use within the Linux kernel. ๐ง
-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.-mtls-size=sizeโ specify bit size of immediate TLS offsets. Valid values are12,24,32,48. This option requires binutils 2.26 or newer. โ ๏ธ-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. Little band-aid for a hardware oopsie ๐ฉน-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. Fast and loose, bestie. ๐ฅ-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โ enable or disable generation of additional code to track speculative execution through conditional branches. The tracking state can then be used by the compiler when expanding calls to__builtin_speculation_safe_copyto permit a more efficient code sequence to be generated. Very security-core of you. ๐ต๏ธ-moutline-atomics,-mno-outline-atomicsโ enable or disable calls to out-of-line helpers to implement atomic operations. These helpers will, at runtime, determine if the LSE instructions from ARMv8.1-A can be used; if not, they will use the load/store-exclusive instructions that are present in the base ARMv8.0 ISA.
This option is only applicable when compiling for the base ARMv8.0 instruction set. If using a later revision, e.g. -march=armv8.1-a or -march=armv8-a+lse, the ARMv8.1-Atomics instructions will be used directly. The same applies when using -mcpu= when the selected cpu supports the lse feature. This option is on by default. โจ
-march=nameโ specify the name of the target architecture and, optionally, one or more feature modifiers. This option has the form-march=arch{+[no]feature}*.
The table below summarizes the permissible values for arch and the features that they enable by default:
armv8-a: Armv8-A : Includes by default+fp,+simdarmv8.1-a: Armv8.1-A :armv8-a,+crc,+lse,+rdmaarmv8.2-a: Armv8.2-A :armv8.1-aarmv8.3-a: Armv8.3-A :armv8.2-a,+pautharmv8.4-a: Armv8.4-A :armv8.3-a,+flagm,+fp16fml,+dotprodarmv8.5-a: Armv8.5-A :armv8.4-a,+sb,+ssbs,+predresarmv8.6-a: Armv8.6-A :armv8.5-a,+bf16,+i8mmarmv8-r: Armv8-R :armv8-r
The value native is available on native AArch64 GNU/Linux and causes the compiler to pick the architecture of the host system. This option has no effect if the compiler is unable to recognize the architecture of the host system,
The permissible values for feature are listed in the sub-section on aarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used. ๐
GCC uses name to determine what kind of instructions it can emit when generating assembly code. If -march is specified without either of -mtune or -mcpu also being specified, the code is tuned to perform well across a range of target processors implementing the target architecture.
-mtune=nameโ specify the name of the target processor for which GCC should tune the performance of the code. Permissible values for this option 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,ampere1,ampere1a,cobalt-100andnative.
okay so the big.LITTLE moment ๐
โ 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 are all like "bestie, tune me for a big.LITTLE system" โจ
And the value neoverse-512tvb is the iconic generalist ๐ โ it says tune for Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits per cycle. In other words, it's telling GCC: tune for Neoverse cores that can execute 4 128-bit Advanced SIMD arithmetic instructions a cycle, and that can execute an equivalent number of SVE arithmetic instructions per cycle (2 for 256-bit SVE, 4 for 128-bit SVE). Not me being more general than tuning for a specific core like Neoverse V1 but more specific than the default tuning described below ๐ญ
Plus, on native AArch64 GNU/Linux systems, the value native tunes performance to the host system. Real talk though: this option does nothing if the compiler can't recognize the processor of the host system ๐
Where none of -mtune=, -mcpu= or -march= are specified, the code gets tuned to perform well across a range of target processors ๐
Important: this option cannot be suffixed by feature modifiers. Periodt.
-mcpu=nameโ tells GCC the name of the target processor, optionally suffixed by one or more feature modifiers ๐ซถ The form is-mcpu=cpu{+[no]feature}*, where the permissible values forcpuare the same as those available for-mtune. The permissible values forfeatureare documented in the sub-section onaarch64-feature-modifiers,,-march and -mcpu Feature Modifiers. Where conflicting feature modifiers are specified, the right-most feature is used ๐
GCC uses name to determine what kind of instructions it can emit when generating assembly code (as if by -march) and to determine the target processor for which to tune for performance (as if by -mtune). Where this option is used in conjunction with -march or -mtune, those options take precedence over the appropriate part of this option. the way that it's two options in a trench coatโฆ
-mcpu=neoverse-512tvb is special ๐ซ โ it does not refer to a specific core, but instead refers to all Neoverse cores that (a) implement SVE and (b) have a total vector bandwidth of 512 bits a cycle. Unless overridden by -march, -mcpu=neoverse-512tvb generates code that can run on a Neoverse V1 core, since Neoverse V1 is the first Neoverse core with these properties. And unless overridden by -mtune, -mcpu=neoverse-512tvb tunes code in the same way as for -mtune=neoverse-512tvb โจ
-moverride=stringโ overrides tuning decisions made by the back-end in response to a-mtune=switch ๐๏ธ The syntax, semantics, and accepted values forstringin this option are not guaranteed to be consistent across releases ๐ญ
This option is only intended to be useful when developing GCC. compiler-dev main character energy only, bestie
-mverbose-cost-dumpโ enables verbose cost model dumping in the debug dump files ๐ธ This option is provided for use in debugging the compiler.-mpc-relative-literal-loads,-mno-pc-relative-literal-loadsโ enable or disable PC-relative literal loads ๐ With this option, literal pools are accessed using a single instruction and emitted after each function. This limits the maximum size of functions to1MB. This is enabled by default for-mcmodel=tiny.-msign-return-address=scopeโ picks the function scope on which return address signing gets applied ๐ Permissible values arenone, which disables return address signing;non-leaf, which enables pointer signing for functions which are not leaf functions; andall, which enables pointer signing for all functions. The default value isnone.
heads up: this option has been deprecated by -mbranch-protection. it's giving legacy ๐
-mbranch-protection=none|standard|pac-ret[+leaf+b-key]|btiโ selects the branch protection features to use ๐ก๏ธnoneis the default and turns off all types of branch protection.standardturns on all types of branch protection features. If a feature has additional tuning options, thenstandardsets it to its standard level.pac-ret[+leaf]turns on return address signing to 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 argumentleafcan be used to extend the signing to include leaf functions. The optional argumentb-keycan be used to sign the functions with the B-key instead of the A-key.btiturns on branch target identification mechanism โจ-mharden-sls=optsโ enables compiler hardening against straight line speculation (SLS) ๐ฅoptsis a comma-separated list of the following options:retbrblr
In addition, -mharden-sls=all enables all SLS hardening, while -mharden-sls=none disables all SLS hardening ๐
-msve-vector-bits=bitsโ specifies the number of bits in an SVE vector register ๐ฆ This option only has an effect when SVE is enabled.
GCC supports two forms of SVE code generation: "vector-length agnostic" output that works with any size of vector register, and "vector-length specific" output that allows GCC to make assumptions about the vector length when it is 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 behavior of these values may change in future releases, and no value except scalable should be relied on for producing code that is 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 used with -march and -mcpu can be any of the following, and their inverses nofeature ๐
crcโ enable CRC extension. This is on by default for-march=armv8.1-a.cryptoโ enable 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 options-marchand-mcpu.simdโ enable Advanced SIMD instructions. This also enables floating-point instructions. This is on by default for all possible values for 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โ enable FP16 extension. This also enables floating-point instructions.fp16fmlโ enable FP16 fmla extension. This also enables FP16 extensions and floating-point instructions. This option is enabled by default for-march=armv8.4-a. Use of this option with architectures prior to Armv8.2-A is not supported.rcpcโ enable the RcPc extension. This does not change code generation from GCC, but is passed on to the assembler, enabling inline asm statements to use instructions from the RcPc extension.dotprodโ enable the Dot Product extension. This also enables Advanced SIMD instructions.aesโ enable the Armv8-a aes and pmull crypto extension. This also enables Advanced SIMD instructions.sha2โ enable the Armv8-a sha2 crypto extension. This also enables Advanced SIMD instructions.sha3โ enable the sha512 and sha3 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.sm4โ enable the sm3 and sm4 crypto extension. This also enables Advanced SIMD instructions. Use of this option with architectures prior to Armv8.2-A is not supported.profileโ enable the Statistical Profiling extension. This option is only to enable the extension at the assembler level and does not affect code generation.rngโ enable the Armv8.5-a Random Number instructions. This option is only to enable the extension at the assembler level and does not affect code generation.memtagโ enable the Armv8.5-a Memory Tagging Extensions. Use of this option with architectures prior to Armv8.5-A is not supported.sbโ enable the Armv8-a Speculation Barrier instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.ssbsโ enable the Armv8-a Speculative Store Bypass Safe instruction. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.predresโ enable the Armv8-a Execution and Data Prediction Restriction instructions. This option is only to enable the extension at the assembler level and does not affect code generation. This option is enabled by default for-march=armv8.5-a.sve2โ enable the Armv8-a Scalable Vector Extension 2. This also enables SVE instructions.sve2-bitpermโ enable SVE2 bitperm instructions. This also enables SVE2 instructions.sve2-sm4โ enable SVE2 sm4 instructions. This also enables SVE2 instructions.sve2-aesโ enable SVE2 aes instructions. This also enables SVE2 instructions.sve2-sha3โ enable SVE2 sha3 instructions. This also enables SVE2 instructions.tmeโ enable the Transactional Memory Extension.i8mmโ enable 8-bit Integer Matrix Multiply instructions. This also enables Advanced SIMD and floating-point instructions. This option is enabled by default for-march=armv8.6-a. Use of this option with architectures prior to Armv8.2-A is not supported.f32mmโ enable 32-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.f64mmโ enable 64-bit Floating point Matrix Multiply instructions. This also enables SVE instructions. Use of this option with architectures prior to Armv8.2-A is not supported.
okay that was a LOT of modifiers but we ate and left no crumbs ๐ and bestie we are SO not done yet, keep scrolling โจ
bf16โ turns on brain half-precision floating-point instructions ๐ง โจ and it also switches on Advanced SIMD and floating-point instructions while it's at it. This one is enabled by default for-march=armv8.6-a. Using it with architectures from before Armv8.2-A is not supported ๐ซ.flagmโ enables the Flag Manipulation instructions Extension ๐pauthโ enables the Pointer Authentication Extension ๐
Okay so the tea on the feature deps โ: feature crypto implies aes, sha2, and simd, which implies fp. And conversely, nofp implies nosimd, which implies nocrypto, noaes and nosha2. Chain reaction, bestie ๐
.
๐ธ Adapteva Epiphany Options ๐ธ
These -m options are defined for Adapteva Epiphany, and yes we're going through every single one:
-mhalf-reg-fileโ don't allocate any register in the ranger32...r63๐ซ. That's what lets your code run on hardware variants that simply lack these registers.-mprefer-short-insn-regsโ preferentially allocate registers that allow short instruction generation โจ. Fair warning though: this can increase instruction count, so it may either reduce or increase overall code size. It's giving chaos, honestly.-mbranch-cost=numโ set the cost of branches to roughly num "simple" instructions. 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 ๐-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 ๐. Note also 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 of 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 ๐ญ.-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, no cap:
-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โ compile binaries suitable for devices with the SRAM-ECC feature enabled, disabled, or either mode. This feature can be enabled per-process on some devices. The compiled code must match the device mode. The default isany, for devices that support it.-mstack-size=bytesโ specify how many bytes of stack space will be requested for each GPU thread (wave-front). Beware that there may be many threads and limited memory available ๐. The size of the stack allocation may also have an impact on run-time performance. The default is 32KB when using OpenACC or OpenMP, and 1MB otherwise.-mxnackโ compile binaries suitable for devices with the XNACK feature enabled. Some devices always require XNACK and some allow the user to configure XNACK. The compiled code must match the device mode. The default is-mno-xnack. At present this option is a placeholder for support that is not yet implemented ๐ง.
๐ ARC Options ๐
The following options control the architecture variant for which code is being compiled:
-mbarrel-shifterโ generate instructions supported by barrel shifter. This is the default unless-mcpu=ARC601or-mcpu=ARCEMis in effect.-mjli-alwaysโ force to call a function usingjli_sinstruction. This option is valid only for ARCv2 architecture.-mcpu=cpuโ set architecture type, register usage, and instruction scheduling parameters for cpu. There are also shortcut alias options available for backward compatibility and convenience. Supported values for cpu are: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 withnorminstructions enabled.arc600_mul32x16โ compile for ARC 600 CPU withnormand 32x16-bit multiply instructions enabled.arc600_mul64โ compile for ARC 600 CPU withnormandmul64-family instructions enabled.arc601_normโ compile for ARC 601 CPU withnorminstructions enabled.arc601_mul32x16โ compile for ARC 601 CPU withnormand 32x16-bit multiply instructions enabled.arc601_mul64โ compile for ARC 601 CPU withnormandmul64-family instructions enabled.nps400โ compile for ARC 700 on NPS400 chip.em_miniโ compile for ARC EM minimalist configuration featuring 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โ disablelrandsrinstructions from using FPX extension aux registers.-meaโ generate extended arithmetic instructions. Currently onlydivaw,adds,subs, andsat16are supported. Only valid for-mcpu=ARC700.-mno-mpyโ bestie do not generate"mpy"-family instructions for ARC700. This option is deprecated. ๐-mmul32x16โ generates 32x16-bit multiply and multiply-accumulate instructions. slay โจ-mmul64โ generates"mul64"and"mulu64"instructions. only valid for-mcpu=ARC600, no exceptions ๐-mnormโ generates"norm"instructions. this is the default if-mcpu=ARC700is in effect, so it's giving main character energy by default ๐-mspfp,-mspfp-compactโ generates single-precision FPX instructions, tuned for the compact implementation. โจ-mspfp-fastโ generates 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, so don't try it anywhere else ๐ซถ-msoft-floatโ okay so this option is ignored; it's provided for compatibility purposes only. software floating-point code is emitted by default, and this default can overridden by FPX options:-mspfp,-mspfp-compact, or-mspfp-fastfor single precision, and-mdpfp,-mdpfp-compact, or-mdpfp-fastfor double precision. literally just there for the vibes ๐-mswapโ generates"swap"instructions. ๐ฆ-matomicโ this 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โ enables"div"and"rem"instructions for ARCv2 cores. ๐ช-mcode-densityโ enables code density instructions for ARC EM. this option is on by default for ARC HS. ๐-mll64โ enables double load/store operations for ARC HS cores. โจ- *
-mtp-regno=regno* โ specify 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 numeric value for multo.wlh1is the default value. the recognized values are:0,noneโ no multiplier available. ๐1,wโ 16x16 multiplier, fully pipelined. the following instructions are enabled:"mpyw"and"mpyuw".2,wlh1โ 32x32 multiplier, fully pipelined (1 stage). the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".3,wlh2โ 32x32 multiplier, fully pipelined (2 stages). the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".4,wlh3โ two 16x16 multipliers, blocking, sequential. the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".5,wlh4โ one 16x16 multiplier, blocking, sequential. the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_s".6,wlh5โ one 32x4 multiplier, blocking, sequential. the following instructions are additionally enabled:"mpy","mpyu","mpym","mpymu", and"mpy_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 for fpu are: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-purposes registers that the processor automatically saves/restores on interrupt entry and exit. register-range is specified as two registers separated by a dash. the register range always starts with"r0", the upper limit is"fp"register. blink and lp_count are optional. this option is only valid for ARC EM and ARC HS cores. ๐ - *
-mrgf-banked-regs=number* โ specifies the number of registers replicated in second register bank on entry to fast interrupt. fast interrupts are interrupts with the highest priority level P0. these interrupts save only PC and STATUS32 registers to avoid memory transactions during interrupt entry and exit sequences. use this option when you are using fast interrupts in an ARC V2 family processor. permitted values are4,8,16, and32. ๐ - *
-mlpc-width=width* โ specify the width of the"lp_count"register. valid values for width are8,16,20,24,28and32bits. the default width is fixed to 32 bits. if the width is less than 32, the compiler does not attempt to transform loops in your program to use the zero-delay loop mechanism unless it is known that the"lp_count"register can hold the required loop-counter value. depending on the width specified, the compiler and run-time library might continue to use the loop mechanism for various needs. this option defines macro"__ARC_LPC_WIDTH__"with the value of width. โจ -mrf16โ this option instructs the compiler to generate code for a 16-entry register file. this option defines the"__ARC_RF16__"preprocessor macro. ๐-mbranch-indexโ enable use of"bi"or"bih"instructions to implement jump tables. ๐ฅ
the following options are passed through to the assembler, and also define preprocessor macro symbols. ๐ ๏ธ
-mdsp-packaโ passed down to the assembler to enable the DSP Pack A extensions. also sets the preprocessor symbol"__Xdsp_packa". 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 is annotated: ๐
-misizeโ annotate assembler instructions with estimated addresses. ๐-mannotate-alignโ explain what alignment considerations lead to the decision to make an instruction short or long. ๐
the following options are passed through to the linker: ๐
-marclinuxโ passed through to the linker, to specify use of the"arclinux"emulation. this option is enabled by default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is not requested. โจ-marclinux_profโ passed through to the linker, to specify use of the"arclinux_prof"emulation. this option is enabled by default in tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets when profiling is requested. ๐
the following options control the semantics of generated code: ๐
-mlong-callsโ generate calls as register indirect calls, thus providing access to the full 32-bit address range. ๐-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, to allow use of the 25-bit range, rather than the 21-bit range with conditional branch-and-link. this is the default for tool chains built for"arc-linux-uclibc"and"arceb-linux-uclibc"targets. ๐-G numโ bestie, this one says: if some externally-visible data is no bigger than num bytes, plop its definition in a small data section. The default num is4for any ARC config, or8when we've got double load/store operations. โจ-mno-sdataโ do not generate sdata references. This is the default for toolchains built forarc-linux-uclibcandarceb-linux-uclibctargets.-mvolatile-cacheโ use ordinarily cached memory accesses for volatile references. This is the default, no cap.-mno-volatile-cacheโ enable cache bypass for volatile references.
The following options fine tune code generation โ yes they really said "fine tune", we're in the โจartisanalโจ zone now:
-malign-callโ do alignment optimizations for call instructions.-mauto-modify-regโ enable the use of pre/post modify with register displacement.-mbbit-peepholeโ enable bbit peephole2.-mno-brccโ this one 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. So don't come for it about the combiner, it said what it said. ๐-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 is 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. โจ noted.
-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. ๐ญ lowkey a trap.-mlraโ enable Local Register Allocation. This is still experimental for ARC, so by default the compiler uses standard reload (i.e.-mno-lra). Experimental, bestie, proceed accordingly.-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 call to a special function inlibgcc; this is referred to as a millicode call. As these calls can pose performance issues, and/or cause linking issues when linking in a nonstandard way, this option is provided to turn on or off millicode call generation.-mcode-density-frameโ this option enable the compiler to emitenterandleaveinstructions. These instructions are only valid for CPUs with code-density feature. (Yes, the original says "enable", we're quoting the vibe, not the grammar. ๐)-mmixed-codeโ tweak register allocation to help 16-bit instruction generation. This generally has the effect of decreasing the average instruction size while increasing the instruction count. Trade-offs, babes.-mq-classโ Ths option is deprecated. Enable q instruction alternatives. This is the default for-Os. (The typo is theirs, and honestly? iconic.)-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โ set probability threshold for unaligning branches. When tuning for ARC700 and optimizing for speed, branches without filled delay slot are preferably emitted unaligned and long, unless profiling indicates that the probability for the branch to be taken is below probability. The default is(REG_BR_PROB_BASE/2), i.e.5000.
The following options are maintained for backward compatibility, but are now deprecated and will be removed in a future release. Gather round, this is the retirement home section ๐ซถ:
-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 build arceb-elf32 and arceb-linux-uclibc targets, 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 build arc-elf32 and arc-linux-uclibc targets, 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โ Replaced by-mdsp-packa.-mEAโ Replaced by-mea.-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โ Valuesarc600,arc601,arc700andarc700-xmacfor cpu are replaced byARC600,ARC601,ARC700andARC700-xmacrespectively. (Yes, lowercase girlies, your time is up. ๐)-multcost=numโ Replaced by-mmultcost.
๐ ARM Options ๐
These -m options are defined for the ARM port. New port, new energy, let's go ๐ฆ:
-mabi=nameโ generate code for the specified ABI. Permissible values are:apcs-gnu,atpcs,aapcs,aapcs-linuxandiwmmxt.-mapcs-frameโ generate a stack frame that is compliant with the ARM Procedure Call Standard for all functions, even if this is not strictly necessary for correct execution of the code. Specifying-fomit-frame-pointerwith this option causes the stack frames not to be generated for leaf functions. The default is-mno-apcs-frame. This option is deprecated.-mapcsโ this is a synonym for-mapcs-frameand is deprecated.-mthumb-interworkโ generate code that supports calling between the ARM and Thumb instruction sets. Without this option, on pre-v5 architectures, the two instruction sets cannot be reliably used inside one program. The default is-mno-thumb-interwork, since slightly larger code is generated when-mthumb-interworkis specified. In AAPCS configurations this option is meaningless.-mno-sched-prologโ prevent the reordering of instructions in the function prologue, or the merging of those instruction with the instructions in the function's body. This means that all functions start with a recognizable set of instructions (or in fact one of a choice from a small set of different function prologues), and this information can be used to locate the start of functions 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.
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. Fr fr, do not mix them, it will not end cute. ๐ญ
-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. Compiler said "not my problem" about 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 linking a big-endian image select between BE8 and BE32 formats. The option has no effect for little-endian images and is ignored. The default is dependent on the selected target architecture. For ARMv6 and later architectures the default is BE8, for older architectures the default is BE32. BE32 format has been deprecated by ARM. ๐
-march=name[+extension...]โ this specifies the name of the target ARM architecture. GCC uses this name to determine what kind of instructions it can emit when generating assembly code. This option can be used in conjunction with or instead of the-mcpu=option. โจ
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, armv7-r, armv8-r, armv6-m, armv6s-m, armv7-m, armv7e-m, armv8-m.base, armv8-m.main, armv8.1-m.main, iwmmxt and iwmmxt2.
Also โ and bestie, listen, this one's on thin ice ๐ง โ these next architectures are recognized, but they don't have Thumb execution state support, and support for them is deprecated: armv4.
โจ extensions, aka the glow-up add-ons ๐
Okay so a ton of these architectures support extensions. You slap one on by appending +extension to the architecture name. Extension options get processed in order, and the capabilities just accumulate โ it's giving stacking buffs in a video game, fr fr.
An extension will also switch on any base extensions it depends on. Like, the +crypto extension will always enable the +simd extension. It's a package deal, no solo acts here.
The one exception to this whole additive situation is extensions prefixed with +no...: โ those ones disable the specified option and any other extensions that might depend on that extension being present. Not me hitting the off switch on your whole dependency tree ๐ญ
So for example:
-march=armv7-a+simd+nofp+vfpv4
is equivalent to writing
-march=armv7-a+vfpv4
because the +simd option is entirely disabled by the +nofp option that follows it. Order matters, bestie. It's a whole timeline situation.
Most extension names are generically named, but what they actually do depends on the architecture you apply them to. Case in point: the +simd option can be applied to both armv7-a and armv8-a, 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 era, main character energy ๐
The table below lists the supported extensions for each architecture. Architectures not mentioned do not support any extensions. Periodt.
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. Heads up: 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 (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 (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.+nofpโ disable the floating-point, Advanced SIMD and cryptographic instructions.+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
+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, plus the Dot Product extension. two for one, we love to see it ๐+cryptoโ the cryptographic instructions โจ and bestie, it also turns on the Advanced SIMD and floating-point instructions and the Dot Product extension. bundle deal, no cap.+nocryptoโ disable the cryptographic extension. gone. bye ๐+nofpโ disable the floating-point, Advanced SIMD and cryptographic instructions. like, all of it ๐ซถ+i8mmโ 8-bit Integer Matrix Multiply instructions. this one also enables the Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. also enables the Advanced SIMD and floating-point instructions. ๐ง
armv8.6-aโ okay so here's the whole menu for this one ๐+fp16โ the half-precision floating-point data processing instructions. this also enables the Advanced SIMD and floating-point instructions, the Dot Product extension, and the half-precision floating-pointfmlaextension. it's giving combo meal ๐+simdโ the ARMv8.3-A Advanced SIMD and floating-point instructions, plus the Dot Product extension.+cryptoโ the cryptographic instructions. also enables the Advanced SIMD and floating-point instructions and 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. also enables the Advanced SIMD and floating-point instructions.+bf16โ Brain half-precision floating-point instructions. also enables the Advanced SIMD and floating-point instructions.
armv7-rโ the roster for this one ๐ธ+fp.spโ the single-precision VFPv3 floating-point instructions. the extension+vfpv3xdcan be used as an alias for this one โจ+fpโ the VFPv3 floating-point instructions with 16 double-precision registers. the extension+vfpv3-d16can be used as an alias for this one.+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โ the lil set ๐+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โ here's what you can toggle ๐+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. pick your coprocessor, bestie ๐
armv8-m.mainโ same energy, slightly different toggles โจ+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โ the last architecture menu, we made it ๐+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. ngl, sometimes it just doesn't know ๐ญ
-mtune=nameโ this one names the target ARM processor GCC should tune the performance of the code for. for some ARM implementations you can get better performance by using it ๐ the permissible names are:
arm7tdmi, arm7tdmi-s, arm710t, arm720t, arm740t, strongarm, strongarm110,
strongarm1100, 0strongarm1110, 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, ares,
cortex-r4, cortex-r4f, cortex-r5, cortex-r7, cortex-r8, cortex-r52,
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.
additionally, this option can specify that GCC should tune the performance of the code for a big.LITTLE system. the 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 specifies that GCC should tune the performance for a blend of processors within architecture arch. the aim is to generate code that run well on the current most popular processors, balancing between optimizations that benefit some CPUs in the range and avoiding performance pitfalls of other CPUs. the effects of this option may change in future GCC versions as CPU models come and go. ๐ฆ
-mtune permits the same extension options as -mcpu, but the extension options do not affect the tuning of the generated code.
-mtune=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. ๐
-mcpu=name[+extension...]โ this specifies the name of the target ARM processor. GCC uses this name to derive the name of 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). where this option is used alongside-marchor-mtune, those options take precedence over the appropriate part of this one. periodt.
many of the supported CPUs implement optional architectural extensions. where that's the case, the architectural extensions are normally enabled by default. if implementations that lack the extension exist, you can use the extension syntax to disable those extensions that have been omitted. for floating-point and Advanced SIMD (Neon) instructions, the settings of -mfloat-abi and -mfpu must also 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. iconic behaviour honestly ๐
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. that's a long list bestie, read it twice ๐ญ+nofp.dpโ disables the double-precision component of the floating-point instructions oncortex-r5,cortex-r7,cortex-r8,cortex-r52andcortex-m7.+nosimdโ disables the SIMD (but not floating-point) instructions ongeneric-armv7-a,cortex-a5,cortex-a7andcortex-a9.
+cryptoโ turns on the crypto instructions, and it works forcortex-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. that's the whole list bestie, don't @ me ๐
Also, the generic-armv7-a pseudo target is lowkey special: it defaults to VFPv3 with 16 double-precision registers, and it supports these 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 literally the same as the extensions to -march=armv7-a, so no new lore to learn ๐ซถ
You can also do -mcpu=generic-arch, which is permissible and equals -march=arch -mtune=generic-arch. Peep -mtune for more deets.
And -mcpu=native? That makes the compiler auto-detect the CPU of the build computer. As of rn this feature is only supported on GNU/Linux, and not all architectures are recognized. If the auto-detect flops, the option has no effect. it's giving "we tried" ๐ญ
โจ -mfpu=name โจ
This one specifies what floating-point hardware (or hardware emulation) is available on the target. The 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-armv8 and crypto-neon-fp-armv8. Note that neon is an alias for neon-vfpv3 and vfp is an alias for vfpv2. girlboss shorthand, we love to see it โจ
The setting auto is the default and it's special โ it makes the compiler pick the floating-point and Advanced SIMD instructions based on the settings of -mcpu and -march.
Real talk: if the selected floating-point hardware includes the NEON extension (e.g.-mfpu=neon), floating-point operations are not generated by GCC's auto-vectorization pass unless-funsafe-math-optimizationsis 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. precision loss? not the vibe ๐
You can also set the fpu name at function level by using the target("fpu=") function attributes or pragmas. per-function slay ๐
โจ -mfp16-format=name โจ
Specify the format of the __fp16 half-precision floating-point type. Permissible names are none, ieee, and alternative; the default is none, in which case the __fp16 type is not defined. no type for you ๐
โจ -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 are 8, 32 and 64. The default value varies for different toolchains. For the COFF targeted toolchain the default value is 8. A value of 64 is 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. messy, honestly ๐ซ
This option is deprecated. โ ๏ธ
โจ -mabort-on-noreturn โจ
Generate a call to the function abort at the end of a noreturn function. It gets executed if the function tries to return. like, you said you weren't gonna return bestie, what happened ๐ญ
โจ -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. exceptions on exceptions, the lore runs deep ๐
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. pointers stay unbothered fr fr
โจ -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. that's on runtime, not us ๐ซก
โจ -mpic-register=reg โจ
Specify the register to be used for PIC addressing. For standard PIC base case, the default is any suitable register determined by the compiler. For single PIC base case, the default is R9 if the target is EABI based or stack-checking is enabled, otherwise the default is R10. defaults doing defaults things ๐
โจ -mpic-data-is-text-relative โจ
Assume that the displacement between the text and data segments is fixed at static link time. This permits using PC-relative addressing operations to access data known to be in the data segment. For non-VxWorks RTP targets, this option is enabled by default. When disabled on such targets, it will enable -msingle-pic-base by default. cascade behavior, iconic โจ
โจ -mpoke-function-name โจ
Write the name of each function into the text section, directly preceding the function prologue. The generated code is similar to 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
When performing a stack backtrace, code can inspect 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 that there is a function name embedded immediately preceding this location and has length ((pc[-3]) & 0xff000000). bit math girlies rise ๐ง
โจ -mthumb โจ
โจ -marm โจ
Select between generating code that executes in ARM and Thumb states. The default for most configurations is to generate code that executes in ARM state, but the default can be changed by configuring GCC with the --with-mode=state configure option.
You can also override the ARM and Thumb mode for each function by using the target("thumb") and target("arm") function attributes or pragmas. per-function mood swings, valid ๐ฆ
โจ -mflip-thumb โจ
Switch ARM/Thumb modes on alternating functions. This option is provided for regression testing of mixed Thumb/ARM code generation, and is not intended for ordinary use in compiling code. testing-only bestie, don't ship it โ ๏ธ
โจ -mtpcs-frame โจ
Generate a stack frame that is compliant with the Thumb Procedure Call Standard for all non-leaf functions. (A leaf function is one that does not call any other functions.) The default is -mno-tpcs-frame. lone-wolf functions get no special frame treatment ๐
โจ -mtpcs-leaf-frame โจ
Generate a stack frame that is compliant with the Thumb Procedure Call Standard for all leaf functions. (A leaf function is one that does not call any other functions.) The default is -mno-apcs-leaf-frame. yes, the default really is spelled with apcs there, copy it exactly, no cap ๐
โจ -mcallee-super-interworking โจ
Gives all externally visible functions in the file being compiled an ARM instruction set header which switches to Thumb mode before executing the rest of the function. This allows these functions to be called from non-interworking code. This option is not valid in AAPCS configurations because interworking is enabled by default. already enabled? then this is giving redundant energy ๐
โจ -mcaller-super-interworking โจ
Allows calls via function pointers (including virtual functions) to execute correctly regardless of whether the target code has been compiled for interworking or not. There is a small overhead in the cost of executing a function pointer if this option is enabled. This option is not valid in AAPCS configurations because interworking is enabled by default. small cost, big correctness, the tradeoff of all time โ๏ธ
โจ -mtp=name โจ
Specify the access model for the thread local storage pointer. The valid models are soft, which generates calls to __aeabi_read_tp, cp15, which fetches the thread pointer from cp15 directly (supported in the arm6k architecture), and auto, which uses the best available method for the selected processor. The default setting is auto. auto stays winning ๐
โจ -mtls-dialect=dialect โจ
Specify the dialect to use for accessing thread local storage. Two dialects are supported---gnu and gnu2. The gnu dialect selects the original GNU scheme for supporting local and global dynamic TLS models. The gnu2 dialect selects the GNU descriptor scheme, which provides better performance for shared libraries. The GNU descriptor scheme is compatible with the original scheme, but 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. gnu2 is the glow-up, but it needs the whole squad to update first ๐
โจ -mword-relocations โจ
Only generate 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 -fpic or -fPIC is specified. This option conflicts with -mslow-flash-data. pick a lane bestie, they cannot coexist ๐
โจ -mfix-cortex-m3-ldrd โจ
Some Cortex-M3 cores can cause data corruption when ldrd instructions with overlapping destination and base registers are used. This option avoids generating these instructions. This option is enabled by default when -mcpu=cortex-m3 is specified. data corruption? absolutely not, we're fixing that on sight ๐ฅ
โจ -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 is not enabled then words in packed data structures are accessed a byte at a time. slow and steady, one byte at a time ๐
-munaligned-access,-mno-unaligned-accessโ controls whether the compiler generates code that does unaligned accesses to memory. This sets the ARM attributeTag_CPU_unaligned_accessin the object file you get out, true or false, matching whichever of these you picked. And bestie, if unaligned access is enabled, the preprocessor symbol__ARM_FEATURE_UNALIGNEDgets defined too. โจ-mneon-for-64bitsโ deprecated, does literally nothing. It's giving ghost town. ๐-mslow-flash-dataโ assume that loading data from flash is slower than fetching instructions. So it minimizes literal loads for better performance, periodt. Only supported when you're compiling for ARMv7 M-profile, and it's off by default. Also? It conflicts with-mword-relocations. Pick a lane. ๐-masm-syntax-unifiedโ assume your inline assembler is using unified asm syntax. Default is currently off, which implies divided syntax. Heads up: this option has no impact on Thumb2. But that may change in future releases of GCC. And divided syntax should be considered deprecated. ๐-mrestrict-itโ restricts generation of IT blocks so they conform to the rules of ARMv8-A. IT blocks can only contain a single 16-bit instruction from a select set of instructions. This one 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. Disabled by default. iykyk. ๐ง-mverbose-cost-dumpโ enables verbose cost model dumping in the debug dump files. Provided for use in debugging the compiler. ๐ฅ-mpure-codeโ do not allow constant data to be placed in code sections. Additionally, when compiling for ELF object format, give all text sections the ELF processor-specific section attributeSHF_ARM_PURECODE. Only available when generating non-pic code for M-profile targets. โจ-mcmseโ generate secure code as per the ARMv8-M Security Extensions: Requirements on Development Tools Engineering Specification, which you can find at <https://developer.arm.com/documentation/ecm0359818/latest/>. ๐ก๏ธ-mfix-cmse-cve-2021-35465โ mitigate 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. And if you need to turn the mitigation off? The option-mno-fix-cmse-cve-2021-35465does exactly that. ๐-mfdpic,-mno-fdpicโ select 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, bestie.
Note that static linking is not supported, because it would still involve the dynamic linker when the program self-relocates. If that behavior is acceptable to you, use-staticand-Wl,-dynamic-linkeroptions.
The opposite -mno-fdpic option is useful (and required, fr fr) 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 is avr2.
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โ "Classic" devices with 16 KiB up to 64 KiB of program memory and with theMOVWinstruction. mcu =attiny167,attiny1634,atmega8u2,atmega16u2,atmega32u2,ata5505,ata6617c,ata664251,at90usb82,at90usb162.avr4โ "Enhanced" devices with up to 8 KiB of program memory. mcu =atmega48,atmega48a,atmega48p,atmega48pa,atmega48pb,atmega8,atmega8a,atmega8hva,atmega88,atmega88a,atmega88p,atmega88pa,atmega88pb,atmega8515,atmega8535,ata6285,ata6286,ata6289,ata6612c,at90pwm1,at90pwm2,at90pwm2b,at90pwm3,at90pwm3b,at90pwm81.avr5โ "Enhanced" devices with 16 KiB up to 64 KiB of program memory. 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,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,ata5795,ata5790,ata5790n,ata5791,ata6613c,ata6614q,ata5782,ata5831,ata8210,ata8510,ata5702m322,at90pwm161,at90pwm216,at90pwm316,at90can32,at90can64,at90scr100,at90usb646,at90usb647,at94k,m3000.avr51โ "Enhanced" devices with 128 KiB of program memory. mcu =atmega128,atmega128a,atmega128rfa1,atmega128rfr2,atmega1280,atmega1281,atmega1284,atmega1284p,atmega1284rfr2,at90can128,at90usb1286,at90usb1287.avr6โ "Enhanced" devices with 3-byte PC, i.e. with more than 128 KiB of program memory. mcu =atmega256rfr2,atmega2560,atmega2561,atmega2564rfr2.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.avrxmega3โ "XMEGA" devices with up to 64 KiB of combined program memory and RAM, and with program memory visible in the RAM address space. mcu =attiny202,attiny204,attiny212,attiny214,attiny402,attiny404,attiny406,attiny412,attiny414,attiny416,attiny417,attiny804,attiny806,attiny807,attiny814,attiny816,attiny817,attiny1604,attiny1606,attiny1607,attiny1614,attiny1616,attiny1617,attiny3214,attiny3216,attiny3217,atmega808,atmega809,atmega1608,atmega1609,atmega3208,atmega3209,atmega4808,atmega4809.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.avrxmega5โ "XMEGA" devices with more than 64 KiB and up to 128 KiB of program memory and more than 64 KiB of RAM. mcu =atxmega64a1,atxmega64a1u.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.avrxmega7โ "XMEGA" devices with more than 128 KiB of program memory and more than 64 KiB of RAM. mcu =atxmega128a1,atxmega128a1u,atxmega128a4u.avrtinyโ "TINY" Tiny core devices with 512 B up to 4 KiB of program memory. mcu =attiny4,attiny5,attiny9,attiny10,attiny20,attiny40.avr1โ this ISA is implemented by the minimal AVR core and supported for assembler only. mcu =attiny11,attiny12,attiny15,attiny28,at90s1200.
-mabsdataโ assume that all data in static storage can be accessed by LDS / STS instructions. This option has only an effect on reduced Tiny devices like ATtiny40. See also theabsdataAVR Variable Attributes, variable attribute. ๐ซ-maccumulate-argsโ accumulate outgoing function arguments and acquire/release the needed stack space for outgoing function arguments once, in the function prologue/epilogue. Without this option, outgoing arguments are pushed before calling a function and popped afterwards. ๐ซถ
Popping the arguments after the function call can be expensive on AVR, so accumulating the stack space might lead to smaller executables, because arguments need not be removed from the stack after such a function call. ๐ธ
This option can lead to reduced code size for functions that perform several calls to functions that get their arguments on the stack โ like calls to printf-like functions. iykyk ๐ซถ
-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 instead of being inlined. Code size is smaller. tiny but mighty โจ-mdouble=bits-mlong-double=bitsโ Set the size (in bits) of thedoubleorlong doubletype, respectively. Possible values for bits are32and64. Whether or not a specific value for bits is 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. ๐-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 Attributesno_gccisrfunction attribute. This feature is activated per default if optimization is on (but not with-Og, see Optimize Options), and if GNU Binutils support PR21683 (https://sourceware.org/PR21683). ๐ฅ-mint8โ Assumeintto be an 8-bit integer. This affects the sizes of all types: acharis 1 byte, anintis 1 byte, alongis 2 bytes, andlong longis 4 bytes. > 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 inmain. The effect is the same like attaching attribute AVR Function AttributesOS_tasktomain. It is 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. ๐ฌ-mrelaxโ Try to replaceCALLresp.JMPinstruction by the shorterRCALLresp.RJMPinstruction 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 are not known before code is located. Therefore, the assembler code generated by the compiler is the same, but the instructions in the executable may differ from instructions in the assembler code. ๐
Relaxing must be turned on if linker stubs are needed, see the section on EIND and linker stubs below. ๐
-mrmwโ Assume that the device supports the Read-Modify-Write instructionsXCH,LAC,LASandLAT. ๐ฆ-mshort-callsโ Assume thatRJMPandRCALLcan target the whole program memory.
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. ๐
This option is used internally by the compiler to select and build multilibs for architectures avr2 and avr25. These architectures mix devices with and without SPH. For any setting other than -mmcu=avr2 or -mmcu=avr25 the compiler driver adds or removes this option from the compiler proper's command line, because the compiler then knows if the device or architecture has an 8-bit stack pointer and thus no SPH register or not. ๐ง
-mstrict-Xโ Use address registerXin a way proposed by the hardware. This means thatXis only used in indirect, post-increment or pre-decrement addressing. ๐ฏ
Without this option, the X register may be used in the same way as Y or Z, which then is emulated by additional instructions. For example, loading a value with X+const addressing with a small non-negative const < 64 to a register Rn is performed as
adiw r26, const ; X += const
ld <Rn>, X ; <Rn> = *X
sbiw r26, const ; X -= const
-mtiny-stackโ Only change the lower 8 bits of the stack pointer. ๐ฃ-mfract-convert-truncateโ Allow to use truncation instead of rounding towards zero for fractional fixed-point types. โ๏ธ-nodevicelibโ Don't link against AVR-LibC's device specific librarylib<mcu>.a. ๐ซ-nodevicespecsโ Don't add-specs=device-specs/specs-mcuto the compiler driver's command line. The user takes responsibility for supplying the sub-processes like compiler proper, assembler and linker with appropriate command line options. This means that the user has to supply her private device specs file by means of-specs=path-to-specs-file. There is no more need for option-mmcu=mcu. ๐ซก
This option can also serve as a replacement for the older way of specifying custom device-specs files that needed -B some-path to point to a directory which contains a folder named device-specs which contains a specs file named specs-mcu, where mcu was specified by -mmcu=mcu. ๐
-Waddr-space-convertโ Warn about conversions between address spaces in the case where the resulting address space is not contained in the incoming address space. ๐ฃ-Wmisspelled-isrโ Warn if the ISR is misspelled, i.e. without__vectorprefix. Enabled by default. โ๏ธ
โจ EIND and Devices with More Than 128 Ki Bytes of Flash โจ
Pointers in the implementation are 16 bits wide. The address of a function or label is represented as word address so that indirect jumps and calls can target any code address in the range of 64 Ki words. ๐ง
In order to facilitate indirect jump on devices with more than 128 Ki bytes of program memory space, there is a special function register called EIND that serves as the most significant part of the target address when EICALL or EIJMP instructions are used. ๐
Indirect jumps and calls on these devices are handled as follows by the compiler, and are subject to some limitations:
- The compiler never sets
EIND. ๐ - The compiler uses
EINDimplicitly inEICALL/EIJMPinstructions, or might readEINDdirectly in order to emulate an indirect call/jump by means of aRETinstruction. ๐ - The compiler assumes that
EINDnever changes during the startup code or during the application. In particular,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. Thus, the indirect call/jump jumps to such a stub. The stub contains a direct jump to the desired address. ๐
- Linker relaxation must be turned on so that the linker generates the stubs correctly in all situations. See the compiler option
-mrelaxand the linker option--relax. There are corner cases where the linker is supposed to generate stubs but aborts without relaxation and without a helpful error message. ๐ - The default linker script is arranged for code with
EIND = 0. If code is supposed to work for a setup withEIND != 0, a custom linker script has to be used in order to place the sections whose name start 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, see the AVR-LibC user manual (http://nongnu.org/avr-libc/user-manual/). ๐ - It is legitimate for user-specific startup code to set up
EINDearly, for example by means of initialization code located in section.init3. Such code runs prior to 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 is located. โฐ
#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 are generated automatically by the linker if the following two conditions are 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 such
gsmodifiers for code labels in the following situations:- Taking address of a function or code label. ๐ฏ
- Computed goto. ๐
- If prologue-save function is used, see
-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 so is not supported:
int main (void)
{
/* Call function at word address 0x2 */
return ((int(*)(void)) 0x2)();
}
Instead, a stub has to be set up, i.e. 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 the application be 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 way bigger than that 64 KiB range you can reach with 16-bit pointers, bestie. And to get at memory outside that 64 KiB range, the content of a "RAMP" register gets used as the high part of the address ๐ซ โ so the "X", "Y", "Z" address register gets concatenated with the "RAMPX", "RAMPY", "RAMPZ" special function register, respectively, to build a wide address. And similarly, "RAMPD" is used together with direct addressing. Teamwork, honestly ๐ซถ
- The startup code initializes the
"RAMP"special function registers with zero. - If a AVR Named Address Spaces, named address space other than generic or
"__flash"is used, then"RAMPZ"is set as needed before the operation. - If the device supports RAM larger than 64 KiB and the compiler needs to change
"RAMPZ"to accomplish an operation,"RAMPZ"is reset to zero after the operation. - If the device comes with a specific
"RAMP"register, 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
"RAMP"registers, you must reset it to zero after the access. Not optional, bestie, that's the rule ๐
โจ AVR Built-in Macros โจ
GCC defines several built-in macros so that your user code can vibe-check for the presence or absence of features ๐ Almost any of the following built-in macros are deduced from device capabilities and thus 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__"โ Build-in macro that resolves to a decimal number that identifies the architecture and 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 to"atmega8".
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. Fancy ๐"__AVR_HAVE_ELPM__"โ The device has the"ELPM"instruction."__AVR_HAVE_ELPMX__"โ The device has the"ELPM Rn,Z"and"ELPM Rn,Z+"instructions."__AVR_HAVE_MOVW__"โ The device has the"MOVW"instruction to perform 16-bit register-register moves."__AVR_HAVE_LPMX__"โ The device has the"LPM Rn,Z"and"LPM Rn,Z+"instructions."__AVR_HAVE_MUL__"โ The device has a hardware multiplier. Slay."__AVR_HAVE_JMP_CALL__"โ The device has the"JMP"and"CALL"instructions. This is the case for devices with more than 8 KiB of program memory."__AVR_HAVE_EIJMP_EICALL__""__AVR_3_BYTE_PC__"โ The device has the"EIJMP"and"EICALL"instructions. 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."__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 the"RAMPD","RAMPX","RAMPY","RAMPZ"special 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 are"SBRS","SBRC","SBIS","SBIC"and"CPSE". The second macro is only defined if"__AVR_HAVE_JMP_CALL__"is also set."__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 like"IN","OUT","SBI", etc. may use a different address as if addressed by an instruction to access RAM like"LD"or"STS". 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 of"LD*"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 for"avrtiny"and"avrxmega3". Even more convenient, there is no need to use address spaces like"__flash"or features like attribute"progmem"and"pgm_read_*"."__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 of"double"if-mdouble=is not set. To test the layout of"double"in 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 for"long double"instead of"double"."__WITH_DOUBLE_COMPARISON__"โ Reflects the--with-double-comparison={tristate|bool|libf7}configure option (https://gcc.gnu.org/install/configure.html#avr) and is defined to2or3."__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]โ Specifies the name of the target Blackfin processor. Currently, cpu can be one of bf512, 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.
The optional sirevision specifies the silicon revision of the target Blackfin processor. Any workarounds available for the targeted silicon revision are enabled. If sirevision is none, no workarounds are enabled. If sirevision is any, 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. If sirevision is none, the "__SILICON_REVISION__" is not defined. If sirevision is any, the "__SILICON_REVISION__" is defined to be 0xffff. If this optional sirevision is not used, GCC assumes the latest known silicon revision of the targeted Blackfin processor.
GCC defines a preprocessor macro for the specified cpu. For the bfin-elf toolchain, this option causes the hardware BSP provided by libgloss to be linked in if -msim is not given.
Without this option, bf532 is used as the processor by default.
Note that support forbf561is incomplete. Forbf561, only the preprocessor macro is defined. That's it, bestie, that's all you get ๐ญ
-msimโ Specifies that 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. Free real estate โจ-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_LOADS"is 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_SYNCS"is 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โ bestie we're assuming the program is arbitrarily large. this is the default, no cap. ๐-mstack-check-l1โ do the stack checking using info the uClinux kernel dropped into L1 scratchpad memory. iconic teamwork fr.-mid-shared-libraryโ generate code that supports shared libraries via the library ID method. this lets you do execute in place AND shared libraries in an environment with no virtual memory management, which is giving "we make it work anywhere" energy. this option implies-fPIC. with abfin-elftarget, it implies-msim. โจ-mno-id-shared-libraryโ generate code that does not assume ID-based shared libraries are being used. this is the default, lowkey the chill option. ๐-mleaf-id-shared-libraryโ generate code that supports shared libraries via the library ID method, but assumes this library or executable won't link against any other ID shared libraries. that lets the compiler use faster code for jumps and calls. speed, slay. ๐ฅ-mno-leaf-id-shared-libraryโ do not assume 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. so likeโฆ0is the moment, the rest is just committing. ๐-msep-dataโ generate code that lets the data segment live 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. main character memory layout. ๐-mno-sep-dataโ generate code that assumes 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-calls restores the default behavior. note these switches have no effect on how the compiler generates code to handle function calls via function pointers. iykyk. ๐ฆ
-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. it's giving "rules are more like guidelines" ngl. ๐-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. periodt.-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 -mcorea or -mcoreb, which selects the one-application-per-core programming model. without -mcorea or -mcoreb, the single-application/dual-core programming model is used. in this model, the main function of Core B should be named as coreb_main.
if this option is not used, the single-core application programming model is used. so many models bestie, pick your vibe. ๐
-mcoreaโ build a standalone application for Core A of BF561 when using the one-application-per-core programming model. proper start files and link scripts are used to support Core A, and the macro__BFIN_COREAis defined. this option can only be used in conjunction with-mmulticore. ๐-mcorebโ build a standalone application for Core B of BF561 when using the one-application-per-core programming model. proper start files and link scripts are used to support Core B, and the macro__BFIN_COREBis defined. when this option is used,coreb_mainshould be used instead ofmain. this option can only be used in conjunction with-mmulticore. โจ-msdramโ build a standalone application for SDRAM. proper start files and link scripts are used to put the application into SDRAM, and the macro__BFIN_SDRAMis defined. the loader should initialize SDRAM before loading the application. do not skip that step bestie. ๐-micplbโ assume that ICPLBs are enabled at run time. this has an effect on 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 determine what kind of instructions it can emit when generating assembly code. permissible names are:c62x,c64x,c64x+,c67x,c67x+,c674x. choose your fighter. ๐-mbig-endianโ generate code for a big-endian target. ๐-mlittle-endianโ generate code for a little-endian target. this is the default, the tiny icon. ๐ญ-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. the corresponding sections used for large pieces of data are.fardata,.farand.const. small stuff gets the cozy spot, big stuff goes far. ๐ซถ-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. everyone's small now, we don't gatekeep. ๐-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. absolute addresses only, no shortcuts. โญ
๐ CRIS Options ๐
these options are defined specifically for the CRIS ports.
-march=architecture-type-mcpu=architecture-typeโ generate code for the specified architecture. the choices for architecture-type arev3,v8andv10for respectively ETRAX 4, ETRAX 100, and ETRAX 100 LX. default isv0. ๐-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. same menu, different intent bestie. ๐ธ-mmax-stack-frame=nโ warn when the stack frame of a function exceeds n bytes. it's giving "we're watching you" energy. ๐ญ-metrax4-metrax100โ the options-metrax4and-metrax100are synonyms for-march=v3and-march=v8respectively. โจ-mmul-bug-workaround-mno-mul-bug-workaroundโ work around a bug in themulsandmuluinstructions for CPU models where it applies. this option is active 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. tea spilled, literally. ๐ซ-mcc-initโ do not use condition-code results from previous instruction; always emit compare and test instructions before use of condition codes. fresh check every single time, no leftovers. ๐-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 (no-options) 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. alignment glow-up, but the ABI stays untouched. ๐-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. bestie please look at your output, it will not warn you. ๐ญ
-melfโ legacy no-op option. it's giving "i'm here but i do nothing", honestly relatable. ๐-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.
-mmacโ enable the use of multiply-accumulate instructions. disabled by default. ๐ธ-mcr16cplus-mcr16cโ generate code for CR16C or CR16C+ architecture. CR16C+ architecture is default. ๐-msimโ links the librarylibsim.awhich is in compatible with simulator. applicable to ELF compiler only. ๐ฆ-mint32โ choose integer type as 32-bit wide. thicc ints. ๐-mbit-opsโ generatessbit/cbitinstructions for bit manipulations. bit by bit, iconic. โญ-mdata-model=modelโ choose a data model. the choices for model arenear,farormedium.mediumis default. however,faris not valid with-mcr16c, as the CR16C architecture does not support the far data model. know the limits bestie. ๐ญ
๐ 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. pick your era, the default is the newest vibe. ๐-mcpu=cpuโ picks the C-SKY target processor, bestie. Valid values for cpu are a whole entire menu:
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, and
ck810ftv.
-mbig-endian,-EB,-mlittle-endian,-ELโ pick big- or little-endian code. The default is little-endian. ๐ฆ-mfloat-abi=nameโ says which floating-point ABI to use. Permissible values are:soft,softfpandhard.- Saying
softmakes GCC spit out output containing library calls for floating-point operations. softfplets it generate code using hardware floating-point instructions, but still uses the soft-float calling conventions.hardallows generation of floating-point instructions and uses FPU-specific calling conventions.- The default depends on the specific target configuration.
- Saying
Heads up, queen: 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. No mixing. Periodt.
-mhard-float,-msoft-floatโ select hardware or software floating-point implementations. The default is soft float.-mdouble-float,-mno-double-floatโ when-mhard-floatis in effect, enable generation of double-precision float instructions. This is the default except when compiling for CK803.-mfdivdu,-mno-fdivduโ when-mhard-floatis in effect, enable generation of"frecipd","fsqrtd", and"fdivd"instructions. This is the default except when compiling for CK803.-mfpu=fpuโ selects 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โ enables 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-mistackoption is required to handle the"interrupt"and"isr"function attributes. Like, no-mistack, no interrupt magic. ๐
-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 numbered0-7to 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 numbered16-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โ generate code using"stm"and"ldm"instructions. This option isn't supported on CK801 but is enabled by default on other processors.-mconstpool,-mno-constpoolโ create constant pools in the compiler instead of deferring it to the assembler. This option is the default and required for correct code generation on CK801 and CK802, and is optional on other processors.-mstack-size,-mno-stack-sizeโ emit.stack_sizedirectives for each function in the assembly output. This option defaults to off.-mccrt,-mno-ccrtโ generate code for the C-SKY compiler runtime instead of libgcc. This option defaults to off.-mbranch-cost=nโ set the branch costs to roughlyninstructions. The default is1.-msched-prolog,-mno-sched-prologโ permit scheduling of function prologue and epilogue sequences.
Okay so this one is spicy ๐ถ๏ธ: using -msched-prolog can result in code that is not compliant with the C-SKY V2 ABI prologue requirements, and that cannot be debugged or backtraced. It is disabled by default. So likeโฆ be careful, bestie.
-msimโ links the librarylibsemi.a, which is compatible with the 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 so by running the compiler or linker multiple times and joining the results together with lipo. ๐ฎโ๐จ
The subtype of the file created (like ppc7400 or ppc970 or i686) is determined by the flags that specify the ISA that GCC is targeting, like -mcpu or -march. The -force_cpusubtype_ALL option can be used to override this.
The Darwin tools vary in their behavior when presented with an ISA mismatch:
- The assembler,
as, only permits instructions to be used that are valid for the subtype of the file it is 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 asked 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. -Fdirโ add the framework directory dir to the head of the list of directories to be searched for header files. These directories are interleaved with those specified by-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
Headersand/orPrivateHeadersdirectory 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, withHeadersbeing searched first. A subframework is a framework directory that is in a framework'sFrameworksdirectory. 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 can be found in/System/Library/Frameworksand/Library/Frameworks. An example include looks like#include <Framework/header.h>, whereFrameworkdenotes the name of the framework andheader.his found in thePrivateHeadersorHeadersdirectory.
- A framework directory is a directory with frameworks in it. A framework is a directory with a
-iframeworkdirโ like-Fexcept the directory is treated as a system directory. The main difference between this-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โ emit debugging information for symbols that are used. For stabs debugging format, this enables-feliminate-unused-debug-symbols. This is by default ON.-gfullโ emit debugging information for all symbols and types.-fconstant-cfstringsโ the-fconstant-cfstringsis an alias for-mconstant-cfstrings.-mconstant-cfstringsโ when the NeXT runtime is being used (the default on these systems), override any-fconstant-string-classsetting and cause@"..."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โ enable 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โ override the defaults for"bool"so 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. It's giving "commit to the bit" energy, fr fr. ๐ญ
-mfix-and-continue,-ffix-and-continue,-findirect-dataโ generate code suitable for fast turnaround development, such as to allow GDB to 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โ cause the errors having to do with files that have the wrong architecture to be fatal.-bind_at_loadโ marks the output file so the dynamic linker binds all undefined references the second the file gets loaded or launched. no lazy binding era, bestie.-bundleโ produces a Mach-o bundle format file. wanna know more?man ld(1), she explains it ๐-bundle_loaderexecutable โ tells it which executable is gonna load the build output file we're linking. again,man ld(1)has the tea โ-dynamiclibโ pass this and GCC makes a dynamic library instead of an executable when linking, using the Darwinlibtoolcommand. iconic behaviour tbh.-force_cpusubtype_ALLโ makes GCC's output file have theALLsubtype instead of whatever the-mcpuor-marchoption was controlling. not me overriding the vibe check ๐ญ-allowable_clientclient_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โ okay so ALL of these get passed straight to the Darwin linker, and the Darwin linker man page describes them in detail. that's the whole vibe. iykyk ๐ฆ
๐ DEC Alpha Options ๐
these -m options are defined for the DEC Alpha implementations, and yes she's vintage but she still ate ๐
โจ the floaty ones โจ
-mno-soft-float-msoft-floatโ use (or don't use) the hardware floating-point instructions for floating-point operations. when-msoft-floatis specified, functions inlibgcc.aare used to do floating-point operations. and like โ unless those routines get replaced by stuff that emulates floating-point ops, or compiled so they call such emulation routines, these routines issue floating-point operations. so if you're compiling for an Alpha with no floating-point operations, you must make sure the library is built so it doesn't call them. no cap.
heads up bestie: Alpha implementations without floating-point operations are still required to have floating-point registers. yeah. that's just how she is ๐ญ
-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 isn't used, floating-point operands get passed in integer registers as if they were integers, and floating-point results get 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. periodt.
a typical use of this option is building a kernel that doesn't use โ and therefore doesn't need to save and restore โ any floating-point registers. main character kernel energy fr fr.
-mieeeโ the Alpha architecture implements floating-point hardware optimized for maximum performance. it's mostly compliant with the IEEE floating-point standard, but for full compliance you need software assistance. this option generates fully IEEE-compliant code except that the inexact-flag is not maintained (see below, bestie). turn this on and the preprocessor macro_IEEE_FPis defined during compilation. the resulting code is less efficient but 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. โจ-mieee-with-inexactโ like-mieeeexcept the generated code also maintains the IEEE inexact-flag. turning this on makes the generated code implement fully-compliant IEEE math. and on top of_IEEE_FP,_IEEE_FP_EXACTis defined as a preprocessor macro. on some Alpha implementations the resulting code may execute significantly slower than the default code. since there's very little code that depends on the inexact-flag, you should normally not specify this option. other Alpha compilers call this option-ieee_with_inexact. ๐
๐ trap & rounding girlies ๐
- *
-mfp-trap-mode=trap-mode* โ this option controls what floating-point related traps are enabled. other Alpha compilers call this option-fptmtrap-mode. the trap mode can be set to one of four values:nโ this is the default (normal) setting. the only traps that are enabled are the ones that can't 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 Alpha architecture manual for the details, bestie).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-fprmrounding-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 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. meaning: without software assistance it's literally impossible to recover from a floating trap, and program execution normally needs to be terminated. GCC can generate code that assists operating system trap handlers in determining the exact location that caused a floating-point trap. depending on what an application needs, you can pick different levels of precision:pโ program precision. this is the default and 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โ 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. that's it. that's the whole thing. ๐-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 option to build a shared library dynamic loader. itself a shared library, it must relocate itself in memory before it can find the variables and constants in its own data segment. self-relocating queen ๐
๐ธ instruction set vibes ๐ธ
-mbwx-mno-bwx-mcix-mno-cix-mfix-mno-fix-mmax-mno-maxโ 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-mcpu=option, or that of the CPU on which GCC was built if none is specified. slay.-mfloat-vax-mfloat-ieeeโ generate code that uses (does not use) VAX F and G floating-point arithmetic instead of IEEE single and double precision.-mexplicit-relocs-mno-explicit-relocsโ older Alpha assemblers provided no way to generate symbol relocations except via assembler macros. and using those macros doesn't allow optimal instruction scheduling ๐ค GNU binutils as of version 2.12 supports 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's 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 are 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 to 64KB, but lets the variables be directly accessed via a single instruction. iconic.
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. periodt. ๐
-msmall-text,-mlarge-textโ okay so with-msmall-textthe compiler is like "bestie, I'm assuming the code of the whole entire program (or shared library) fits in 4MB", which means it's reachable with a branch instruction ๐ . And when-msmall-datais used, the compiler can assume that all local symbols share the same$gpvalue, which cuts the number of instructions a function call needs from 4 down to 1. glow up fr.
The default is -mlarge-text.
-mcpu=cpu_typeโ sets the instruction set and the instruction scheduling parameters for machine type cpu_type. You can drop either the EV style name or the matching chip number, your choice ๐. GCC supports scheduling parameters for the EV4, EV5 and EV6 family of processors, and it picks the default instruction-set values from whatever processor you name. If you don't specify a processor type at all, GCC just defaults to the processor it was built on.
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. Heads up tho: -mcpu=native has no effect if GCC doesn't recognize the processor ๐.
-mtune=cpu_typeโ this one sets only the instruction scheduling parameters for machine type cpu_type. The instruction set stays exactly as it was, no touchy โ.
Native toolchains also support the value native, which selects the best architecture option for the host processor. And again, -mtune=native has no effect if GCC doesn't recognize the processor.
-mmemory-latency=timeโ sets the latency the scheduler should assume for typical memory references as seen by the application. And bestie, this number is highly dependent on the memory access patterns your app uses and the size of the external cache on the machine. very much a vibe check per-machine situation.
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 that
L3is only valid for EV5.
- 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 that
๐ eBPF Options ๐
-mframe-limit=bytesโ specifies the hard limit for frame sizes, in bytes. Currently the value you can specify should be less than or equal to32767. Defaults to whatever limit is imposed by the version of the Linux kernel targeted.-mkernel=versionโ specifies the minimum version of the kernel that will run the compiled program. GCC uses this version to figure out 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โ generate code for a big-endian target.-mlittle-endianโ generate code for a little-endian target. This is the default ๐ .-mxbpfโ generate code for an expanded version of BPF, which relaxes some of the restrictions imposed by the BPF architecture:- Save and restore callee-saved registers at function entry and exit, respectively.
๐ธ FR30 Options ๐ธ
These options are defined specifically for the FR30 port.
-msmall-modelโ use the small address space model. This can produce smaller code, but it does assume that all symbolic values and addresses fit into a 20-bit range. so, y'know, only if they actually do ๐ญ.-mno-lsimโ assume that runtime support has been provided and so there is 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.
-msimโ specifies that the program will be run on the simulator. This causes an alternate runtime startup and library to be linked.
You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. no cap, that's a real requirement ๐ซถ.
-mlraโ enable Local Register Allocation. This is still experimental for FT32, so by default the compiler uses standard reload.-mnodivโ do not usedivandmodinstructions.-mft32bโ enable use of the extended instructions of the FT32B processor.-mcompressโ compress all code using the Ft32B code compression scheme.-mnopmโ do not 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โ do not 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โ select 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. With abfin-elftarget, this option implies-msim.-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. It's enabled by default if optimizing for speed and compiling for shared libraries (i.e.,-fPICor-fpic), or when an optimization option such as-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โ enable the use of"GPREL"relocations in the FDPIC ABI for data that is 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 is not,-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. like, literally never, it's giving "internal plumbing" ๐ง.-mlinked-fpโ follow 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 allows the functions to 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 has an effect 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โ turns off the optimization of&&and||inside conditional execution. ๐
bestie this switch is literally just for debugging the compiler itself and will probably get yeeted in a future version. so likeโฆ don't build your whole personality on it.
-mnested-cond-execโ turns ON the nested conditional execution optimizations (this is the default, so she's already on by default, slay). โจ
again: mainly a compiler-debugging switch, and likely to be removed in a future version. just so you know.
-mno-nested-cond-execโ turns OFF those nested conditional execution optimizations.
same disclaimer, same energy: mainly for debugging the compiler, likely to get removed someday.
-moptimize-membarโ this one yeets redundantmembarinstructions out of the compiler-generated code. it is enabled by default, no cap. ๐งน-mno-optimize-membarโ this one turns OFF the automatic removal of redundantmembarinstructions from the generated code. so the membars stay. iconic of them honestly.-mtomcat-statsโ makes gas print out tomcat statistics. numbers girlies rise ๐- *
-mcpu=cpu* โ pick which processor type you're generating code for. the possible values arefrv,fr550,tomcat,fr500,fr450,fr405,fr400,fr300andsimple. ๐
๐ GNU/Linux Options ๐
these -m options are defined for GNU/Linux targets:
-mglibcโ use the GNU C library. this is the default except on*-*-linux-*uclibc*,*-*-linux-*musl*and*-*-linux-*android*targets. so like, she's the main character everywhere else. ๐-muclibcโ use the 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 that's 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. one option, three jobs, she's employed. ๐
-tno-android-ccโ disable the compilation effects of-mandroid, i.e., do not enable-mbionic,-fPIC,-fno-exceptionsand-fno-rttiby default.-tno-android-ldโ disable the linking effects of-mandroid, i.e., pass standard Linux linking options to the linker.
๐ธ H8/300 Options ๐ธ
these -m options are defined for the H8/300 implementations:
-mrelaxโ shorten some address references at link time when possible; it uses the linker option-relax. โจ-mhโ generate code for the H8/300H.-msโ generate code for the H8S.-mnโ generate code for the H8S and H8/300H in the normal mode. this switch must be used either with-mhor-ms. like, it doesn't work alone bestie, it needs a buddy.-ms2600โ generate code for the H8S/2600. this switch must be used with-ms. ๐ซถ-mexrโ extended registers are stored on the stack before execution of a function with the monitor attribute. the default option is-mexr. this option 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. this option is valid only for H8S targets.-mint32โ makeintdata 32 bits by default. glow up for your ints ๐-malign-300โ on the H8/300H and H8S, use the same alignment rules as for the H8/300. the default for the H8/300H and H8S is to align longs and floats on 4-byte boundaries.-malign-300causes them to be aligned on 2-byte boundaries. this option has no effect on the H8/300. so don't come for her on the H8/300, she's not even listening.
๐ HPPA Options ๐
these -m options are defined for the HPPA family of computers:
-march=architecture-type โ generate 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. refer to/usr/lib/sched.modelson an HP-UX system to determine the proper architecture option for your machine. code compiled for lower numbered architectures runs on higher numbered architectures, but **not the other way around. โฌ๏ธ only, never โฌ๏ธ.-mpa-risc-1-0,-mpa-risc-1-1,-mpa-risc-2-0โ synonyms for-march=1.0,-march=1.1, and-march=2.0respectively. same girl, different name tags. ๐-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, only aggregates larger than eight bytes are passed by hidden reference, and the option provides better compatibility with OpenMP. so it's giving "risky but sometimes worth it". ๐-mjump-in-delayโ this option is ignored and provided for compatibility purposes only. she's here for the vibes, not for the function. ๐-mdisable-fpregsโ prevent floating-point registers from being used in any manner. this is necessary for compiling kernels that perform lazy context switching of floating-point registers. if you use this option and then attempt to perform floating-point operations, the compiler aborts. like, dead. gone. ๐ญ so don't do that.-mdisable-indexingโ prevent the compiler from using indexing address modes. this avoids some rather obscure problems when compiling MIG generated code under MACH.-mno-space-regsโ generate code that assumes the target has no space registers. this allows GCC to generate faster indirect calls and use unscaled index address modes. ๐ฅ
such code is suitable for level 0 PA systems and kernels.
-mfast-indirect-callsโ generate code that assumes calls never cross space boundaries. this allows GCC to emit code that performs faster indirect calls. โก
this option does not work in the presence of shared libraries or nested functions. no cap, it just won't.
-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. ๐-mlong-load-storeโ generate 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โ use the portable calling conventions proposed by HP for ELF systems. โจ-mgasโ enable the use of assembler directives that only GAS understands. gas girlies only ๐- *
-mschedule=cpu-type* โ schedule 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 determine the proper scheduling option for your machine. the default scheduling is8000. ๐ -mlinker-optโ enable the optimization pass in the HP-UX linker. note 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. so likeโฆ spicy. ๐ถ๏ธ-msoft-floatโ generate 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.
-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. all or nothing bestie, it's giving commitment. ๐ซถ
-msioโ generate the predefine_SIOfor 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โ use 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 usingwhich `gcc -print-prog-name=ld`. this option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*.-mhp-ldโ use 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 usingwhich `gcc -print-prog-name=ld`. this option is only available on the 64-bit HP-UX GCC, i.e. configured withhppa*64*-*-hpux*. ๐-mlong-callsโ generate 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. ๐ญ she's long, she's indirect, she's doing her best.
-munix=unix-std โ bestie, this one makes the compiler spit out predefines and pick a startfile for a specific UNIX standard. Your choices for unix-std are93,95, and98.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. And the defaults?93for HP-UX 10.00,95for HP-UX 10.10 through to 11.00, and98for HP-UX 11.11 and later. ๐
Okay so here's the tea on what each one actually does: -munix=93 gives you the exact same predefines as GCC 3.3 and 3.4. -munix=95 adds extra predefines for XOPEN_UNIX and _XOPEN_SOURCE_EXTENDED, plus the startfile unix95.o. And -munix=98 adds predefines for _XOPEN_UNIX, _XOPEN_SOURCE_EXTENDED, _INCLUDE__STDC_A1_SOURCE and _INCLUDE_XOPEN_SOURCE_500, plus the startfile unix98.o.
โ ๏ธ No cap, this is important: this option changes the interfaces for various library routines. It also messes with the operational behavior of the C library. So extreme care is needed when you use this option. It is giving "handle with oven mitts." ๐งค
Library code that's meant to work with more than one UNIX standard has to test, set, and restore the variable __xpg4_extended_mask as appropriate. And most GNU software? Doesn't provide this capability. ๐
-nolibdldโ suppresses the generation of link options that searchlibdld.slwhen the-staticoption is specified on HP-UX 10 and later. ๐ซถ-staticโ so the HP-UX implementation ofsetlocaleinlibcdepends onlibdld.sl. And there's no archive version oflibdld.sl. Which means when you pass-static, you need special link options to resolve that dependency. ๐ญ
On HP-UX 10 and later, the GCC driver adds the necessary options to link with libdld.sl whenever -static is specified. Side effect? The resulting binary ends up dynamic. And on the 64-bit port, the linkers generate dynamic binaries by default anyway, so like, it was already that girl. If you want to stop the GCC driver from adding these link options, that's exactly what -nolibdld is for.
-threadsโ adds support for multithreading with the dce thread library under HP-UX. Sets flags for both the preprocessor and the linker. Teamwork, fr fr. ๐ค
โจ IA-64 Options โจ
These are the -m options defined for the Intel IA-64 architecture. Get comfy. ๐ฆ
-mbig-endianโ generate code for a big-endian target. This is the default for HP-UX.-mlittle-endianโ generate 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 you're 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 not always. ๐-mfixed-range=register-range โ generate code treating the given register range as fixed registers. A fixed register is one the register allocator cannot use. This is useful when compiling kernel code. A register range is specified as two registers separated by a dash. You can specify multiple register ranges separated by a comma. ๐-mtls-size=tls-size โ specify the 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โ (dis/en)able 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โ (en/dis)able 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โ (dis/en)able 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โ (en/dis)able 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โ (en/dis)able 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โ (en/dis)able 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 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 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 โ a 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 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. โจ
๐ M32C Options ๐
-mcpu=name โ bestie, this picks the CPU your code is gonna be generated for ๐ฏ and name has to be one of exactly these:r8cfor the R8C/Tiny series,m16cfor the M16C (up to /60) series,m32cmfor the M16C/80 series, orm32cfor the M32C/80 series. periodt.-msimโ says the program is gonna run on the simulator ๐ฅ๏ธ which makes an alternate runtime library get linked in โ one that supports, like, file I/O and stuff. > โ ๏ธ You must not use this option when generating programs that will run on real hardware; you must provide your own runtime library for whatever I/O functions are needed. no cap, real hardware needs real libraries ๐-memregs=number โ tells GCC how many memory-based pseudo-registers to use during code generation ๐งฎ These pseudo-registers get used like real registers, so it's giving a whole tradeoff: GCC's ability to fit the code into available registers vs. the performance penalty of using memory instead of registers. > Note that 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. consistency is the vibe or it's chaos ๐
๐ฅ M32R/D Options ๐ฅ
These -m options are defined for Renesas M32R/D architectures, bestie, let's go ๐ฆ
-m32r2โ generate code for the M32R/2 โจ-m32rxโ generate code for the M32R/X ๐ซ-m32rโ generate code for the M32R. This is the default ๐-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) ๐ญ slow but honest-msdata=noneโ disable use of the small data area. Variables are put 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 do not generate special code to reference them ๐ซถ-msdata=useโ put small global and static data in the small data area, and generate special instructions to reference them ๐-Gnum โ 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. at least it's not silently cursed ๐
-mdebugโ makes the M32R-specific code in the compiler display some statistics that might help in debugging programs ๐-malign-loopsโ align all loops to a 32-byte boundary ๐-mno-align-loopsโ do not 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 is1then branches are preferred over conditional code, if it is2, 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. iykyk ๐
-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 *cpu*s are:68000,68010,68020,68030,68040,68060,68302,68332andcpu32. The ColdFire *cpu*s 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. Other combinations of -mcpu and -march are rejected ๐
GCC defines the macro __mcf_cpu_cpu when ColdFire target cpu is selected. It also defines __mcf_family_family, where the value of family is given by the table above.
-mtune=tune โ tune the code for a particular microarchitecture within the constraints set by-marchand-mcpu. The M680x0 microarchitectures are:68000,68010,68020,68030,68040,68060andcpu32. The ColdFire microarchitectures are:cfv1,cfv2,cfv3,cfv4andcfv4e๐๏ธ
You can also use -mtune=68020-40 for code that needs to run relatively well on 68020, 68030 and 68040 targets. -mtune=68020-60 is similar but includes 68060 targets as well. These two options select the same tuning decisions as -m68020-40 and -m68020-60 respectively.
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. If GCC is tuning for a range of architectures, as selected by -mtune=68020-40 or -mtune=68020-60, it defines the macros for every architecture in the range.
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 is equivalent to-march=68000๐
Use this option 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 is 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 is equivalent to-march=68020๐ซ-m68030โ generate output for a 68030. This is the default when the compiler is configured for 68030-based systems. It is equivalent to-march=68030๐-m68040โ generate output for a 68040. This is the default when the compiler is configured for 68040-based systems. It is equivalent to-march=68040๐
This option inhibits the use of 68881/68882 instructions that have to be emulated by software on the 68040. Use this option 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 is 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 this option 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 is equivalent to-march=cpu32โญ
Use this option 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 is equivalent to-mcpu=5206, and is now deprecated in favor of that option ๐
Use this option 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โ makes output for a ColdFire 5407 CPU. Heads up tho bestie: this one is deprecated now, the glow-up replacement is the equivalent-mcpu=5407.-mcfv4eโ output for a ColdFire V4e family CPU (like547x/548x, iykyk). This one does bring hardware floating-point instructions into the mix. It's equivalent to-mcpu=547x, and yeah, it's deprecated in favor of that option. ๐ซถ-m68020-40โ generates output for a 68040, but without touching any of the new instructions. The vibe is code that runs relatively efficiently on a 68020/68881, a 68030, or a 68040. It does still use the 68881 instructions that get emulated on the 68040.
This option is equivalent to -march=68020 -mtune=68020-40.
-m68020-60โ generates output for a 68060, again without the new instructions. Code that can run relatively efficiently on a 68020/68881, a 68030, or a 68040. It does use the 68881 instructions that are emulated on the 68060.
This 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 with no FPU. ๐-mdiv,-mno-divโ generate (or don't generate) ColdFire hardware divide and remainder instructions. If-marchis used without-mcpu, the default is"on"for ColdFire architectures and"off"for M680x0 architectures. Otherwise the default comes from the target CPU (either the default CPU, or the one you named with-mcpu). For example, the default is"off"for-mcpu=5206and"on"for-mcpu=5206e.
GCC defines the macro __mcfhwdiv__ when this option is enabled. ๐
-mshortโ treats typeintas 16 bits wide, likeshort int. Bonus lore: 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 treatintas 16 bits wide. This is the default.-mnobitfield,-mno-bitfieldโ don't 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're using a configuration designed for a 68020. ๐-mrtdโ uses a different function-calling convention, where functions that take a fixed number of arguments return with thertdinstruction, which pops their arguments while returning. Saves one instruction in the caller since there's no need to pop the args there.
Warning bestie, this is a real one: this calling convention is incompatible with the one normally used on Unix, so you can't 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, but not here.)
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โ controls 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โ generates code that lets the data segment live 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โ generates code that assumes the data segment follows the text segment. This is the default.-mid-shared-libraryโ generates 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โ generates 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 just 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 isn't needed;-fPICsuffices. ๐ธ
GCC normally uses a single instruction to load values from the GOT. While that's relatively efficient, it only works if the GOT is smaller than about 64k. Anything larger makes the linker report an error such as:
relocation truncated to fit: R_68K_GOT16O foobar
If this happens, you should recompile your code with -mxgot. It should then work with very large GOTs. However, code generated with -mxgot is less efficient, since it takes 4 instructions to fetch the value of a global symbol.
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. ๐
These options have no effect unless GCC is generating position-independent code.
-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 needing 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. ๐-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โ bestie, this makes little-endian code. ๐ฆ-mio-volatileโ tells the compiler that literally any variable tagged with the"io"attribute should be treated as volatile. no takebacks.-mlโ variables get dumped into the.farsection by default.-mleadzโ turns on the"leadz"(leading zero) instruction. slay.-mmโ now variables go to the.nearsection by default instead.-mminmaxโ enables the"min"and"max"instructions. icon behaviour tbh.-mmultโ enables the multiplication and multiply-accumulate instructions. ๐-mno-optsโ turns OFF every optional instruction that-mall-optsturned on. the reverse card.-mrepeatโ enables the"repeat"and"erepeat"instructions, which are the low-overhead looping ones.-msโ every variable defaults to the.tinysection. โ ๏ธ heads up: there's a 65536-byte limit on this section. accesses to these variables go through the%gpbase register.-msaturโ enables the saturation instructions. note that the compiler does not currently generate these itself โ this option exists for compatibility with other tools, like"as".-msdramโ links the SDRAM-based runtime instead of the default ROM-based runtime.-msimโ links the simulator run-time libraries.-msimnovecโ links the simulator runtime libraries, but excluding the built-in support for reset and exception vectors and tables.-mtfโ all functions default to the.farsection. without this option, functions default to the.nearsection.-mtiny=nโ variables that arenbytes or smaller get allocated to the.tinysection. these use the$gpbase register. default for this option is4, but ๐ซถ remember there's a 65536-byte limit on the.tinysection.
โจ MicroBlaze Options โจ
-msoft-floatโ use software emulation for floating point (this is the default).-mhard-floatโ use hardware floating-point instructions instead. main character energy.-mmemcpyโ do not optimize block moves, just use"memcpy".-mno-clearbssโ โ ๏ธ this option is deprecated. use-fno-zero-initialized-in-bssinstead, bestie.-mcpu=cpu-typeโ use the features of, and schedule code for, the given CPU. supported values come in the formatvX.YY.Z, whereXis a major version,YYis the minor version, andZis 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โ โ ๏ธ deprecated, bestie. use-fstack-checkinstead.-mxl-gp-optโ use GP-relative.sdata/.sbsssections.-mxl-multiply-highโ use multiply high instructions for the high part of a 32x32 multiply.-mxl-float-convertโ use hardware floating-point conversion instructions.-mxl-float-sqrtโ use the 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. the valid models are:executableโ normal executable (default), uses startup codecrt0.o.-mpic-data-is-text-relativeโ assume that the displacement between the text and data segments is fixed at static link time. this lets data be referenced by offset from the start of the text address instead of the GOT, since PC-relative addressing is not supported.xmdstubโ for use with the 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.o, which does not contain a processor reset vector handler. it's suitable for transferring control on a processor reset to the bootloader rather than to the application.novectorsโ for applications that do not require any of the MicroBlaze vectors. this one may be useful for applications running within a monitoring application. it usescrt3.oas a startup file.
also, the option-xl-mode-app-modelis a deprecated alias for-mxl-mode-app-model. ๐
๐ 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 refer to processors with FPUs clocked at half the rate of the core, names of the form nf1_1 refer to processors with FPUs clocked at the same rate as the core, and names of the form nf3_2 refer to processors with FPUs clocked a ratio of 3:2 with respect to the core. for compatibility reasons, 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. 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. ๐-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 http://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? unchanged bestie, still the same. But each scalar value gets passed in a single 64-bit register instead of a lil pair of 32-bit registers. So like, scalar floating-point values come back in $f0 only โ not a $f0/$f1 duo. And the call-saved registers? Also still the same set, in that the even-numbered double-precision registers are the ones that get saved. consistency era ๐
Two extra variants of the o32 ABI exist so you can transition from 32-bit to 64-bit registers, and they are: FPXX (-mfpxx) and FP64A (-mfp64 -mno-odd-spreg).
- The FPXX extension mandates that all code has to execute correctly whether it's run using 32-bit or 64-bit registers. It can be interlinked with either FP32 or FP64 โ but not both, ok?? pick a lane. ๐
- The FP64A extension is basically FP64's cousin but it forbids the use of odd-numbered single-precision registers. You can pair it with the "FRE" mode of FPUs in MIPS32R5 processors, and that lets both FP32 and FP64A code interlink and run in the same process without having to switch FPU modes. multitasking icon behavior โจ
๐ธ OPTIONS ๐ธ (still going, we're so back)
-mabicalls,-mno-abicallsโ generate (or don't generate, bestie) code that's suitable for SVR4-style dynamic objects. And-mabicallsis the default for SVR4-based systems. locked in ๐-mshared,-mno-sharedโ generate (or don't) code that's fully position-independent, meaning it can be linked into shared libraries. Heads up: this option only affects-mabicalls.
All -mabicalls code has traditionally been position-independent, no matter what -fPIC and -fpic say. BUT โ as an extension, the GNU toolchain lets executables 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 what you get with -mno-shared.
-mno-shared depends on binutils 2.16 or higher, and it generates objects that can only be linked by the GNU linker. ngl kind of picky. However โ the option does not affect the ABI of the final executable; it only affects the ABI of relocatable objects. And using -mno-shared generally makes executables both smaller and quicker. ate fr fr ๐ฅ
-mshared is the default.
-mplt,-mno-pltโ assume (or don't 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 (or don't lift) the usual restrictions on the size of the global offset table.
GCC normally uses a single instruction to load values from the GOT. efficient queen โจ but it only works if the GOT is smaller than about 64k. Anything bigger and the linker gets mad and reports an error like:
relocation truncated to fit: R_MIPS_GOT16 foobar
If that happens to you, recompile your code with -mxgot. This works with very large GOTs, though the code is also less efficient, since it takes three instructions to fetch the value of a global symbol. trade-off vibes.
Note that some linkers can create multiple GOTs. If you have one of those fancy linkers, you should only need -mxgot when a single object file accesses more than 64k's worth of GOT entries. And very few do. rare occasion energy ๐
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. mysterious. we don't know her. ๐ฆ-mhard-floatโ use floating-point coprocessor instructions.-msoft-floatโ do not use floating-point coprocessor instructions. Implement floating-point calculations using library calls instead. library girlies rise up ๐-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. be careful bestie ๐ญ-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. default queen ๐-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. no thoughts, just abs โจ
-mnan=2008,-mnan=legacyโ these options control the encoding of the special not-a-number (NaN) IEEE 754 floating-point data.
The -mnan=legacy option selects the legacy encoding. In this case quiet NaNs (qNaNs) are denoted by the first bit of their trailing significand field being 0, whereas signaling NaNs (sNaNs) are denoted by the first bit of their trailing significand field being 1.
The -mnan=2008 option selects the IEEE 754-2008 encoding. In this case qNaNs are denoted by the first bit of their trailing significand field being 1, whereas sNaNs are denoted by the first bit of their trailing significand field being 0. they literally just swapped, iconic ๐
The default is -mnan=legacy unless GCC has been configured with --with-nan=2008.
-mllsc,-mno-llscโ use (or don't use)ll,sc, andsyncinstructions to implement atomic memory built-in functions. When neither option is specified, GCC uses the instructions if the target architecture supports them.
-mllsc is useful if the runtime environment can emulate the instructions, and -mno-llsc can be useful when compiling for nonstandard ISAs. You can make either option the default by configuring GCC with --with-llsc and --without-llsc respectively. --with-llsc is the default for some configurations; see the installation documentation for details. iykyk ๐
-mdsp,-mno-dspโ use (or don't 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 (or don't 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 (or don't use) the MIPS SmartMIPS ASE. smart girl summer ๐ธ-mpaired-single,-mno-paired-singleโ use (or don't use) paired-single floating-point instructions. This option requires hardware floating-point support to be enabled.-mdmx,-mno-mdmxโ use (or don't 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.-mips3d,-mno-mips3dโ use (or don't use) the MIPS-3D ASE. The option-mips3dimplies-mpaired-single. package deal โจ-mmicromips,-mno-micromipsโ generate (or don't generate) microMIPS code.
MicroMIPS code generation can also be controlled on a per-function basis by means of micromips and nomicromips attributes. per-function drama ๐
-mmt,-mno-mtโ use (or don't use) MT Multithreading instructions.-mmcu,-mno-mcuโ use (or don't use) the MIPS MCU ASE instructions.-meva,-mno-evaโ use (or don't use) the MIPS Enhanced Virtual Addressing instructions.-mvirt,-mno-virtโ use (or don't use) the MIPS Virtualization (VZ) instructions. virtual baddie era ๐ฆ-mxpa,-mno-xpaโ use (or don't use) the MIPS eXtended Physical Address (XPA) instructions.-mcrc,-mno-crcโ use (or don't use) the MIPS Cyclic Redundancy Check (CRC) instructions.-mginv,-mno-ginvโ use (or don't use) the MIPS Global INValidate (GINV) instructions.-mloongson-mmi,-mno-loongson-mmiโ use (or don't use) the MIPS Loongson MultiMedia extensions Instructions (MMI).-mloongson-ext,-mno-loongson-extโ use (or don't use) the MIPS Loongson EXTensions (EXT) instructions.-mloongson-ext2,-mno-loongson-ext2โ use (or don't 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. scroll down bestie โฌ๏ธ-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. tiny wins โจ
-msym32,-mno-sym32โ assume (or don't 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. shorter AND faster?? we love an overachiever ๐ฅ-G numโ okay so this one says: put definitions of externally-visible data in a small data section if that data is no bigger thannumbytes. Then GCC can generate more efficient accesses to the data; peep-mgpoptfor the tea. The default-Goption depends on the configuration. ๐-mlocal-sdata,-mno-local-sdataโ extend (or do not extend) the-Gbehavior to local data too, like to static variables in C.-mlocal-sdatais the default for all configurations. If the linker is complaining that an application is using too much small data, bestie, 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. ๐ซถ-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 moduleModwith-mextern-sdata -G num -mgpopt, andModreferences a variableVarthat is no bigger thannumbytes, you must make sure thatVaris placed in a small data section. IfVaris defined by another module, you must either compile that module with a high-enough-Gsetting or attach a"section"attribute toVar's definition. IfVaris common, you must link the application with a high-enough-Gsetting. The easiest way of satisfying these restrictions is to compile and link every module with the same-Goption. 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-Gsetting and additionally using-mno-extern-sdatato stop the library from making assumptions about externally-defined data. no cap โจ-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-gpoptis useful for cases where the$gpregister 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-gpoptimplies-mno-local-sdataand-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. lowkey a vibe for tiny devices ๐ธ-muninit-const-in-rodata,-mno-uninit-const-in-rodataโ put uninitialized"const"variables 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 make it fashion ๐-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-relocsis 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. bestie do not divide by zero unless you want the drama ๐ญ-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. pair them up, periodt ๐-mmemcpy,-mno-memcpyโ force (do not force) the use of"memcpy"for non-trivial block moves. The default is-mno-memcpy, which allows GCC to inline most constant-sized copies. ๐-mlong-calls,-mno-long-callsโ disable (do not disable) use of the"jal"instruction. Calling functions using"jal"is more efficient but requires the caller and callee to be in the same 256 megabyte segment. This option has no effect on abicalls code. The default is-mno-long-calls. same 256 MB segment or it's awkward fr fr-mmad,-mno-madโ enable (disable) use of the"mad","madu"and"mul"instructions, as provided by the R4650 ISA. ๐ฅ-mimadd,-mno-imaddโ enable (disable) use of the"madd"and"msub"integer instructions. The default is-mimaddon architectures that support"madd"and"msub"except for the 74k architecture where it was found to generate slower code. not the 74k catching strays ๐-mfused-madd,-mno-fused-maddโ enable (disable) use of the floating-point multiply-accumulate instructions, when they are available. The default is-mfused-madd. On the R8000 CPU when multiply-accumulate instructions are used, the intermediate product is calculated to infinite precision and is not subject to the FCSR Flush to Zero bit. This may be undesirable in some circumstances. On other processors the result is numerically identical to the equivalent computation using separate multiply, add, subtract and negate instructions. ๐ง-nocppโ tell the MIPS assembler to not run its preprocessor over user assembler files (with a.ssuffix) when assembling them. no preprocessor, no problem โจ-mfix-24k,-mno-fix-24kโ work around the 24K E48 (lost data on stores during refill) errata. The workarounds are implemented by the assembler rather than by GCC. ๐ ๏ธ-mfix-r4000,-mno-fix-r4000โ work 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โ work 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โ work around certain R10000 errata:"ll"/"sc"sequences 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 a"nop"instruction 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. The workaround is implemented by the assembler rather than by GCC. short loop bug? not today ๐-mfix-rm7000,-mno-fix-rm7000โ work around the RM7000"dmult"/"dmultu"errata. The workarounds are implemented by the assembler rather than by GCC. ๐ ๏ธ-mfix-vr4120,-mno-fix-vr4120โ work around certain VR4120 errata:"dmultu"does not always produce the correct result."div"and"ddiv"do 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. These errata are handled by the assembler, not by GCC itself. ๐ญ
-mfix-vr4130โ work around the VR4130"mflo"/"mfhi"errata. The workarounds are implemented by the assembler rather than by GCC, although GCC avoids using"mflo"and"mfhi"if the VR4130"macc","macchi","dmacc"and"dmacchi"instructions are available instead. โจ-mfix-sb1,-mno-fix-sb1โ work around certain SB-1 CPU core errata. (This flag currently works around the SB-1 revision 2"F1"and"F2"floating-point errata.) ๐-mr10k-cache-barrier=settingโ specify whether GCC should insert cache barriers to avoid the side effects of speculation on R10K processors. ๐ง
okay so bestie, listen up ๐ the R10K is out here doing the same thing as lots of other processors: it tries to predict which way a conditional branch is gonna go and then just speculatively runs instructions from the "taken" side. Then if it guessed wrong, it aborts those instructions. BUT โ and this is the tea โ on the R10K, even the aborted instructions can leave side effects. ๐
This whole situation only affects kernel stores, and depending on your system, kernel loads too. Like, for example, a speculatively-executed store might load the target memory into cache and mark that cache line as dirty, even if the store itself gets aborted later. Then if a DMA operation writes to the same area of memory before that "dirty" line gets flushed, the cached data just overwrites the DMA-ed data. ๐ญ For the full rundown, including other potential problems, check the R10K processor manual.
So one workaround? 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 how GCC implements this workaround. It assumes that aborted accesses to any byte in these regions don't 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's the kernel's responsibility to make sure speculative accesses to these regions are actually safe. ๐ซถ
If your input program has a function declaration like:
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, and it expects non-GCC functions (like 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โ Specifies the function to call to flush the I and D caches. 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 number 3 (to flush both caches). The default depends on the target GCC was configured for, but commonly is either_flush_funcor__cpu_flush.-mno-flush-funcโ Don't call any such function to flush the caches. ๐ซmbranch-cost=numโ Set the cost of branches to roughly num "simple" instructions. 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โ Enable 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. An exception is for the MIPS32 and MIPS64 architectures and processors that implement those architectures; for those, Branch Likely instructions are not generated by default because the MIPS32 and MIPS64 architectures specifically deprecate their use.-mno-branch-likelyโ Disable use of Branch Likely instructions, regardless of the default for the selected architecture.
heads up bestie: the MIPS32 and MIPS64 architectures deprecate Branch Likely, so they don't generate them by default. ๐ซ
-mcompact-branches=neverโ Ensures that compact branch instructions will never be generated.-mcompact-branches=optimalโ The default. 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.-mcompact-branches=alwaysโ 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.
These options are supported from MIPS Release 6 onwards. โจ
-mfp-exceptionsโ Specifies that 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.-mno-fp-exceptionsโ Specifies that FP exceptions are disabled. (See the note above about scheduling on the SB-1 and other processors.) ๐๏ธ-mvr4130-alignโ The VR4130 pipeline is two-way superscalar, but 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. 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.-mno-vr4130-alignโ Disable this alignment. ๐-msynciโ Enable 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 usesynci.-mno-synciโ Disable generation ofsynciinstructions. This is the default unless overridden by--with-synci.
warning bestie: on many multi-core (SMP) systems, synci does not invalidate the instruction caches on all cores and may lead to undefined behavior. ๐ฑ
-mrelax-pic-callsโ Try to turn PIC calls that are normally dispatched via register$25into direct calls. This is only possible if the linker can resolve the destination at link time and if the destination is within range for a direct call.-mrelax-pic-callsis the default if GCC was configured to use an assembler and a linker that support the.relocassembly directive and-mexplicit-relocsis in effect. With-mno-explicit-relocs, this optimization can be performed by the assembler and the linker alone without help from the compiler.-mno-relax-pic-callsโ Do not try to turn PIC calls into direct calls. ๐-mmcount-ra-addressโ Emit code that allows_mcountto modify the calling function's return address. When enabled, this option extends the usual_mcountinterface with a new ra-address parameter, which has typeintptr_t *and is passed in register$12._mcountcan then modify the return address by doing both of the following:- Returning the new address in register
$31. - Storing the new address in
*ra-address, if ra-address is nonnull. The default is-mno-mcount-ra-address.
- Returning the new address in register
-mno-mcount-ra-addressโ Do not emit such code. This is the default. ๐ฌ-mframe-header-optโ Enable frame header optimization in the o32 ABI. When using the o32 ABI, calling functions will allocate 16 bytes on the stack for the called function to write out register arguments. When enabled, this optimization will suppress the allocation of the frame header if it can be determined that it is unused. This optimization is off by default at all optimization levels.-mno-frame-header-optโ Disable frame header optimization. This is the default. ๐ผ๏ธ-mlxc1-sxc1โ When applicable, enable the generation oflwxc1,swxc1,ldxc1,sdxc1instructions. Enabled by default.-mno-lxc1-sxc1โ When applicable, disable the generation of those instructions. ๐-mmadd4โ When applicable, enable the generation of 4-operandmadd.s,madd.dand related instructions. Enabled by default.-mno-madd4โ When applicable, disable the generation of those instructions. โ
โจ MMIX Options โจ
These options are defined for the MMIX:
-mlibfuncsโ Specify that intrinsic library functions are being compiled, passing all values in registers, no matter the size.-mno-libfuncsโ Do not specify that. ๐-mepsilonโ Generate floating-point comparison instructions that compare with respect to therEepsilon register.-mno-epsilonโ Do not generate such instructions. ๐-mabi=mmixwareโ Generate code that passes function parameters and return values that (in the called function) are seen as registers$0and up.-mabi=gnuโ Generate code that uses the GNU ABI which uses global registers$231and up. ๐-mzero-extendโ When reading data from memory in sizes shorter than 64 bits, use zero-extending load instructions by default, rather than sign-extending ones.-mno-zero-extendโ Do not use zero-extending load instructions by default; use sign-extending ones instead. 0๏ธโฃ-mknuthdivโ Make the result of a division yielding a remainder have the same sign as the divisor.-mno-knuthdivโ With the default, the sign of the remainder follows the sign of the dividend. Both methods are arithmetically valid, the latter being almost exclusively used. โ-mtoplevel-symbolsโ Prepend a:to all global symbols, so the assembly code can be used with thePREFIXassembly directive.-mno-toplevel-symbolsโ Do not prepend a:. ๐ค-melfโ Generate an executable in the ELF format, rather than the default mmo format used by the mmix simulator. ๐ง-mbranch-predictโ Use the probable-branch instructions, when static branch prediction indicates a probable branch.-mno-branch-predictโ Do not use the probable-branch instructions. ๐ฎ-mbase-addressesโ 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. The register is 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. This means that a program that uses lots of static data may require-mno-base-addresses.-mno-base-addressesโ Do not generate code that uses base addresses. ๐-msingle-exitโ Force generated code to have a single exit point in each function.-mno-single-exitโ 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 the MN10300 processors. This is the default. ๐-mno-mult-bugโ don't emit any code that dodges the buggy multiply instructions on MN10300 processors, bestie. we're just... not doing the workaround. ๐-mam33โ generate code that flexes the features only the AM33 processor has. โจ-mno-am33โ don't use those AM33-only features. this is the default, so it's giving "we're being normal about it". ๐ธ-mam33-2โ generate code using the features specific to the AM33/2.0 processor.-mam34โ generate code using the features specific to the AM34 processor.-mtune=cpu-typeโ when scheduling instructions, use the timing characteristics of whatever CPU type you name. lowkey important: this does not change the targeted processor type, it just tunes. the CPU type has to be one ofmn10300,am33,am33-2oram34, no exceptions. ๐-mreturn-pointer-on-d0โ when you generate a function that returns a pointer, this makes it return the pointer in botha0andd0. otherwise the pointer only comes back ina0, and if you try to call such functions without a prototype you get errors. heads up: this option is on by default, so use-mno-return-pointer-on-d0to turn it off. ๐ซถ-mno-crt0โ do not link in the C run-time initialization object file. bye, crt0.-mrelaxโ tells the linker to run a relaxation optimization pass so branches, calls and absolute memory addresses get shortened. this option only does anything when it's on the command line for the final link step, so don't expect it to do cardio earlier in the build.
fr fr: this option makes symbolic debugging impossible. ๐
-mliwโ lets the compiler generate Long Instruction Word instructions if the target is AM33 or later. this is the default. this option defines the preprocessor macro__LIW__. โจ-mno-liwโ do not let the compiler generate Long Instruction Word instructions. this option defines the preprocessor macro__NO_LIW__.-msetlbโ lets the compiler generate theSETLBandLccinstructions if the target is AM33 or later. this is the default. this option defines the preprocessor macro__SETLB__. ๐-mno-setlbโ do not allowSETLBorLccinstructions. 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. (yes she's back, different target, same energy.)
๐ MSP430 Options ๐
these options are defined for the MSP430:
-masm-hexโ force assembly output to always use hex constants. normally these constants are signed decimals, but this option exists for testsuite and/or aesthetic purposes. it's giving โจvibesโจ.-mmcu=โ pick the MCU to target. this gets used to create a C preprocessor symbol based on the MCU name, converted to upper case and pre- and post-fixed with__. that symbol is then 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 that's known to only support the 430 ISA, then that's what gets 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 gets 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 makes the linker search for a script called xxx.ld.
the ISA and hardware multiply supported for the different MCUs is hard-coded into GCC. but an external devices.csv file can be used to extend device support beyond the hard-coded stuff.
GCC searches for the devices.csv file using the following methods, in this precedence order โ first beats second, second beats third:
- Include path specified with
-Iand-Lโdevices.csvgets 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โ set the global environment variableMSP430_GCC_INCLUDE_DIRto the full path to the directory containingdevices.csv, and GCC will search that directory fordevices.csv. ifdevices.csvis found, this directory also gets registered as an include path and linker library path. so header files and linker scripts in this directory can be used without manually specifying-Iand-Lon 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 created it and copieddevices.csvthere, then the MCU data gets read. as above, this directory also gets 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โ turns warnings on or off 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.
ngl bestie, this option is deprecated. use the -mmcu= option to select the ISA instead. ๐
-msimโ link to the simulator runtime libraries and linker script. this overrides any scripts that would've been selected by the-mmcu=option. main character energy, honestly.-mlargeโ use large-model addressing (20-bit pointers, 20-bitsize_t).-msmallโ use small-model addressing (16-bit pointers, 16-bitsize_t).-mrelaxโ this option gets passed to the assembler and linker, and lets the linker perform certain optimizations that cannot be done until the final link. (she's on her final-link-step timing again, iconic.)mhwmult=โ describes the type of hardware multiply supported by the target. accepted values arenonefor no hardware multiply,16bitfor the original 16-bit-only multiply supported by early MCUs,32bitfor the 16/32-bit multiply supported by later MCUs, andf5seriesfor the 16/32-bit multiply supported by F5-series MCUs. you can also give a value ofauto, which tells GCC to deduce the hardware multiply support based on the MCU name provided by the-mmcuoption. if no-mmcuoption is specified, or if the MCU name isn't recognized, then no hardware multiply support is assumed."auto"is the default setting. ๐
hardware multiplies are normally performed by calling a library routine. this saves space in the generated code. but when compiling at -O3 or higher, the hardware multiplier is invoked inline, which makes for bigger but faster code. ๐ฅ
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. 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. ๐ง-mtiny-printfโ enable reduced code sizeprintfandputslibrary functions.
the tiny implementations of these functions are not reentrant, so they must be used with caution in multi-threaded applications. ๐ญ
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.
this option requires Newlib Nano IO, so GCC must be configured with --enable-newlib-nano-formatted-io.
-mmax-inline-shift=โ this option takes an integer between0and64inclusive, and sets the maximum number of inline shift instructions that 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. โจ
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).
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.
-mcode-region=,-mdata-region=โ these options tell the compiler where to place functions and data that don't 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. ๐ธ-msilicon-errata=โ this option passes on a request to the assembler to enable the fixes for the named silicon errata.-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.-mwarn-devices-csv,-mno-warn-devices-csvโ warn ifdevices.csvis not found or there are problems parsing it (default: on). ๐
๐ NDS32 Options ๐
these options are defined for NDS32 implementations:
-mbig-endianโ generate code in big-endian mode.-mlittle-endianโ generate code in little-endian mode.-mreduced-regsโ use reduced-set registers for register allocation.-mfull-regsโ use full-set registers for register allocation. the full set, bestie. no skimping.-mcmovโ generate conditional move instructions.-mno-cmovโ do not generate conditional move instructions. not today. ๐-mext-perfโ generate performance extension instructions. ๐ฅ-mno-ext-perfโ do not generate performance extension instructions.-mext-perf2โ generate performance extension 2 instructions. โจ-mno-ext-perf2โ bestie, do not emit performance extension 2 instructions. Just say no ๐-mext-stringโ go ahead and generate string extension instructions โจ-mno-ext-stringโ and this one says nope, no string extension instructions.-mv3pushโ generate those v3push25/pop25instructions ๐ซถ-mno-v3pushโ do not generate v3push25/pop25instructions.-m16-bitโ generate 16-bit instructions. tiny but mighty ๐-mno-16-bitโ do not generate 16-bit instructions.-misr-vector-size=numโ sets the size of each interrupt vector. It must be4or16, no in-between, that's the vibe check ๐ซ-mcache-block-size=numโ sets the size of each cache block. Has to be a power of 2, somewhere between4and512inclusive. Math class is in session ๐-march=archโ names the target architecture you want. literally just telling it what it's building for ๐-mcmodel=code-modelโ picks the code model, and the options are:smallโ all the data and read-only data segments have to fit inside a 512KB addressing space, and the text segment has to fit within 16MB addressing space.mediumโ the data segment must be within 512KB, while the read-only data segment can live within 4GB addressing space. The text segment should still be within 16MB addressing space.largeโ everything can breathe: all the text and data segments can be within 4GB addressing space.
-mctor-dtorโ turns on the constructor/destructor feature ๐ฅ-mrelaxโ gently guides the linker to relax instructions. it's giving chill โจ
๐ธ Nios II Options ๐ธ
These are the options defined for the Altera Nios II processor. Yes, a whole dedicated section, because she's special like that ๐
-G numโ puts global and static objects that are less than or equal tonumbytes into the small data or BSS sections instead of the normal data or BSS sections. The default value ofnumis8.-mgpopt=option-mgpopt-mno-gpoptโ generate (or do not generate) GP-relative accesses. Here are the option names it recognizes:noneโ do not generate GP-relative accesses.localโ generate GP-relative accesses for small data objects that are not external, weak, or uninitialized common symbols. Also uses GP-relative addressing for objects that have been explicitly placed in a small data section via a"section"attribute.globalโ same aslocal, but also generates GP-relative accesses for small data objects that are external, weak, or common. If you use this one, you must make sure that all parts of your program (libraries included, bestie) are compiled with the same-Gsetting.dataโ generate GP-relative accesses for all data objects in the program. If you use this, 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.allโ generate GP-relative addresses for function pointers as well as data pointers. If you use this, 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.
-mgpopt is equivalent to -mgpopt=local, and -mno-gpopt is equivalent to -mgpopt=none.
The default is -mgpopt, except when -fpic or -fPIC is specified to generate position-independent code. Heads up: the Nios II ABI does not permit GP-relative accesses from shared libraries ๐
You may need to specify -mno-gpopt explicitly when building programs that include large amounts of small data, including large GOT data sections. In that case, the 16-bit offset for GP-relative addressing may not be large enough to allow access to the entire small data section. so like, watch out ๐ซ
-mgprel-sec=regexpโ specifies additional section names that can be accessed via GP-relative addressing. It's most useful alongside"section"attributes on variable declarations and a custom linker script. Theregexpis a POSIX Extended Regular Expression โจ
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.
-mr0rel-sec=regexpโ 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. Most useful alongside"section"attributes on variable declarations and a custom linker script. Theregexpis a POSIX Extended Regular Expression ๐
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.
-mel-mebโ generate little-endian (that's the default ๐ฅฐ) or big-endian (experimental, spicy ๐ถ๏ธ) code, respectively.-march=archโ this specifies the name of the target Nios II architecture. GCC uses this name to figure out what kind of instructions it can emit when generating assembly code. The permissible names are:r1,r2.
The preprocessor macro "__nios2_arch__" is available to programs, with value 1 or 2, indicating the targeted ISA level. cute, right? ๐
-mbypass-cache-mno-bypass-cacheโ forces 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.-mno-cache-volatile-mcache-volatileโ volatile memory access bypasses the cache using the I/O variants of the load and store instructions. The default is not to bypass the cache.-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.-mno-hw-mul-mhw-mul-mno-hw-mulx-mhw-mulx-mno-hw-div-mhw-divโ enable or disable emitting the"mul","mulx"and"div"family of instructions by the compiler. The default is to emit"mul"and not emit"div"and"mulx".-mbmx-mno-bmx-mcdx-mno-cdxโ enable or disable generation of Nios II R2 BMX (bit manipulation) and CDX (code density) instructions. Enabling these instructions also requires-march=r2. Since these instructions are optional extensions to the R2 architecture, the default is not to emit them ๐ซ-mcustom-insn=N-mno-custom-insnโ each-mcustom-insn=Noption enables use of a custom instruction with encodingNwhen generating code that uses insn. For example,-mcustom-fadds=253generates custom instruction253for single-precision floating-point add operations instead of the default behavior of using a library call. iconic behavior, honestly โจ
The following values of insn are supported. Except as otherwise noted, 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_lroundf"function when-fno-math-errnois used.floatis,floatus,floatid,floatudโ conversion from signed or unsigned integer types to floating-point types.
In addition, 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. okay that's a lot of words but it's important, bestie ๐ซถ
fwrxโ writesrc1into the least significant half ofXandsrc2into the most significant half ofX.fwryโ writesrc1intoY.frdxhi,frdxloโ read the most or least (respectively) significant half ofXand store it indest.frdyโ read the value ofYand store it intodest.
Note that 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.
okay so this one is the โจchoose-your-own-adventureโจ version of the custom instruction thing:
-mcustom-fpu-cfg=nameโ turns on a predefined, named set of custom instruction encodings (peep-mcustom-insnup above if you missed it ๐). Right now, these are the sets that exist:-mcustom-fpu-cfg=60-1is literally equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -fsingle-precision-constant
-mcustom-fpu-cfg=60-2is literally equivalent to:
-mcustom-fmuls=252 -mcustom-fadds=253 -mcustom-fsubs=254 -mcustom-fdivs=255 -fsingle-precision-constant
-mcustom-fpu-cfg=72-3is literally 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 literally 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
bestie, the tea โ custom instruction assignments you give with the individual -mcustom-insn= options override the ones from -mcustom-fpu-cfg=, no matter what order you put them in on the command line. order does not matter, periodt ๐
ngl if you want more local control over which FPU config gets picked, you can use the target("custom-fpu-cfg=name") function attribute or pragma. ๐
fph2 is just short for Nios II Floating Point Hardware 2 Component. heads up though: the custom instructions turned on by -mcustom-fmins=233 and -mcustom-fmaxs=234 are only generated if -ffinite-math-only is specified. and the custom instruction turned on by -mcustom-round=248 is only generated if -fno-math-errno is specified. also, in contrast to all the other configurations, -fsingle-precision-constant is not set here. ๐
These extra -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 it's typically used together with-msys-crt0=to say where the alternate startup code provided by the HAL BSP lives. ๐ซถ-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 the low-level system calls the C library needs, likereadandwrite. 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 kept around for backward compatibility. only 64-bit ABI is supported, iykyk.-misa=ISA-stringโ generate code for the given specified PTX ISA (e.g.sm_35). ISA strings must be lower-case. valid ISA strings includesm_30andsm_35. the default ISA issm_35.-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.-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, it 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 so you can test the compiler; to generate code suitable for linking into programs using OpenMP offloading, use option-mgomp. ๐ฆ-muniform-simtโ switch to the code generation variant that lets you 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 array"int __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 position"tid.y"with the current lane index to compute the master lane index. ๐-mgompโ generate code for use in OpenMP offloading: enables the-msoft-stackand-muniform-simtoptions, and selects the corresponding multilib variant.
๐ธ OpenRISC Options ๐ธ
These options are defined for OpenRISC:
-mboard=nameโ configure a board specific runtime. this gets passed to the linker for newlib board library linking. the default is"or1ksim".-mnewlibโ this option is ignored; it's for compatibility purposes only. it used to select linker and preprocessor options for use with newlib.-msoft-div,-mhard-divโ select software or hardware divide (l.div,l.divu) instructions. the default is hardware divide.-msoft-mul,-mhard-mulโ select software or hardware multiply (l.mul,l.muli) instructions. the default is hardware multiply.-msoft-float,-mhard-floatโ select software or hardware for floating point operations. the default is software.-mdouble-floatโ when-mhard-floatis selected, enables generation of double-precision floating point instructions. by default, functions from libgcc are used to perform double-precision floating point operations.-munordered-floatโ when-mhard-floatis selected, enables generation of unordered floating point compare and set flag (lf.sfun*) instructions. by default, functions from libgcc are used to perform unordered floating point compare and set flag operations.-mcmovโ enable generation of conditional move (l.cmov) instructions. by default the equivalent will be generated using set and branch.-mrorโ enable generation of rotate right (l.ror) instructions. by default, functions from libgcc are used to perform rotate right operations.-mroriโ enable generation of rotate right with immediate (l.rori) instructions. by default, functions from libgcc are used to perform rotate right with immediate operations.-msextโ enable generation of sign extension (l.ext*) instructions. by default memory loads are used to perform sign extension.-msfimmโ enable generation of compare and set flag with immediate (l.sf*i) instructions. by default extra instructions will be generated to store the immediate to a register first.-mshftimmโ enable generation of shift with immediate (l.srai,l.srli,l.slli) instructions. by default extra instructions will be generated to store the immediate to a register first.
๐ PDP-11 Options ๐
These options are defined for the PDP-11:
-mfpuโ use hardware FPP floating point. this is the default. (FIS floating point on the PDP-11/40 is not supported.) implies-m45.-msoft-floatโ do not use hardware floating point.-mac0โ return floating-point results in ac0 (fr0 in 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 old"reload"allocator 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โ enable the compiler to 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, which run faster than when the option isn't used. however, the 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 be generated, for example, when compiling code that performs 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 is generated to indicate that you should rewrite the code to avoid byte operations, or to target an AE type that has the necessary hardware support. this option disables these warnings. ๐ฅ
๐ PowerPC Options ๐
These are listed under
๐ธ PRU Options ๐ธ
okay so if you're out here building for the PRU target, these are YOUR flags bestie, and there are five of them. Buckle up ๐
-minrtโ link with a minimum runtime environment, which means no support for static initializers and constructors. Using this can shrink your final ELF binary a lot, which is giving major glow-up energy for tiny targets โจ. BUT โ and this is the important part โ the compiler could still generate code with static initializers and constructors. Nobody's stopping it. It is up to you, the programmer to make sure your source program doesn't use those features. That's on you, not on GCC, fr fr.-mmcu=mcuโ tells GCC which PRU MCU variant to use. Wanna know the exact list of supported MCUs? Check Newlib. That's where the list lives, go look ๐-mno-relaxโ makes GCC hand the linker--no-relaxinstead of--relax. That's the whole vibe. Passing the opposite flag, basically. ๐-mloopโ allows (or does not allow) GCC to use theLOOPinstruction. Simple as that, no notes ๐-mabi=variantโ pick which ABI variant the code gets generated for.-mabi=tiselects the unmodified TI ABI, while-mabi=gnuselects a GNU variant that copes more naturally with certain GCC assumptions. And here's the tea on how they differ โ:- Function Pointer Size โ TI ABI says function (code) pointers are 16-bit, whereas GNU supports only 32-bit data and code pointers. Not a vibe difference, an actual real difference.
- Optional Return Value Pointer โ when a function returns something bigger than 64 bits, it gets passed using a hidden pointer as the first argument of the function. TI ABI, though, mandates that pointer can be
NULLin case the caller isn't using the returned value. GNU always passes and expects a valid return value pointer. NoNULLshenanigans allowed ๐ซ
The current -mabi=ti implementation simply raises a compile error when any of the above code constructs is detected ๐ญ. And as a consequence of all that, the standard C library cannot be built, and it is omitted when linking with -mabi=ti. So likeโฆ plan accordingly.
Also: relaxation is a GNU feature, and for safety reasons it's disabled when using -mabi=ti. Why? Because the TI toolchain does not emit relocations for QBBx instructions, so the GNU linker cannot adjust them when shortening adjacent LDI32 pseudo instructions. That's the technical reason, and I'm telling you because you deserve to know ๐ซถ
๐ฆ RISC-V Options ๐ฆ
RISC-V girlies rise up, this section is LONG and it's ICONIC, let's go ๐
-mbranch-cost=nโ set the cost of branches to roughly n instructions. That's it, that's the flag โญ-mplt/-mno-pltโ when generating PIC code, do or don't allow the use of PLTs. Ignored for non-PIC (so like, if you're not doing PIC this flag is just sitting there minding its own business ๐). The default is-mplt.-mabi=ABI-stringโ specify integer and floating-point calling convention. TheABI-stringhas two parts: the size of integer types, and the registers used for floating-point types. Example time, because examples ate ๐ :-march=rv64ifd -mabi=lp64dmeans 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. Now contrast that with-march=rv64ifd -mabi=lp64f, which still lets the compiler 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 at all. Wild, right?
The default for this argument is system dependent, so if you want a specific calling convention, specify one explicitly. The valid calling conventions are: ilp32, ilp32f, ilp32d, lp64, lp64f, and lp64d. Heads up though: 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's also the ilp32e ABI that can only be used with the rv32e architecture. That ABI is not well specified at present, and is subject to change โ so treat it like it's still in its experimental era.
-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. Nice โจ-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. Same energy as above ๐-march=ISA-stringโ generate code for the given RISC-V ISA (e.g.rv64im). ISA strings must be lower-case (no shouting allowed ๐ข). Examples includerv64i,rv32g,rv32e, andrv32imaf.
When -march= is not specified, use the setting from -mcpu.
If both -march and -mcpu= are not specified, the default for this argument is system dependent, and users who want specific architecture extensions should specify one explicitly. Periodt.
-mcpu=processor-stringโ use the architecture of and optimize the output for the given processor, specified by a 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. That's the whole roster, no substitutions ๐-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, and the default is rocket if both are not specified ๐
The size choice is not intended for use by end-users. It's 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. It's giving internal-tooling-only, iykyk ๐คซ
-mpreferred-stack-boundary=numโ attempt to keep the stack boundary aligned to a2raised to num byte boundary. If-mpreferred-stack-boundaryis not specified, the default is4(that's 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. Do not mix and match, bestie, it will not end well ๐ญ
-msmall-data-limit=nโ put global and static data smaller than n bytes into a special section (on some targets). Cute little optimization ๐ธ-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. Small and slow, or big and fast โ your call ๐-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 (yes, the polarity is like that, read it twice ๐). 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.-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. (And yes, that second one is spelled-mno-exlicit-relocsin the manual โ keep it exactly like that, I'm not touching it ๐)-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. Chill vibes, linker does the work ๐ง-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 for type arexlen, which uses x register width as the alignment value, andnatural, which 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 a canary at guard. Supported locations areglobalfor a global canary, ortlsfor a 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 ๐ง So like, if you're not in the kernel, this probably isn't your moment.
๐ RL78 Options ๐
tiny microcontroller time, let's get into it ๐ง
-msimโ links in additional target libraries to support operation within a simulator. Perfect for when you're not on real hardware yet ๐ฎ-mmul=none/-mmul=g10/-mmul=g13/-mmul=g14/-mmul=rl78โ specifies the type of hardware multiplication and division support to be used. Let me break it down ๐ :- 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".
- The simplest is
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. And the G10 or S1 core does not have register banks, so it uses a different calling convention ๐ Different core, different rules, that's the whole story.
So like, if this option is set it also picks which flavor of hardware multiply support you're getting, unless an explicit -mmul=none on the command line says "no bestie, not today". So specifying -mcpu=g13 enables the use of the G13 hardware multiply peripheral, and specifying -mcpu=g10 disables the use of hardware multiplications altogether. โจ
Okay so here's the tea โ: even though the RL78/G14 core is the default target, actually passing -mcpu=g14 or -mcpu=rl78 on the command line does change the behavior of the toolchain, because it also enables G14 hardware multiply support. And if those options are not specified on the command line? Then software multiplication routines get used, even though the code targets the RL78 core. Why? Backwards compatibility with older toolchains that didn't have hardware multiply and divide support. iykyk ๐
Plus a C preprocessor macro gets defined based on the setting of this option. Possible values are: __RL78_G10__, __RL78_G13__ or __RL78_G14__.
-mg10,-mg13,-mg14,-mrl78โ these are literally just aliases for the matching-mcpu=option. They exist for backwards compatibility, bestie. ๐ซถ-mallregsโ lets the compiler use all of the available registers. By defaultr24..r31are reserved for use in interrupt handlers. Turn this on and those registers can be used in ordinary functions too. ๐ฅ-m64bit-doubles,-m32bit-doublesโ makes 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โ says 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, because that makes the interrupt handlers faster. โก The target option-mg13needs to be passed for this to work, since 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 if 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 to specify which instructions are available on the processor you're using. The default value of these options is determined when configuring GCC. Specifying-mcpu=cpu_typeoverrides the specification of these options. We recommend you use the-mcpu=cpu_typeoption rather than the options listed above. Periodt.
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.
The -mmfcrf option allows GCC to generate the move from condition register field instruction implemented on the POWER4 processor and other processors that support the PowerPC V2.01 architecture. The -mpopcntb option allows GCC to 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. The -mpopcntd option allows GCC to generate the popcount instruction implemented on the POWER7 processor and other processors that support the PowerPC V2.06 architecture. The -mfprnd option allows GCC to generate the FP round to integer instructions implemented on the POWER5+ processor and other processors that support the PowerPC V2.03 architecture. The -mcmpb option allows GCC to generate the compare bytes instruction implemented on the POWER6 processor and other processors that support the PowerPC V2.05 architecture. The -mhard-dfp option allows GCC to generate the decimal floating-point instructions implemented on some POWER processors.
The -mpowerpc64 option allows GCC to generate the additional 64-bit instructions that are found in the full PowerPC64 architecture, and to treat GPRs as 64-bit, doubleword quantities. GCC defaults to -mno-powerpc64.
-mcpu=cpu_typeโ set architecture type, register usage, and instruction scheduling parameters for machine type cpu_type. ๐ Supported values for cpu_type are401,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, andnative.
-mcpu=powerpc, -mcpu=powerpc64, and -mcpu=powerpc64le specify 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 native as cpu type detects and selects the architecture option that corresponds to the host processor of the system performing the compilation. -mcpu=native has 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. ๐ญ
The -mcpu options 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 -mcpu option, like -mcpu=970 -mno-altivec.
On AIX, the -maltivec and -mpowerpc64 options are not enabled or disabled by the -mcpu option 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โ set the instruction scheduling parameters for machine type cpu_type, but do not set the architecture type or register usage the way-mcpu=cpu_typedoes. The same values for cpu_type are used for-mtuneas for-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 to 64k.-mcmodel=mediumโ generate PowerPC64 code for the medium model: the TOC and other static data may be up to a total of 4G in size. This is the default for 64-bit Linux.-mcmodel=largeโ generate PowerPC64 code for the large model: the TOC may be up to 4G in 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 keep) 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โ turns on (or off) codegen that uses the atomic quad word memory instructions, bestie. Heads up though:-mquad-memory-atomicrequires 64-bit mode, no exceptions ๐-mfloat128,-mno-float128โ enables/disables the__float128keyword for IEEE 128-bit floating point, and picks between software emulation and actual hardware instructions for it.
Okay so the tea โ: the VSX instruction set (-mvsx) must be enabled to use IEEE 128-bit floating point support at all, and it's only supported on Linux.
Default vibe check: -mfloat128 is enabled on PowerPC Linux systems using the VSX instruction set, and disabled everywhere else.
Now if you're on a 64-bit system and you use the ISA 3.0 instruction set (-mpower9-vector or -mcpu=power9), the IEEE 128-bit floating point support also unlocks generation of ISA 3.0 IEEE 128-bit floating point instructions. Otherwise โ if you don't ask for ISA 3.0 instructions, or you're targeting a 32-bit big endian system โ IEEE 128-bit floating point gets done with software emulation, periodt.
-mfloat128-hardware,-mno-float128-hardwareโ enable/disable using ISA 3.0 hardware instructions to support the__float128data type. The default 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 (GNU/Linux included, bestie). 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, exactly like-mpowerpc64does ๐-mfull-toc,-mno-fp-in-toc,-mno-sum-in-toc,-mminimal-tocโ these modify generation of the TOC (Table Of Contents), which gets created for every executable file.-mfull-tocis the default pick. In that case, GCC allocates at least one TOC entry for each unique non-automatic variable reference in your program, and it also drops floating-point constants into the TOC. Sad part: only 16,384 entries are available in the TOC ๐ญ
So if the linker yells at you that you've overflowed the available TOC space, you can shrink how much TOC you're eating with -mno-fp-in-toc and -mno-sum-in-toc. -mno-fp-in-toc stops GCC from putting floating-point constants in the TOC, and -mno-sum-in-toc forces GCC to generate code that calculates the sum of an address and a constant at run time instead of stuffing that sum into the TOC. You can specify one or both. Either one makes GCC produce very slightly slower and larger code, in exchange for conserving TOC space.
Still out of TOC space even with both? Then specify -mminimal-toc instead. This one makes GCC create only one TOC entry per file. When you use it, GCC produces code that's slower and larger, but uses extremely little TOC space. Pro tip vibe: you might only want this on files that contain less frequently-executed code ๐ซถ
-maix64,-maix32โ enable 64-bit AIX ABI and calling convention: 64-bit pointers, 64-bitlongtype, and all the infrastructure needed to support them. Specifying-maix64implies-mpowerpc64, while-maix32disables the 64-bit ABI and implies-mno-powerpc64. GCC defaults to-maix32โจ-mxl-compat,-mno-xl-compatโ produce code that conforms more closely to IBM XL compiler semantics when using AIX-compatible ABI. It passes floating-point arguments to prototyped functions beyond the register save area (RSA) on the stack in addition to argument FPRs. It does not assume that the most significant double in a 128-bitlong doublevalue is properly rounded when comparing values and converting todouble. And it uses XL symbol names forlong doublesupport routines.
Story time ๐: the AIX calling convention was extended but not initially documented, to handle an obscure K&R C case of calling a function that takes the address of its arguments with fewer arguments than declared. IBM XL compilers access floating-point arguments that don't fit in the RSA from the stack when a subroutine is compiled without optimization. Because 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 calling subroutines compiled by IBM XL compilers without optimization.
-mpeโ support IBM RS/6000 SP Parallel Environment (PE). It links an application written to use message passing with special startup code so the application can actually run. The system must have PE installed in the standard location/usr/lpp/ppe.poe/, or the specs file has to be overridden with the-specs=option to point at the appropriate directory location. Also: the Parallel Environment does not support threads, so-mpeand-pthreadare incompatible ๐ซ-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) and aligns them on their natural size-based boundary.-malign-powertells GCC to follow the ABI-specified alignment rules. 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โ generate code that does not use (uses) the floating-point register set. Software floating-point emulation is provided if you use-msoft-float, and you must pass the option to GCC when linking too, iykyk.-mmultiple,-mno-multipleโ generate code that uses (does not use) the load multiple word instructions and the store multiple word instructions. These are 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 are PPC740 and PPC750, which permit these instructions in little-endian mode.-mupdate,-mno-updateโ generate code that uses (does not use) the load or store instructions that update the base register to the address of the calculated memory location. These are generated by default. If you use-mno-update, there's a small window between when the stack pointer gets 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โ generate code that tries to avoid (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โ generate code that uses (does not use) the floating-point multiply and accumulate instructions. These are generated by default if hardware floating point is used. Note the glow-up: 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โ generate code that uses (does not use) the half-word multiply and multiply-accumulate instructions on the IBM 405, 440, 464 and 476 processors. These instructions are generated by default when targeting those processors.-mdlmzb,-mno-dlmzbโ generate code that uses (does not 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, do not (do) force structures and unions that contain bit-fields to be aligned to the base type of the bit-field.
Example time ๐: 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. With -mno-bit-align, that structure is aligned to a 1-byte boundary and is 1 byte in size. Slay.
-mno-strict-align,-mstrict-alignโ on System V.4 and embedded PowerPC systems, do not (do) assume that unaligned memory references are handled by the system.-mrelocatable,-mno-relocatableโ generate code that allows (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 actually 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 let static executables 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, do not (do) 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, compile code for the processor in little-endian mode. The-mlittle-endianoption is the same as-mlittle, no cap.-mbig,-mbig-endianโ on System V.4 and embedded PowerPC systems, compile code for the processor in big-endian mode. The-mbig-endianoption is the same as-mbig, fr fr.-mdynamic-no-picโ on Darwin and Mac OS X systems, compile code so that it is not relocatable, but so that its external references are relocatable. The resulting code is suitable for applications, but not shared libraries ๐-msingle-pic-baseโ okay so this one says: treat the register you use for PIC addressing as read-only ๐ instead of loading it up in the prologue of every single function. The runtime system is the one responsible for initializing this register with a suitable value before execution even begins. no cap, that's on them ๐ซถ-mprioritize-restricted-insns=priorityโ this controls the priority handed out to dispatch-slot restricted instructions during the second scheduling pass โจ. priority takes the value0,1, or2to assign no, highest, or second-highest priority (respectively) to dispatch-slot restricted instructions. pick your fighter bestie ๐-msched-costly-dep=dependence_typeโ this one decides which dependences the target considers costly while it's doing instruction scheduling ๐. 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 costlystore_to_loadโ any dependence from store to load is costlynumberโ any dependence whose latency is greater than or equal to number is costly
-minsert-sched-nops=schemeโ this controls which NOP insertion scheme gets used during the second scheduling pass ๐ธ. scheme takes one of these values:noโ don't insert NOPs, we're doing nothing ๐ซpadโ pad with NOPs any dispatch group that has vacant issue slots, according to the scheduler's groupingregroup_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 groupingnumberโ 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, compile 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โ specify both-mcall-sysvand-meabioptions. two-for-one, we love a bundle ๐-mcall-sysv-noeabiโ specify both-mcall-sysvand-mno-eabioptions โจ-mcall-aixdescโ on System V.4 and embedded PowerPC systems, compile code for the AIX operating system ๐-mcall-linuxโ on System V.4 and embedded PowerPC systems, compile code for the Linux-based GNU system ๐ง-mcall-freebsdโ on System V.4 and embedded PowerPC systems, compile code for the FreeBSD operating system ๐ฅ-mcall-netbsdโ on System V.4 and embedded PowerPC systems, compile code for the NetBSD operating system ๐-mcall-openbsdโ on System V.4 and embedded PowerPC systems, compile code for the OpenBSD operating system ๐ก-mtraceback=traceback_typeโ select the type of traceback table ๐. Valid values for traceback_type arefull,part, andno.-maix-struct-returnโ return all structures in memory (as specified by the AIX ABI) ๐พ-msvr4-struct-returnโ return structures smaller than 8 bytes in registers (as specified by the SVR4 ABI) โจ-mabi=abi-typeโ extend the current ABI with a particular extension, or remove such an extension ๐ฆ. Valid values are:altivec,no-altivec,ibmlongdouble,ieeelongdouble,elfv1,elfv2, and for AIX:vec-extabi,vec-default.-mabi=ibmlongdoubleโ change the current ABI to use IBM extended-precisionlong double. This is not likely to work if your system defaults to using IEEE extended-precisionlong double๐ญ. If you change thelong doubletype from IEEE extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. Requires-mlong-double-128to be enabled โ ๏ธ-mabi=ieeelongdoubleโ change the current ABI to use IEEE extended-precisionlong double. This is not likely to work if your system defaults to using IBM extended-precisionlong double๐ญ. If you change thelong doubletype from IBM extended-precision, the compiler will issue a warning unless you use the-Wno-psabioption. Requires-mlong-double-128to be enabled โ ๏ธ-mabi=elfv1โ change the current ABI to use 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 ๐ iconic honestly, but don't.-mabi=elfv2โ change the current ABI to use the ELFv2 ABI โจ. This is the default ABI for little-endian PowerPC 64-bit Linux. Overriding the default ABI requires special system support and is likely to fail in spectacular ways ๐ same energy, same warning bestie.-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 ๐ท๏ธ-mprototype-mno-prototypeโ on System V.4 and embedded PowerPC systems, assume that all calls to variable argument functions are properly prototyped ๐. Otherwise, the compiler must 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 that 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 that the startup module is calledcrt0.oand the standard C libraries arelibmvme.aandlibc.a๐-madsโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibads.aandlibc.aโจ-myellowknifeโ on embedded PowerPC systems, assume that the startup module is calledcrt0.oand the standard C libraries arelibyk.aandlibc.a๐ก๐ช (yes that's literally the name, we love it)-mvxworksโ on System V.4 and embedded PowerPC systems, specify that you are compiling for a VxWorks system ๐-membโ on embedded PowerPC systems, set thePPC_EMBbit 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 ๐ง. Selecting-meabimeans that the stack is aligned to an 8-byte boundary, a function__eabiis called frommainto set up the EABI environment, and the-msdataoption can use bothr2andr13to point to two separate small data areas. Selecting-mno-eabimeans that the stack is aligned to a 16-byte boundary, no EABI initialization function is called frommain, and the-msdataoption only usesr13to 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 initializedconstglobal and static data in the.sdata2section, which is pointed to by registerr2๐. Put small initialized non-constglobal and static data in the.sdatasection, which is pointed to by registerr13. Put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. The-msdata=eabioption is incompatible with the-mrelocatableoption โ ๏ธ. The-msdata=eabioption also sets the-memboption.-msdata=sysvโ on System V.4 and embedded PowerPC systems, put small global and static data in the.sdatasection, which is pointed to by registerr13โจ. Put small uninitialized global and static data in the.sbsssection, which is adjacent to the.sdatasection. The-msdata=sysvoption is incompatible with the-mrelocatableoption โ ๏ธ-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 registerr13to address small data however ๐ . 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 as well ๐. This is the default.-mblock-move-inline-limit=numโ inline all block moves (such as calls tomemcpyor structure copies) 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 (such as calls tomemcmpor structure compares) less than or equal to num bytes ๐ง. If num is0, 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 is not constant, at most num bytes will be compared beforememcmpis 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 is not found at the end of the inline compare, a call tostrcmporstrncmpwill take 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 is8. The-G numswitch is also passed to the linker. All modules should be compiled with the same-G numvalue โ no mixing, bestie, keep it consistent ๐-mregnames,-mno-regnamesโ on System V.4 and embedded PowerPC systems, do (or don't) spit out register names in the assembly output using symbolic forms. ๐-mlongcall,-mno-longcallโ by default, assume every single call is far away, so a longer and wayyy more expensive calling sequence is needed. This is required for calls farther than 32 megabytes (33,554,432 bytes) from the current location. A short call gets generated if the compiler knows the call can't possibly be that far. This setting can be overridden by theshortcallfunction attribute, or by#pragma longcall(0).
Some linkers can detect out-of-range calls and generate glue code on the fly. On those systems, long calls are unnecessary and just generate slower code. As of this writing, the AIX linker can do this, and so can the GNU linker for PowerPC/64. There's a plan to add this feature to the GNU linker for 32-bit PowerPC systems too.
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 don't 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.-mpltseqcode and-mbss-plt32-bit PowerPC relocatable objects may not be linked together. ๐ซ-mtls-markers,-mno-tls-markersโ mark (or don't mark) calls to__tls_get_addrwith a relocation specifying the function argument. The relocation lets the linker reliably associate a function call with argument setup instructions for TLS optimization, which in turn lets GCC better schedule the sequence.-mrecip,-mno-recipโ this option enables use of the reciprocal estimate and reciprocal square root estimate instructions with additional Newton-Raphson steps to bump up precision, instead of doing a divide or square root and divide for floating-point arguments. You should use the-ffast-mathoption when using-mrecip(or at least-funsafe-math-optimizations,-ffinite-math-only,-freciprocal-mathand-fno-trapping-math). Heads up tho โ while the throughput of the sequence is generally 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 of 1.0 equals 0.99999994) for reciprocal square roots. ๐ฌ-mrecip=optโ this one controls which reciprocal estimate instructions may be used.optis a comma-separated list of options, which may be preceded by a!to invert the option: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, for example, -mrecip=all,!rsqrtd enables all of the reciprocal estimate instructions, except for the FRSQRTE, XSRSQRTEDP, and XVRSQRTEDP instructions which handle the double-precision reciprocal square root calculations. ๐ฏ
-mrecip-precision,-mno-recip-precisionโ assume (or don't assume) that the reciprocal estimate instructions provide higher-precision estimates than is mandated by the PowerPC ABI. Selecting-mcpu=power6,-mcpu=power7or-mcpu=power8automatically selects-mrecip-precision. The double-precision square root estimate instructions are not generated by default on low-precision machines, since they don't provide an estimate that converges after three steps.-mveclibabi=typeโ specifies the ABI type to use for vectorizing intrinsics using an external library. The only type supported at present ismass, which says to use IBM's Mathematical Acceleration Subsystem (MASS) libraries for vectorizing intrinsics using external libraries. 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, andtanhf4when generating code for power7. Both-ftree-vectorizeand-funsafe-math-optimizationsmust also be enabled. The MASS libraries must be specified at link time. ๐-mfriz,-mno-frizโ generate (or don't generate) thefrizinstruction when the-funsafe-math-optimizationsoption is used to optimize rounding of floating-point values to 64-bit integer and back to floating point. Thefrizinstruction does not return the same value if the floating-point number is too large to fit in an integer. ๐-mpointers-to-nested-functions,-mno-pointers-to-nested-functionsโ generate (or don't generate) 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, TOC value to be loaded in registerr2, and static chain value to be loaded in registerr11. The-mpointers-to-nested-functionsis on by default. 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 generate) 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. The-mno-save-toc-indirectoption is the default.-mcompat-align-parm,-mno-compat-align-parmโ generate (or don't generate) 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. This is corrected in more recent versions of GCC. This option may be used to generate code that's compatible with functions compiled with older versions of GCC.
The -mno-compat-align-parm option 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 canary at guard. Supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default with GNU libc version 2.4 or later). ๐ค
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. The default for those is as specified in the relevant ABI. -mstack-protector-guard-symbol=symbol overrides the offset with a symbol reference to a canary in the TLS block.
-mpcrel,-mno-pcrelโ generate (or don't generate) pc-relative addressing. The-mpcreloption requires that the medium code model (-mcmodel=medium) and prefixed addressing (-mprefixed) options are enabled.-mprefixed,-mno-prefixedโ generate (or don't generate) 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 generate) the MMA instructions. The-mmaoption requires that the option-mcpu=power10(or later) is enabled.-mrop-protect,-mno-rop-protectโ generate (or don't generate) 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 generate) code that will run in privileged state. ๐-mblock-ops-unaligned-vsx,-mno-block-ops-unaligned-vsxโ generate (or don't generate) unaligned vsx loads and stores for inline expansion ofmemcpyandmemmove.
๐ RX Options ๐
These command-line options are defined for RX targets:
-m64bit-doubles,-m32bit-doublesโ ok so this is literally just choosing how big thedoubledata type is ๐-m64bit-doublesmakes it 64 bits,-m32bit-doublesmakes it 32 bits. The default is-m32bit-doubles, and bestie there's a reason: the RX floating-point hardware only works on 32-bit values. that's the whole tea ๐ซ-fpu,-nofpuโ turns the RX floating-point hardware on (-fpu) or off (-nofpu). Default is on for the RX600 series and off for the RX200 series. but here's the catch: floating-point instructions are only generated for 32-bit floating-point values, so the FPU hardware is not used for doubles if you went and used-m64bit-doubles.
โ ๏ธ Note: if-fpuis enabled then-funsafe-math-optimizationsis also enabled automatically. Why? because the RX FPU instructions are themselves unsafe ๐ญ no cap.
-mcpu=nameโ picks which type of RX CPU you're targeting. Currently three types are supported: the generic RX600 and RX200 series hardware, plus the specific RX610 CPU. Default is RX600. The only difference between RX600 and RX610 is that the RX610 does not support theMVTIPLinstruction ๐ and the RX200 series has no hardware floating-point unit at all, so-nofpugets enabled by default when you pick that type.-mbig-endian-data,-mlittle-endian-dataโ stores data (not code, bestie, only data) in big-endian format. Default is-mlittle-endian-data, i.e. data gets stored in the little-endian format โจ-msmall-data-limit=Nโ sets the max size in bytes of global and static variables that can get 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 is up to the programmer to make sure the area does not overflow ๐ซ also, when the small data area is used, one of the RX's registers (usuallyr13) is reserved for pointing to this area, so it's no longer available for the compiler to use. which could mean slower and/or larger code if variables get pushed onto the stack instead of being held in this register.
๐ Note: common variables (the ones that have not been initialized) and constants are not placed into the small data area, because they are assigned to other sections in the output executable.
The default value is zero, which disables this feature. and 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 is of benefit to their program ๐ง see the description of the -mpid option for 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โ when generating assembler output, use a syntax that's compatible with Renesas's AS100 assembler. This syntax can also be handled by the GAS assembler, but it has some restrictions so it is not generated by default ๐-mmax-constant-size=Nโ specifies the maximum size, in bytes, of a constant that can be used as an operand in an RX instruction. So like, the RX instruction set does allow constants up to 4 bytes long to be used in instructions, but a longer value equates to a longer instruction. so in some circumstances it can be beneficial to restrict the size of constants used in instructions. constants that are too big instead get placed into a constant pool and referenced via register indirection โจ The value N can be between 0 and 4. a value of 0 (the default) or 4 means that constants of any size are allowed.-mrelaxโ enable linker relaxation ๐ฅ which is a process whereby the linker attempts to reduce the size of a program by finding shorter versions of various instructions. Disabled by default.-mint-register=Nโ specify the number of registers to reserve for fast interrupt handler functions. The value N can be between 0 and 4. a value of 1 means registerr13is reserved for the exclusive use of fast interrupt handlers. a value of 2 reservesr13andr12. a value of 3 reservesr13,r12andr11, and a value of 4 reservesr13throughr10. a value of 0, the default, does not reserve any registers ๐-msave-acc-in-interruptsโ specifies that 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.
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. so 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, because 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,SUNTIL,SWHILEand 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 useJSR, but 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. iykyk ๐
๐ฆ S/390 and zSeries Options ๐ฆ
these are the -m options defined for the S/390 and zSeries architecture, bestie, and there's a whole lil family of them ๐
-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-stackand-mhard-floatis 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โ turn the packed stack layout on (or off). With-mno-packed-stack, the compiler uses all the fields of that 96/160 byte register save area for their default purpose only โ and yeah, unused fields still eat up stack space, no refunds ๐. With-mpacked-stack, the register save slots get densely packed at the top of the register save area and the leftover space gets reused for other stuff, so you're making way better use of the stack you've got. BUT โ 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. Rules are rules bestie ๐
As long as the stack frame backchain isn't used, code generated with -mpacked-stack is call-compatible with code generated with -mno-packed-stack. Lowkey important note though: 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. That 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. If you wanna build a linux kernel, use -msoft-float.
The default is to not use the packed stack layout.
-msmall-exec,-mno-small-execโ generate (or don't 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โ with-m31you get code compliant to the GNU/Linux for S/390 ABI. With-m64you get code compliant to the GNU/Linux for zSeries ABI. This is what lets GCC in particular generate 64-bit instructions ๐. For the s390 targets the default is-m31, while s390x targets default to-m64.-mzarch,-mesaโ-mzarchmeans generate code using the instructions available on z/Architecture.-mesameans generate code using the instructions available on ESA/390. Heads up:-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. If 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โ the-mzvectoroption enables vector language extensions and builtins using instructions available with the vector extension facility introduced with the IBM z13 machine generation. This option adds support forvectorto be used as a keyword to define vector type variables and arguments.vectoris only available when GNU extensions are enabled. It will not be expanded when requesting strict standard compliance, e.g. with-std=c99. On top of the GCC low-level builtins,-mzvectorenables a set of builtins added for compatibility with AltiVec-style implementations like Power and Cell. To make use of these builtins, the header filevecintrin.hneeds to be included.-mzvectoris disabled by default.-mmvcle,-mno-mvcleโ generate (or do not generate) code using themvcleinstruction to perform block moves. When-mno-mvcleis specified, use amvcloop instead. This is the default unless optimizing for size.-mdebug,-mno-debugโ print (or don't print) additional debug information when compiling. The default is to not print debug information.- *
-march=cpu-type* โ generate code that runs on cpu-type, which is the name of a system representing a certain processor type. 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 cpu type can be used to select the best architecture option for the host processor. -march=native has no effect if GCC does not recognize the processor.
- *
-mtune=cpu-type* โ tune to cpu-type everything applicable about the generated code, 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 the value used for-march. -mtpf-trace,-mno-tpf-traceโ generate code that adds (does not add) in TPF OS specific branches to trace routines in the operating system. This option is off by default, even when compiling for the TPF OS.-mtpf-trace-skip,-mno-tpf-trace-skipโ generate code that changes (does not change) the default branch targets enabled by-mtpf-traceto point to specialized trace routines providing the ability of selectively skipping function trace entries for the TPF OS. This option is off by default, even when compiling for the TPF OS and specifying-mtpf-trace.-mfused-madd,-mno-fused-maddโ generate code that uses (does not 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 exceeds the given frame size. Because this is a compile-time check it doesn't need to be a real problem when the program runs. It is intended to identify functions that most probably cause a stack overflow. It is useful to be used in an environment with limited stack size, e.g. the linux kernel. -mwarn-dynamicstackโ emit a warning if the function callsallocaor uses dynamically-sized arrays. This is generally a bad idea with a limited stack size ๐ฌ.- *
-mstack-guard=stack-guard*,-mstack-size=stack-size โ if these options are provided, the S/390 back end emits additional instructions in the function prologue that trigger a trap if the stack size is stack-guard bytes above the stack-size (remember that the stack on S/390 grows downward). 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 be used to help debugging stack overflow problems. The additionally emitted code causes only little overhead and hence 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. In order to be efficient, the extra code makes the assumption that the stack starts at an address aligned to the value given by stack-size. The stack-guard option can only be used in conjunction 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 is 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 ofbcnzinstructions.-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 without 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 without 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. (so likeโฆ it's giving "same vibe, extra garnish" ๐)-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. Heads up bestie: this changes the calling conventions, and thus some functions from the standard C library do not 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 inswitchtables. The default is to use 16-bit offsets.-mbitopsโ Enable the use of bit manipulation instructions on SH2A.-mfmovdโ Enable the use of the instructionfmovd. 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 theMACregister as call-clobbered, even if-mrenesasis given.-mieee,-mno-ieeeโ Control the IEEE compliance of floating-point comparisons, which affects the handling of cases 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โ Inline code to invalidate instruction cache entries after setting up nested function trampolines. This option has no effect if-musermodeis in effect and the selected code generation option (e.g.-m4) does not allow the use of theicbiinstruction. If the selected code generation option does not allow the use of theicbiinstruction, and-musermodeis not in effect, the inlined code manipulates the instruction cache address array directly with an associative write. This not only requires privileged mode at run time, but it also fails if the cache line had been mapped via the TLB and has become unmapped. fr fr, read that twice ๐-misizeโ Dump instruction size and location in the assembly code.-mpadstructโ This option is deprecated. It pads structures to multiple of 4 bytes, which is incompatible with the SH ABI. don't use it, bestie ๐- *
-matomic-model=model* โ Sets the model of atomic operations and additional parameters as a comma separated list. For details on the atomic built-in functions see __atomic Builtins. The following models and parameters are supported:noneโ Disable compiler generated atomic sequences and emit library calls for atomic operations. This is the default if the target is notsh*-*-linux*.soft-gusaโ Generate GNU/Linux compatible gUSA software atomic sequences for the atomic built-in functions. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for SH3* and SH4* single-core systems. This option is enabled by default when the target issh*-*-linux*and SH3* or SH4*. When the target is SH4A, this option also partially utilizes the hardware atomic instructionsmovli.landmovco.lto create more efficient code, unless strict is specified.soft-tcbโ Generate software atomic sequences that use a variable in the thread control block. This is a variation of the gUSA sequences which can also be used on SH1* and SH2* targets. The generated atomic sequences require additional support from the interrupt/exception handling code of the system and are only suitable for single-core systems. When using this model, thegbr-offset=parameter has to be specified as well.soft-imaskโ Generate software atomic sequences that temporarily disable interrupts by settingSR.IMASK = 1111. This model works only when the program runs in privileged mode and is only suitable for single-core systems. Additional support from the interrupt/exception handling code of the system is not required. This model is enabled by default when the target issh*-*-linux*and SH1* or SH2*.hard-llcsโ Generate hardware atomic sequences using themovli.landmovco.linstructions only. This is only available on SH4A and is suitable for multi-core systems. Since the hardware instructions support only 32 bit atomic variables access to 8 or 16 bit variables is emulated with 32 bit accesses. Code compiled with this option is also compatible with other software atomic model interrupt/exception handling systems if executed on an SH4A system. Additional support from the interrupt/exception handling code of the system is not required for this model.gbr-offset=โ This parameter specifies the offset in bytes of the variable in the thread control block structure that should be used by the generated atomic sequences when the soft-tcb model has been selected. For other models this parameter is ignored. The specified value must be an integer multiple of four and in the range 0-1020.strictโ This parameter prevents mixed usage of multiple atomic models, even if they are compatible, and makes the compiler generate atomic sequences of the specified model only.
-mtasโ Generate thetas.bopcode for__atomic_test_and_set. Notice that depending on the particular hardware and software configuration this can degrade overall performance due to the operand cache line flushes that are implied by thetas.binstruction. On multi-core SH4A processors thetas.binstruction must be used with caution since it can result in data corruption for certain cache configurations. data corruption?? not the vibe ๐ญ-mprefergotโ When generating position-independent code, emit function calls using the Global Offset Table instead of the Procedure Linkage Table.-musermode,-mno-usermodeโ Don't allow (allow) the compiler generating privileged mode code. Specifying-musermodealso implies-mno-inline-ic_invalidateif the inlined code would not work in user mode.-musermodeis the default when the target issh*-*-linux*. If the target is SH1* or SH2*-musermodehas no effect, since there is no user mode.- *
-multcost=number* โ Set the cost to assume for a multiply insn. - *
-mdiv=strategy* โ Set the division strategy to be used for integer division operations. strategy can be one of:call-div1โ Calls a library function that uses the single-step division instructiondiv1to perform the operation. 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 performs the operation in double precision floating point. Division by zero causes a floating-point exception. This is the default for SHcompact with FPU. Specifying this for targets that do not have a double precision FPU 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. Specifying this for targets that do not have dynamic shift instructions defaults tocall-div1.
When a division strategy has not been specified the default strategy is selected based on the current target. For SH2A the default strategy is to use the divs and divu instructions instead of library function calls. lookup tables? we love a girl who plans ahead โจ
-maccumulate-outgoing-argsโ Reserve space once for outgoing arguments in the function prologue rather than around each call. Generally beneficial for performance and size. Also needed for unwinding to avoid changing the stack frame around conditional code.- *
-mdivsi3_libfunc=name* โ Set 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 same sets of input/output/clobbered registers as if this option were not present. - *
-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. kernel girlies, this one's for you ๐ -mbranch-cost=numโ bestie, this tells the compiler "okay so a branch instruction costs num, that's the vibe." Higher numbers make it try harder to spit out branch-free code whenever it can. If you don't specify anything, the value gets picked based on whatever processor type you're compiling for. ๐-mzdcbranch,-mno-zdcbranchโ assume (or like, don't assume) that the zero displacement conditional branch instructionsbtandbfare fast. With-mzdcbranch, the compiler prefers zero displacement branch code sequences. It's on by default when generating code for SH4 and SH4A, and you can turn it off explicitly with-mno-zdcbranch.-mcbranch-force-delay-slotโ forces the usage of delay slots for conditional branches, which stuffs the delay slot with anopif no suitable instruction can be found. By default this option is disabled. You can enable it to work around hardware bugs, like the ones found in the original SH7055. ๐-mfused-madd,-mno-fused-maddโ generate code that uses (or doesn't use) the floating-point multiply and accumulate instructions. These get generated by default if hardware floating point is used. Heads up though: 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 from emitting thefscainstruction for sine and cosine approximations. The option-mfscamust be used in combination with-funsafe-math-optimizations. It's 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 from emitting thefsrrainstruction for reciprocal square root approximations. The option-mfsrramust be used in combination with-funsafe-math-optimizationsand-ffinite-math-only. It's enabled by default when generating code for SH4A. Using-mno-fsrradisables reciprocal square root approximations even if-funsafe-math-optimizationsand-ffinite-math-onlyare in effect.-mpretend-cmoveโ prefer zero-displacement conditional branches for conditional move instruction patterns. This can result in faster code on the SH4 processor. ๐-mfdpicโ generate code using the FDPIC ABI.
๐ Solaris 2 Options ๐
These -m options are supported on Solaris 2:
-mclear-hwcapโ tells the compiler to remove the hardware capabilities generated by the Solaris assembler. This is only necessary when object files use ISA extensions not supported by the current machine, but check at runtime whether or not to use them. ๐-mimpure-textโ used in addition to-shared, tells the compiler to not 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 suppresses the relocations remain against allocatable but non-writable sections linker error message. However, the necessary relocations trigger copy-on-write, and the shared object is not actually shared across processes.
Instead of using-mimpure-text, you should compile all source code with-fpicor-fPIC. Like, genuinely. Do that instead. ๐
These switches are supported in addition to the above on Solaris 2:
-pthreadsโ this is a synonym for-pthread. โจ
๐ SPARC Options ๐
These -m options are supported on the SPARC:
-mno-app-regs,-mapp-regsโ specify-mapp-regsto generate output using the global registers 2 through 4, which the SPARC SVR4 ABI reserves for applications. Like the global register 1, each global register 2 through 4 is then treated as an allocable register that is clobbered by function calls. This is the default.
To be fully SVR4 ABI-compliant at the cost of some performance loss, specify -mno-app-regs. You should compile libraries and system software with this option.
-mflat,-mno-flatโ with-mflat, the compiler does not generate save/restore instructions and 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 are 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; 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. ๐ญ
-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 thecasainstruction 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 oflddandstdinstructions for copies in structure assignment, in place of twice as manyldandstpairs. However, the use of this changed alignment directly violates the SPARC ABI. Thus, 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. ๐ซฃ-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. โญ-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. And 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. it's giving "every chip ever, lovingly catalogued" energy fr fr โจ
-mtune=cpu_typeโ sets the instruction scheduling parameters for machine type cpu_type, but does NOT set the instruction set or register set that-mcpu=cpu_typedoes. Same values work for both, but the only ones actually useful here are the ones 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,niagara7andm8. And with native Solaris and GNU/Linux toolchains,nativecan 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. (yes bestie, they stack, it's a whole vibe ๐)-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 as niagara-3 and later. Setting-mvis3also sets-mvis2and-mvis. ๐ฆ-mvis4,-mno-vis4โ with-mvis4, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions. The default is-mvis4when targeting a cpu that supports such instructions, such as niagara-7 and later. Setting-mvis4also sets-mvis3,-mvis2and-mvis.-mvis4b,-mno-vis4bโ with-mvis4b, GCC generates code that takes advantage of version 4.0 of the UltraSPARC Visual Instruction Set extensions, plus the additional VIS instructions introduced in the Oracle SPARC Architecture 2017. The default is-mvis4bwhen targeting a cpu that supports such instructions, such as m8 and later. Setting-mvis4balso sets-mvis4,-mvis3,-mvis2and-mvis. โจ-mcbcond,-mno-cbcondโ with-mcbcond, GCC generates code that takes advantage of the UltraSPARC Compare-and-Branch-on-Condition instructions. The default is-mcbcondwhen targeting a CPU that supports such instructions, such as Niagara-4 and later.-mfmaf,-mno-fmafโ with-mfmaf, GCC generates code that takes advantage of the UltraSPARC Fused Multiply-Add Floating-point instructions. The default is-mfmafwhen targeting a CPU that supports such instructions, such as Niagara-3 and later. ๐ฅ-mfsmuld,-mno-fsmuldโ with-mfsmuld, GCC generates code that takes advantage of the Floating-point Multiply Single to Double (FsMULd) instruction. The default is-mfsmuldwhen targeting a CPU supporting the architecture versions V8 or V9 with FPU except-mcpu=leon.-mpopc,-mno-popcโ with-mpopc, GCC generates code that takes advantage of the UltraSPARC Population Count instruction. The default is-mpopcwhen targeting a CPU that supports such an instruction, such as Niagara-2 and later.-msubxc,-mno-subxcโ with-msubxc, GCC generates code that takes advantage of the UltraSPARC Subtract-Extended-with-Carry instruction. The default is-msubxcwhen targeting a CPU that supports such an instruction, such as Niagara-7 and later.-mfix-at697fโ enables the documented workaround for the single erratum of the Atmel AT697F processor (which corresponds to erratum #13 of the AT697E processor). ๐ ๏ธ-mfix-ut699โ enables the documented workarounds for the floating-point errata and the data cache nullify errata of the UT699 processor.-mfix-ut700โ enables the documented workaround for the back-to-back store errata of the UT699E/UT700 processor.-mfix-gr712rcโ enables 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โ sets 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. ๐ญ
-mmemory-model=mem-modelโ sets 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.-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).-YP,dirsโ search the directories dirs, and no others, for libraries specified with-l.-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 to 500M in 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.-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. (a whole flag just vibing, doing nothing, iconic honestly) ๐
โญ 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โ okay so these two are a lil toggle: do not use (or 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. ๐-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 isnbytes or less into the tiny data area that registereppoints to. The tiny data area can hold up to 256 bytes in total (128 bytes for byte references). ๐ซถ-msda=nโ put static or global variables whose size isnbytes or less into the small data area that registergppoints to. The small data area can hold up to 64 kilobytes. ๐ธ-mzda=nโ put static or global variables whose size isnbytes or less into the first 32 kilobytes 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. ๐ฆ-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. periodt. ๐
-mdisable-callt,-mno-disable-calltโ this option suppresses generation of theCALLTinstruction for thev850e,v850e1,v850e2,v850e2v3andv850e3v5flavors 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. IfCALLTinstructions 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. โจ-mlong-jumps,-mno-long-jumpsโ disable (or re-enable) the generation of PC-relative jump instructions. ๐ฆ-msoft-float,-mhard-floatโ disable (or re-enable) the generation of hardware floating point instructions. This option is only significant when the target architecture is V850E2V3 or higher. If hardware floating point instructions are being generated then the C preprocessor symbol__FPU_OK__is defined, otherwise the symbol__NO_FPU__is defined. ๐ธ-mloopโ enables the use of the e3v5 LOOP instruction. The use of this instruction is not enabled by default when the e3v5 architecture is selected because its use is still experimental. ๐-mrh850-abi,-mghsโ enables support for the RH850 version of the V850 ABI. This is the default. With this version of the ABI the following rules apply:- 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 following rules apply:- 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. Use this option only if the assembler/linker complain about out of range branches within a switch table. ๐จ-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. ๐
โจ 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.-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 typecpu_type. Supported values forcpu_typearemcm,gr5andgr6.mcmis a synonym ofgr5present 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 typecpu_type, but do not set the instruction set or register set that the option-mcpu=cpu_typewould. ๐ฏ-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, registers r24 to r31 cannot be accessed in this mode; on the GR6, only registers r29 to r31 are 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 forsizeare32orshortfor 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 typecpu-type. In contrast to-mtune=cpu-type, which merely tunes the generated code for the specifiedcpu-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 one's iconic: it picks the CPU to generate code for at compile time by literally sniffing out what processor type the compiling machine is. Using-march=nativeenables every instruction subset the local machine supports (which means, bestie, the result might not run on different machines ๐ โ it's giving "works on my machine" energy fr). And-mtune=nativeproduces code optimized for the local machine, but only under the constraints of whatever instruction set you selected. ๐ซถx86-64โ a generic CPU with 64-bit extensions. Simple. Clean. Does what it says. โจx86-64-v2x86-64-v3x86-64-v4โ these three cpu-type choices 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 that particular micro-architecture level. ๐
Since these cpu-type values do not have a corresponding -mtune setting, using -march with these values enables generic tuning. Want specific tuning instead? Enable it with the -mtune=other-cpu-type option, using an appropriate other-cpu-type value. ๐
i386โ the original Intel i386 CPU. The blueprint, the blueprint. ๐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 instruction set support.pentium3pentium3mโ Intel Pentium III CPU, based on Pentium Pro core with MMX and SSE instruction set support.pentium-mโ Intel Pentium M; a low-power version of the Intel Pentium III CPU with MMX, SSE and SSE2 instruction set support. Used by Centrino notebooks. ๐pentium4pentium4mโ Intel Pentium 4 CPU with MMX, SSE and SSE2 instruction set support.prescottโ improved version of Intel Pentium 4 CPU with MMX, SSE, SSE2 and SSE3 instruction set support.noconaโ improved version of Intel Pentium 4 CPU with 64-bit extensions, MMX, SSE, SSE2 and SSE3 instruction set support.core2โ Intel Core 2 CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.nehalemโ Intel Nehalem CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2 and POPCNT instruction set support.westmereโ Intel Westmere CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES and PCLMUL instruction set support.sandybridgeโ Intel Sandy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AES and PCLMUL instruction set support.ivybridgeโ Intel Ivy Bridge CPU with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AES, PCLMUL, FSGSBASE, RDRND and F16C instruction set support.haswellโ Intel Haswell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2 and F16C instruction set support.broadwellโ Intel Broadwell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED ADCX and PREFETCHW instruction set support.skylakeโ Intel Skylake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC and XSAVES instruction set support. โจbonnellโ Intel Bonnell CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3 and SSSE3 instruction set support.silvermontโ Intel Silvermont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL and RDRND instruction set support.goldmontโ Intel Goldmont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT and FSGSBASE instruction set support.goldmont-plusโ Intel Goldmont Plus CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX and UMIP instruction set support. ๐tremontโ Intel Tremont CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, UMIP, GFNI-SSE, CLWB, MOVDIRI, MOVDIR64B, CLDEMOTE and WAITPKG instruction set support.knlโ Intel Knight's Landing CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, PREFETCHWT1, AVX512F, AVX512PF, AVX512ER and AVX512CD instruction set support. ๐ฅknmโ Intel Knights Mill CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, PREFETCHWT1, AVX512F, AVX512PF, AVX512ER, AVX512CD, AVX5124VNNIW, AVX5124FMAPS and AVX512VPOPCNTDQ instruction set support.skylake-avx512โ Intel Skylake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ and AVX512CD instruction set support.cannonlakeโ Intel Cannonlake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA and UMIP instruction set support.icelake-clientโ Intel Icelake Client CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES instruction set support. ๐งโจicelake-serverโ Intel Icelake Server CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES, PCONFIG and WBNOINVD instruction set support.cascadelakeโ Intel Cascadelake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD and AVX512VNNI instruction set support.cooperlakeโ Intel cooperlake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, CLWB, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VNNI and AVX512BF16 instruction set support.tigerlakeโ Intel Tigerlake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, PKU, AVX, AVX2, AES, PCLMUL, FSGSBASE, RDRND, FMA, BMI, BMI2, F16C, RDSEED, ADCX, PREFETCHW, CLFLUSHOPT, XSAVEC, XSAVES, AVX512F, AVX512VL, AVX512BW, AVX512DQ, AVX512CD, AVX512VBMI, AVX512IFMA, SHA, CLWB, UMIP, RDPID, GFNI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, VPCLMULQDQ, VAES, PCONFIG, WBNOINVD, MOVDIRI, MOVDIR64B, AVX512VP2INTERSECT and KEYLOCKER instruction set support. ๐ฏsapphirerapidsโ Intel sapphirerapids CPU with 64-bit extensions, 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, AVX512VP2INTERSECT, ENQCMD, CLDEMOTE, PTWRITE, WAITPKG, SERIALIZE, TSXLDTRK, UINTR, AMX-BF16, AMX-TILE, AMX-INT8, AVX-VNNI and AVX512BF16 instruction set support. ๐alderlakeโ Intel Alderlake CPU with 64-bit extensions, MOVBE, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2, POPCNT, AES, PREFETCHW, PCLMUL, RDRND, XSAVE, XSAVEC, XSAVES, XSAVEOPT, FSGSBASE, PTWRITE, RDPID, SGX, UMIP, 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 with 64-bit extensions,MOVBE,MMX,SSE,SSE2,SSE3,SSSE3,SSE4.1,SSE4.2,POPCNT,PKU,AVX,AVX2,AES,PCLMUL,FSGSBASE,RDRND,FMA,BMI,BMI2,F16C,RDSEED,ADCX,PREFETCHW,CLFLUSHOPT,XSAVEC,XSAVES,AVX512F,AVX512VL,AVX512BW,AVX512DQ,AVX512CD,AVX512VBMI,AVX512IFMA,SHA,CLWB,UMIP,RDPID,GFNI,AVX512VBMI2,AVX512VPOPCNTDQ,AVX512BITALG,AVX512VNNI,VPCLMULQDQ,VAESinstruction set support. ๐k6โ AMD K6 CPU withMMXinstruction set support.k6-2,k6-3โ improved versions of the AMD K6 CPU withMMXand3DNow!instruction set support. โจathlon,athlon-tbirdโ AMD Athlon CPU withMMX,3dNOW!, enhanced3DNow!andSSEprefetch instructions support.athlon-4,athlon-xp,athlon-mpโ improved AMD Athlon CPU withMMX,3DNow!, enhanced3DNow!and fullSSEinstruction set support.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 supersetsMMX,SSE,SSE2,3DNow!, enhanced3DNow!and 64-bit instruction set extensions.)k8-sse3,opteron-sse3,athlon64-sse3โ improved versions of AMD K8 cores withSSE3instruction set support.amdfam10,barcelonaโ CPUs based on AMD Family 10h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSE4A,3DNow!, enhanced3DNow!,ABMand 64-bit instruction set extensions.)bdver1โ CPUs based on AMD Family 15h cores with x86-64 instruction set support. (This supersetsFMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver2โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver3โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,XOP,LWP,AES,PCLMUL,CX16,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)bdver4โ AMD Family 15h core based CPUs with x86-64 instruction set support. (This supersetsBMI,BMI2,TBM,F16C,FMA,FMA4,FSGSBASE,AVX,AVX2,XOP,LWP,AES,PCLMUL,CX16,MOVBE,MMX,SSE,SSE2,SSE3,SSE4A,SSSE3,SSE4.1,SSE4.2,ABMand 64-bit instruction set extensions.)znver1โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,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.)znver2โ AMD Family 17h core based CPUs with x86-64 instruction set support. (This supersetsBMI,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.)znver3โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,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.)znver4โ AMD Family 19h core based CPUs with x86-64 instruction set support. (This supersetsBMI,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,GFNIand 64-bit instruction set extensions.)btver1โ CPUs based on AMD Family 14h cores with x86-64 instruction set support. (This supersetsMMX,SSE,SSE2,SSE3,SSSE3,SSE4A,CX16,ABMand 64-bit instruction set extensions.)btver2โ CPUs based on AMD Family 16h cores with x86-64 instruction set support. This includesMOVBE,F16C,BMI,AVX,PCLMUL,AES,SSE4.2,SSE4.1,CX16,ABM,SSE4A,SSSE3,SSE3,SSE2,SSE,MMXand 64-bit instruction set extensions.winchip-c6โ IDT WinChip C6 CPU, dealt in same way asi486with additionalMMXinstruction set support.winchip2โ IDT WinChip 2 CPU, dealt in same way asi486with additionalMMXand3DNow!instruction set support.c3โ VIA C3 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.) ๐ญc3-2โ VIA C3-2 (Nehemiah/C5XL) CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.)c7โ VIA C7 (Esther) CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.)samuel-2โ VIA Eden Samuel 2 CPU withMMXand3DNow!instruction set support. (No scheduling is implemented for this chip.)nehemiahโ VIA Eden Nehemiah CPU withMMXandSSEinstruction set support. (No scheduling is implemented for this chip.)estherโ VIA Eden Esther CPU withMMX,SSE,SSE2andSSE3instruction set support. (No scheduling is implemented for this chip.)eden-x2โ VIA Eden X2 CPU with x86-64,MMX,SSE,SSE2andSSE3instruction 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,AVXandAVX2instruction set support. (No scheduling is implemented for this chip.)nanoโ generic VIA Nano CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.)nano-1000โ VIA Nano 1xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.)nano-2000โ VIA Nano 2xxx CPU with x86-64,MMX,SSE,SSE2,SSE3andSSSE3instruction set support. (No scheduling is implemented for this chip.)nano-3000โ VIA Nano 3xxx CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.)nano-x2โ VIA Nano Dual Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.)nano-x4โ VIA Nano Quad Core CPU with x86-64,MMX,SSE,SSE2,SSE3,SSSE3andSSE4.1instruction set support. (No scheduling is implemented for this chip.)geodeโ AMD Geode embedded processor withMMXand3DNow!instruction set support. ๐ฆ
-mtune=cpu-type ๐
Okay bestie, so this one is the vibe tuner, not the feature unlocker, and the distinction is everything.
-mtune=cpu-type tunes everything applicable about the generated code to cpu-type โ except for the ABI and the set of available instructions. So while picking a specific cpu-type schedules things appropriately for that particular chip, the compiler does not generate any code that cannot run on the default machine type unless you also use a -march=cpu-type option. ๐
Like, fr fr: if GCC is configured for i686-pc-linux-gnu then -mtune=pentium4 generates code that is tuned for Pentium 4 but still runs on i686 machines. Cute, right? ๐
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 -mtune or -march option 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. ๐ซถ
Heads up: as new processors are deployed in the marketplace, the behavior of this option will change. So 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. Not a bug, just a moving target, bestie. ๐ญ
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. That's the whole tea. ๐
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 -mtune or -march option instead of -mtune=intel. But, if you want your application performs better on both Haswell and Silvermont, then you should use this option. ๐
Same warning as above, and it's giving deja vu: 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. โญ
And yep, there is no -march=intel option either, 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โ okay so this one is literally just a deprecated synonym for-mtune. that's it. that's the whole thing. use-mtunebestie, the glow-up already happened ๐-mfpmath=unitโ tells GCC which unit should be doing your floating-point arithmetic. your choices, queen:387โ uses the standard 387 floating-point coprocessor that's chilling on the majority of chips, and emulated everywhere else. code compiled with this runs almost everywhere which is iconic tbh. the catch? temporary results get computed in 80-bit precision instead of whatever precision the type actually specified, so you get slightly different results compared to most other chips ๐ญ. peep-ffloat-storefor the whole detailed breakdown. this is the default choice for non-Darwin x86-32 targets.sseโ uses the scalar floating-point instructions sitting in the SSE instruction set. supported by Pentium III and newer chips, and over in AMD land by the Athlon-4, Athlon XP and Athlon MP chips ๐ฆ. the earlier version of SSE only supports single-precision arithmetic, so double and extended-precision arithmetic still get done with 387. a later version โ only present in Pentium 4 and AMD x86-64 chips โ supports double-precision too. for the x86-32 compiler you must use-march=cpu-type,-msseor-msse2switches to enable SSE extensions and make this option actually do something. for the x86-64 compiler those extensions are enabled by default, no effort required โจ. the resulting code should be considerably faster in the majority of cases and dodges the numerical instability problems of 387 code, but it may break some existing code that expects temporaries to be 80 bits ๐. this is the default choice for the x86-64 compiler, Darwin x86-32 targets, and the default for x86-32 targets with the SSE2 instruction set when-ffast-mathis enabled.sse,387/sse+387/bothโ attempts to utilize both instruction sets at once. this effectively doubles the amount of available registers, and on chips with separate execution units for 387 and SSE, the execution resources too ๐. use this one with care though, because it's still experimental โ the GCC register allocator does not model separate functional units well, resulting in unstable performance ๐.
-masm=dialectโ outputs assembly instructions using the dialect you picked. it also affects which dialect is used for basicasmand extendedasm. supported choices (in dialect order) areattorintel. the default isatt. Darwin does not supportintel, sorry bestie.-mieee-fp,-mno-ieee-fpโ controls whether or not the compiler uses IEEE floating-point comparisons. these correctly handle the case where the result of a comparison is unordered โจ.-m80387,-mhard-floatโ generates output containing 80387 instructions for floating point ๐ฅ.-mno-80387,-msoft-floatโ generates 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 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. no shortcuts, babe.
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โ do not use the FPU registers for return values of functions. the usual calling convention has functions return values of typesfloatanddoublein an FPU register, even if there's no FPU โ the whole idea being that the operating system should emulate an FPU. this option makes such values get returned in ordinary CPU registers instead ๐ .-mno-fancy-math-387โ some 387 emulators do not support thesin,cosandsqrtinstructions for the 387. specify this option to avoid generating those instructions. it gets overridden when-marchindicates that the target CPU always has an FPU, so the instruction doesn't need emulation. heads up: these instructions are not 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-doubleis 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. lowkey a big deal.
-m96bit-long-double,-m128bit-long-doubleโ these switches control the size of thelong 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) preferlong doubleto 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-doublealignslong doubleto a 16-byte boundary by padding thelong doublewith an additional 32-bit zero โจ. in the x86-64 compiler,-m128bit-long-doubleis the default choice, as its ABI specifies thatlong doubleis aligned on a 16-byte boundary. notice that neither of these options enables any extra precision over the x87 standard of 80 bits for along doubleโ no extra slay, just alignment.
โ ๏ธ 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 of thelong 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. (yes, same warning, different option, we're being thorough bestie ๐ซถ)
-malign-data=typeโ controls how GCC aligns variables. the supported values for type are:compatuses increased alignment value compatible uses GCC 4.8 and earlier,abiuses alignment value as specified by the psABI, andcachelineuses increased alignment value to match the cache line size.compatis 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โ uses 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 using the function attributestdcall. you can also override the-mrtdoption by using the function attributecdecl.
โ ๏ธ 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.) so like, be normal about it.
-mregparm=numโ controls 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. all of them. no exceptions ๐.
-msseregparmโ uses 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โ returns 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 โ it's giving legacy-support-only, fr fr.-mpc32,-mpc64,-mpc80โ sets the 80387 floating-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 ๐.
Okay bestie, we're still deep in the x86 options and it's giving compiler sorcery โจ. First up, a little tea about floating-point rounding: setting the rounding of floating-point operations to less than the default 80 bits can speed some programs by 2% or more. Butโand this is a big butโ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. So like, know the risks, babe. ๐
-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 attribute"force_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: When generating code for the x86-64 architecture with SSE extensions disabled,-mpreferred-stack-boundary=3can be used to keep the stack boundary aligned to 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 x87 long double and__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-boundaryis not specified, the one specified by-mpreferred-stack-boundaryis 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. ๐ธ
-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,-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 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.
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. ๐ฅ
-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-listis 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. ๐-mno-defaultโ This option instructs GCC to turn off all tunable features. See also-mtune-ctrl=feature-listand-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. ๐-mprefer-vector-width=optโ This option instructs GCC to use opt-bit vector width in instructions instead of default on the selected platform.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.
-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_bswap32"and"__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_crc32si"and"__builtin_ia32_crc32di"to generate the"crc32"machine instruction. ๐-mmwaitโ okay bestie, this one enables built-in functions__builtin_ia32_monitorand__builtin_ia32_mwaitso they generate themonitorandmwaitmachine instructions. โจ-mrecipโ enables use ofRCPSSandRSQRTSSinstructions (and their vectorized variantsRCPPSandRSQRTPS) with an additional Newton-Raphson step to increase precision instead ofDIVSSandSQRTSS(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). ๐ญ
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 note that GCC emits the above sequence with additional Newton-Raphson step for vectorized single-float division and vectorized sqrtf(x) already with -ffast-math (or the above option combination), and doesn't need -mrecip. no cap.
-mrecip=optโ This option controls which reciprocal estimate instructions may be used.optis a comma-separated list of options, which may be preceded by a!to invert the option: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 approximation for scalar division.vec-divโ Enable the approximation for vectorized division.sqrtโ Enable the approximation for scalar square root.vec-sqrtโ Enable the approximation for vectorized square root.
So, for example, -mrecip=all,!sqrt enables all of the reciprocal approximations, except for square root. ๐
-mveclibabi=typeโ Specifies the ABI type to use for vectorizing intrinsics using an external library. Supported values fortypearesvmlfor the Intel short vector math library andacmlfor the AMD math core library. To use this option, both-ftree-vectorizeand-funsafe-math-optimizationshave to be enabled, and an SVML or ACML ABI-compatible library must be specified at link time.
GCC currently 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 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. ๐ฆ
-mabi=nameโ Generate code for the specified calling convention. Permissible values aresysvfor the ABI used on GNU/Linux and other systems, andmsfor the Microsoft ABI. The default is to use the Microsoft ABI when targeting Microsoft Windows and the SysV ABI on all other systems. You can control this behavior for specific functions by using the function attributesms_abiandsysv_abi.-mforce-indirect-callโ Force all calls to functions to be indirect. This is useful when using Intel Processor Trace where it generates more precise timing information for function calls. ๐ฅ-mmanual-endbrโ InsertENDBRinstruction at function entry only via thecf_checkfunction attribute. This is useful when used with the option-fcf-protection=branchto control ENDBR insertion at the function entry.-mcall-ms2sysv-xloguesโ Due to differences in 64-bit ABIs, any Microsoft ABI function that calls a System V ABI function must consider RSI, RDI and XMM6-15 as clobbered. By default, the code for saving and restoring these registers is emitted inline, resulting in fairly lengthy prologues and epilogues. Using-mcall-ms2sysv-xloguesemits prologues and epilogues that use stubs in the static portion oflibgccto perform these saves and restores, thus reducing function size at the cost of a few extra instructions.-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 cannot be satisfied on all systems. ๐-mpush-args/-mno-push-argsโ UsePUSHoperations to store outgoing parameters. This method is shorter and usually equally fast as method usingSUB/MOVoperations and is enabled by default. In some cases disabling it may improve performance because of improved scheduling and reduced dependencies.-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 is not equal to 2. The drawback is a notable increase in code size. This switch implies-mno-push-args.-mthreadsโ Support 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.-mms-bitfields/-mno-ms-bitfieldsโ Enable/disable bit-field layout compatible with the native Microsoft Windows compiler.
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. Particularly when moving packed data between functions compiled with GCC and the native Microsoft compiler (either via function call or as data in a file), it may be necessary to access either format.
This option is enabled by default for Microsoft Windows targets. This behavior can also be controlled locally by use of variable or type attributes. For more information, see x86 Variable Attributes and x86 Type Attributes.
The Microsoft structure layout algorithm is fairly simple with the exception of 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
alignedattribute or thepackpragma), 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.
- 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,baris 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 is 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,
t2has 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. periodt ๐
-mno-align-stringopsโ bestie, this says do not align the destination of inlined string operations. It makes your code smaller and faster if the destination is already aligned โ but GCC doesn't know that, so it's just doing extra work for no reason ๐-minline-all-stringopsโ okay so by default GCC only inlines string ops when the destination is known to be aligned to at least a 4-byte boundary. This flag unlocks way more inlining and grows your code size, but it can genuinely slay performance for code that leans on fastmemcpyandmemsetfor short lengths. It also turns on inline expansion ofstrlenfor all pointer alignments. iconic โจ-minline-stringops-dynamicallyโ for string operations of unknown size, this does run-time checks: inline code for small blocks, library call for large blocks. little bit of both, main character energy ๐-mstringop-strategy=algโ overrides the internal decision heuristic for which algorithm gets used to inline string operations. The allowed values for alg are:rep_byterep_4byterep_8byteโ expand using i386repprefix of the specified size.byte_looploopunrolled_loopโ expand into an inline loop.libcallโ always use a library call.
-mmemcpy-strategy=strategyโ overrides the internal decision heuristic for whether__builtin_memcpyshould be inlined, and which inline algorithm to use when the expected size of the copy is known. strategy is a comma-separated list ofalg:max_size:dest_aligntriplets. alg is specified in-mstringop-strategy, max_size says the max byte size that inline algorithm alg is allowed for. For the last triplet, max_size must be-1. The max_size values in the list must be in increasing order. The minimal byte size for alg is0for the first triplet, andmax_size + 1of the preceding range. no cap, just triplet math ๐-mmemset-strategy=strategyโ literally the same vibe as-mmemcpy-strategy=except it controls__builtin_memsetexpansion instead.-momit-leaf-frame-pointerโ don't keep the frame pointer in a register for leaf functions. This skips the instructions to save, set up, and restore frame pointers, and frees up an extra register in leaf functions. Heads up:-fomit-leaf-frame-pointerremoves the frame pointer for leaf functions, which might make debugging harder. ๐ญ-mtls-direct-seg-refs-mno-tls-direct-seg-refsโ controls whether TLS variables can be accessed with offsets from the TLS segment register (%gsfor 32-bit,%fsfor 64-bit), or whether the thread base pointer has to be added. Whether this is even valid depends on your operating system and whether it maps the segment to cover the entire TLS area. ๐ฆ
For systems using the GNU C Library, the default is on.
-msse2avx-mno-sse2avxโ tells the assembler to encode SSE instructions with the VEX prefix. The option-mavxturns this on by default. โจ-mfentry-mno-fentryโ if profiling is active (-pg), put the profiling counter call before the prologue. Note: on x86 architectures the attributems_hook_prologueisn't possible at the moment for-mfentryand-pg. ๐-mrecord-mcount-mno-record-mcountโ if profiling is active (-pg), generate a__mcount_locsection containing pointers to each profiling call. This is useful for automatically patching and out calls. ๐ง-mnop-mcount-mno-nop-mcountโ if 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, not sibling calls ending withjump. Valid types arenoneto not instrument,callto generate a call to__return__, ornop5to generate a 5 byte nop. ๐-mrecord-return-mno-record-returnโ generate 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-setupโ when 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: since the RAX register is used to avoid unnecessarily saving vector registers on the 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 doesn't have those issues, regardless of the RAX register value. ๐ญ
-m8bit-idiv-mno-8bit-idivโ on 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 the range of 0 to 255, 8-bit unsigned integer divide is used instead of 32-bit/64-bit integer divide. ate ๐-mavx256-split-unaligned-load-mavx256-split-unaligned-storeโ split 32-byte AVX unaligned load and store.-mstack-protector-guard=guard-mstack-protector-guard-reg=reg-mstack-protector-guard-offset=offsetโ generate stack protection code using a canary at guard. Supported locations areglobalfor global canary ortlsfor per-thread canary in the TLS block (the default). This option only has an effect when-fstack-protectoror-fstack-protector-allis specified. ๐ก๏ธ
With the tls choice, the options -mstack-protector-guard-reg=reg and -mstack-protector-guard-offset=offset additionally specify which segment register (%fs or %gs) to use as the 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 stops the compiler from using floating-point, vector, mask, and bound registers. strict queen behavior ๐-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 attributeindirect_branch. ๐
Note that-mcmodel=largeis incompatible with-mindirect-branch=thunkand-mindirect-branch=thunk-extern, since the thunk function may not be reachable in the large code model. ๐
Note that-mindirect-branch=thunk-externis 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 attributefunction_return. ๐
Note that-mindirect-return=thunk-externis compatible with-fcf-protection=branch, since the external thunk can be made to enable control-flow check.
Note that-mcmodel=largeis incompatible with-mfunction-return=thunkand-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. no detours, we're going straight through ๐ฆ-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 a CS prefix tocallandjmpto indirect thunk with branch target inr8-r15registers, so that the call and jmp instruction length is 6 bytes โ letting them 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.
-m32-m64-mx32-m16-miamcuโ generate code for a 16-bit, 32-bit or 64-bit environment. The-m32option setsint,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 the fact 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's 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โ the small code model, bestie. The program and its symbols have to be linked in the lower 2 GB of the address space. Pointers are64bits. Programs can be statically or dynamically linked. And guess what โ this is the default code model. It's giving main character energy by default, periodt. ๐-mcmodel=kernelโ the kernel code model. The kernel runs in the negative 2 GB of the address space. You have to use this model for Linux kernel code. No wiggle room, no vibe check, it's mandatory. ๐-mcmodel=mediumโ the medium model. The program is linked in the lower 2 GB of the address space, and small symbols get placed there too. Symbols with sizes larger than-mlarge-data-thresholdget yeeted into large data or BSS sections and can live above 2GB. Programs can be statically or dynamically linked. ๐ฆ-mcmodel=largeโ the large model. This one makes zero assumptions about addresses and sizes of sections. It just doesn't speculate. Iconic, honestly. โจ-maddress-mode=longโ generates code for long address mode. Only supported for64-bitandx32environments. It's the default address mode for64-bitenvironments. ๐-maddress-mode=shortโ generates code for short address mode. Only supported for32-bitandx32environments. And it's the default address mode for32-bitandx32environments. ๐-mneeded,-mno-neededโ emit theGNU_PROPERTY_X86_ISA_1_NEEDEDGNU property for Linux target, which is basically your binary going "hey, this is the micro-architecture ISA level you need to execute me bestie." ๐ธ
๐ป x86 Windows Options ๐ป
These extra options are available for Microsoft Windows targets, iykyk:
-mconsoleโ says a console application is what we're generating, by telling the linker to set the PE header subsystem type that console applications need. Available for Cygwin and MinGW targets, and it's enabled by default on those targets. ๐ซถ-mdllโ available forCygwinandMinGWtargets. It says a DLL โ a dynamic link library โ is what we're generating, which enables the selection of the required runtime startup object and entry point. Slay. ๐-mnop-fun-dllimportโ available forCygwinandMinGWtargets. It says the"dllimport"attribute should be ignored. Not me telling you to ignore things ๐ญ-mthreadโ available for MinGW targets. It says MinGW-specific thread support is what's being used. ๐งต-municodeโ available for MinGW-w64 targets. It makes the"UNICODE"preprocessor macro get predefined, and it picks Unicode-capable runtime startup code. Very demure, very Unicode. โจ-mwin32โ available forCygwinandMinGWtargets. It says the typical Microsoft Windows predefined macros get set in the pre-processor, but it does not influence the choice of runtime library/startup code. So it's a vibe, not a decision-maker. ๐-mwindowsโ available forCygwinandMinGWtargets. It says a GUI application is what's 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 theUser32API โ the one that's used to set executable privileges โ isn't available. ๐-fwritable-relocated-rdataโ available for MinGW and Cygwin targets. It says relocated-data in read-only section gets put into the".data"section. This is necessary for older runtimes that don't support modification of".rdata"sections for pseudo-relocation. ๐-mpe-aligned-commonsโ available forCygwinandMinGWtargets. It says the GNU extension to the PE file format that permits the 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. ๐
Also, check under x86 Options for the standard options, bestie โ don't come for me, they're just listed there.
๐ฆ Xstormy16 Options ๐ฆ
These options are defined for Xstormy16:
-msimโ choose startup files and linker script suitable for the simulator. That's it, that's the whole vibe. โจ
๐ธ Xtensa Options ๐ธ
These options are supported for Xtensa targets:
-mconst16,-mno-const16โ enable or disable use of"CONST16"instructions for loading constant values. Fun fact: the"CONST16"instruction is currently not a standard option from Tensilica. When it's enabled,"CONST16"instructions are always used in place of the standard"L32R"instructions. And the use of"CONST16"is enabled by default only if the"L32R"instruction isn't available. Iykyk. ๐-mfused-madd,-mno-fused-maddโ enable or disable use of fused multiply/add and multiply/subtract instructions in the floating-point option. Heads up: this has no effect if the floating-point option isn't also enabled. Disabling fused multiply/add and multiply/subtract instructions forces the compiler to use separate instructions for the multiply and 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, thereby producing results with more bits of precision than the IEEE standard specifies. Disabling fused multiply add/subtract instructions also ensures the program output isn't sensitive to the compiler's ability to combine multiply and add/subtract operations. Math girlies, this one's for you. ๐งฎโจ-mserialize-volatile,-mno-serialize-volatileโ when this option is enabled, GCC inserts"MEMW"instructions before"volatile"memory references to guarantee sequential consistency. The default is-mserialize-volatile. Use-mno-serialize-volatileto omit the"MEMW"instructions. ๐-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. ๐-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. This allows the literal pool to be placed in a data RAM/ROM, and it also allows the linker to 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 in order 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โ these options control the treatment of literal pools. The default is-mno-auto-litpools, which places literals in a separate section in the output file unless-mtext-section-literalsis used. With-mauto-litpoolsthe literals are interspersed in the text section by the assembler. The compiler doesn't produce explicit".literal"directives and loads literals into registers with"MOVI"instructions instead of"L32R"to let the assembler do relaxation and place literals as necessary. This option allows the assembler to create several literal pools per function and assemble very big functions, which may not be possible with-mtext-section-literals. Big function energy. ๐ฆ-mtarget-align,-mno-target-alignโ when this option is 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 is performed. The default is-mtarget-align. These options do not affect the treatment of auto-aligned instructions like"LOOP", which the assembler always aligns, either by widening density instructions or by inserting NOP instructions. ๐-mlongcalls,-mno-longcallsโ when this option is enabled, GCC instructs the assembler to translate direct calls to 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 occurs for calls to functions in other source files. Specifically, the assembler translates a direct"CALL"instruction into an"L32R"followed by a"CALLX"instruction. The default is-mno-longcalls. This option should be used in programs where the call target can potentially be out of range. Now listen โ 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. Periodt. ๐ญ-mabi=nameโ generate code for the specified ABI. Permissible values are:call0,windowed. Default ABI is chosen by the Xtensa core configuration. ๐-mabi=call0โ when this option is enabled, function parameters are passed in registers"a2"through"a7", registers"a12"through"a15"are caller-saved, and register"a15"may 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 registers"a10"through"a15", and the called function rotates the register window by8registers on entry so that its arguments are found in registers"a2"through"a7". Register"a7"may be used as a frame pointer. The register window is rotated8registers 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 section is all about the env vars that change how GCC acts. Some give it directories or prefixes to search for files, some set other stuff about compilation. ๐
Note: you can also tell GCC where to search with options like-B,-I, and-L. Those options beat environment variables. Environment variables beat whatever GCC's configuration says. Precedence chain, periodt. ๐
LANG, LC_CTYPE, LC_MESSAGES, LC_ALL
These control localization info so GCC can work with different national conventions. GCC checks locale categories LC_CTYPE and LC_MESSAGES if it was configured to do so. Those categories can be set to any value your installation supports. A typical value is en_GB.UTF-8 for English in the United Kingdom encoded in UTF-8. ๐
LC_CTYPE specifies character classification. GCC uses it to figure out character boundaries in a string; needed for some multibyte encodings that contain quote and escape characters that are otherwise interpreted as string end or escape. ๐ญ
LC_MESSAGES specifies language for diagnostic messages. ๐ฌ
If LC_ALL is set, it overrides LC_CTYPE and LC_MESSAGES; otherwise LC_CTYPE and LC_MESSAGES default to the value of LANG. If none set, GCC defaults to traditional C English behavior. ๐ฌ๐ง
TMPDIR
If TMPDIR is set, it specifies the directory for temporary files. GCC uses temp files to hold output of one compilation stage used as input to the next: e.g., output of the preprocessor, which is input to the compiler proper. ๐๏ธ
GCC_COMPARE_DEBUG
Setting GCC_COMPARE_DEBUG is nearly equivalent to passing -fcompare-debug to the compiler driver. See the docs of that option for details. ๐
GCC_EXEC_PREFIX
If GCC_EXEC_PREFIX is set, it specifies a prefix to use in the names of 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. ๐ ๏ธ
If GCC_EXEC_PREFIX is not set, GCC attempts to figure out an appropriate prefix 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. ๐คฏ
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. ๐
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). ๐
LANG (the multibyte-character one)
This variable is used to pass locale info to the compiler. One way the info is used is to determine the character set 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. ๐ฏ๐ตC-SJISโ recognize SJIS characters.C-EUCJPโ recognize EUCJP characters.
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. ๐ค
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. โ ๏ธ
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. ๐ขfixits-v2โ as"fixits-v1", but columns are expressed as display columns, as per-fdiagnostics-column-unit=display. ๐ฅ๏ธ
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. ๐ช๐ง
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. ๐ป
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. ๐
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. ๐งฉ
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. โ๏ธ
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. โฐ
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. ๐ ๏ธ
๐ BUGS ๐
For instructions on reporting bugs, see <file:///usr/share/doc/gcc-11/README.Bugs>. ๐
๐ 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. ๐
๐ 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. ๐ซถ
๐ AUTHOR ๐
See the Info entry for gcc, or <http://gcc.gnu.org/onlinedocs/gcc/Contributors.html>, for contributors to GCC. ๐
ยฉ๏ธ COPYRIGHT ยฉ๏ธ
Copyright (c) 1988-2021 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. ๐
(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.
๐ That's the whole page, bestie โ source/version gcc-11, dated 2024-07-19, page GCC(1). No cap, you made it. Periodt. ๐
๐ฆ where this page comes from
- ubuntu noble: gcc-11-mips64-linux-gnuabi64 11.5.0-1ubuntu1~24.04cross1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms