gcc is a driver that runs a compiler, an assembler and a linker
The gcc command compiles nothing itself. It runs cc1, which turns C into assembly. Then it runs the binutils assembler and linker on the result. The chapters follow that path into cc1, then cover how GCC is configured, built and tested.
Each chapter opens with what that part looks like from the command line, then shows the code behind it. A dotted underline marks a term from the glossary at the end of this chapter. Hover it for the definition, or click it to open the entry.
$ gcc -v -o hello hello.c Target: x86_64-pc-linux-gnu ← the triplet this gcc produces code for Configured with: ../configure --prefix=… … ← the configure options of this build …/cc1 -quiet -v hello.c … -o /tmp/ccA.s ← the compiler proper: C to assembly as -v --64 -o /tmp/ccB.o /tmp/ccA.s ← binutils: assembly to an object file …/collect2 -plugin …/liblto_plugin.so … -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o hello …/crt1.o …/crti.o …/crtbegin.o /tmp/ccB.o -lgcc … -lc … …/crtend.o …/crtn.o ← collect2 runs ld with this command line
gcc -### prints the same commands without running them. The driver chapter shows how gcc builds each line from specs. The crt files and -lgcc come from GCC and the C library, not from the user.| Command | What it shows | Chapter |
|---|---|---|
gcc -### -c foo.c | The commands that the driver would run. | The driver |
gcc -dumpspecs | The built-in specs that produce those commands. | Spec playground |
gcc -fsyntax-only foo.c | Stops after the front end: errors are reported and no code is made. | Front ends |
gcc -O2 -c -fdump-tree-all foo.c | One file per GIMPLE pass, each holding the function after that pass. | Three IRs |
gcc -Q --help=optimizers -O2 | Which -f optimisation options -O2 turns on. | The pass manager |
gcc -O2 -S -dp foo.c | Assembly with the name of the pattern behind each instruction. | The back end |
gcc -Q --help=target | The -m options of this port and their values. | The back end |
gcc -flto -O2 a.c b.c | Optimisation across files, run during the link. | LTO |
Glossary · the driver
driver
The gcc program. It reads the options, builds the command lines of the other programs from specs, and runs them. g++ and gfortran are the same driver with other defaults.
Chapter: the driver →compiler proper
The program that compiles one source file to assembly: cc1 for C, cc1plus for C++, gnat1 for Ada, f951 for Fortran. The driver runs it once per file.
Chapter: the map →spec
A string in a small language that tells the driver which command to build from the options. gcc -dumpspecs prints the built-in specs. -specs=FILE adds or replaces some of them.
switch
One option of the gcc command line, as the driver stores it for the specs to test.
Chapter: spec playground →collect2
The program that the driver runs for the link step. It runs ld. Without the linker plugin, it also runs the LTO step and links a second time.
Chapter: the driver →Glossary · inside cc1
front end
The part of a compiler proper that knows the language. It parses the source, checks it, and builds GENERIC trees.
Chapter: front ends →middle end
The optimiser that knows neither the language nor the CPU. It works on GIMPLE.
Chapter: the pass manager →back end
The part that knows the CPU. It turns GIMPLE into RTL, allocates registers, schedules instructions and prints assembly.
Chapter: the back end →GENERIC
The tree form that every front end produces: nested expressions and statements, with no trace of the source language's syntax.
Chapter: three IRs →GIMPLE
A simpler tree form: statements with at most one operation each, and temporaries for the intermediate values. The middle end works on it.
Chapter: three IRs →SSA
Static single assignment: a form of GIMPLE in which each variable version is assigned exactly once. Most optimisations need it.
Chapter: three IRs →RTL
Register Transfer Language, the IR of the back end. Each instruction is an expression over machine modes and registers, written in a Lisp-like syntax.
Chapter: three IRs →pass
One step of the compiler that analyses or changes the IR. passes.def lists the passes in the order they run.
Chapter: the pass manager →IPA
Interprocedural analysis: passes that look at all functions of a unit, or of the whole program with LTO, instead of one function. Inlining is an IPA pass.
Chapter: the pass manager →dump file
A text file that a -fdump-* option writes: the IR of each function after one pass.
Glossary · the target
port
The code that adapts GCC to one CPU family: a directory under gcc/config/ and a stanza in config.gcc.
Chapter: the back end →machine description
The .md files of a port. They list the instructions of the CPU as RTL patterns, with the assembly text to print for each one.
Chapter: the back end →pattern
An entry in a machine description. A define_insn says which RTL an instruction matches and how to print it. A define_expand says how to build the RTL for an operation.
Chapter: the back end →optab
A table from an operation and a mode, such as addition in SImode, to the named pattern that implements it.
Chapter: the back end →predicate and constraint
Two tests on a pattern operand. A predicate says which operands the pattern accepts at all. A constraint says which registers or constants each alternative needs, for the register allocator.
Chapter: the back end →target hook
A function pointer in the targetm structure that a port can replace. It answers questions such as the cost of an instruction or where an argument goes.
target macro
The older form of a target hook: a #define in tm.h, fixed when cc1 is compiled.
libgcc
A runtime library that GCC links into programs. It holds routines for operations that the CPU has no instruction for, called libcalls, such as soft-float or 64-bit division on a 32-bit CPU.
Chapter: build and bootstrap →Glossary · build, LTO and project
target triplet
The cpu-vendor-system name of a machine, such as x86_64-pc-linux-gnu or aarch64-elf. config.gcc selects the files of a port by matching this name.
Chapter: the back end →build, host, target
Three machines in a configure command. GCC is compiled on the build machine and runs on the host. The target is the machine it produces code for. A cross compiler has a host different from its target.
Chapter: build and bootstrap →bootstrap
Building GCC with itself: stage1 by the system compiler, stage2 by stage1, stage3 by stage2. The objects of stage2 and stage3 must then be identical.
Chapter: build and bootstrap →LTO
Link-time optimisation. With -flto, cc1 writes GIMPLE into the object files, and the optimiser runs again over the whole program during the link.
WPA and LTRANS
The two modes of lto1. WPA, whole-program analysis, reads every unit and splits the program into partitions. LTRANS compiles one partition to machine code.
Chapter: LTO →linker plugin
liblto_plugin.so, a GCC library that ld loads with -plugin. It lets ld read the symbols of GIMPLE objects and hands the LTO step to GCC.
garbage collector
GCC's memory manager for IR. A GTY marker on a type or a variable tells the collector to keep what it points to.
Chapter: infrastructure →DejaGnu
The Tcl test framework of the GNU toolchain. make check runs it, and the dg- comments in a test file are its directives.
cc1 is three compilers in a row, joined by two intermediate languages
A front end builds GENERIC trees. The middle end optimises GIMPLE in SSA form. The back end lowers to RTL and matches it against the machine description.
From the command line
gcc -v prints each program that the driver runs. gcc -print-prog-name=cc1 prints the path of the compiler proper that it would use.
- The gcc command compiles nothing. It expands specs and runs cc1, the assembler, then collect2, which runs ld.
- Each language has its own cc1. Its front end parses and hands each function to the call graph as GENERIC trees.
- The gimplifier flattens GENERIC into GIMPLE: three-address statements with explicit temporaries.
- The pass manager runs the optimisers in passes.def order: SSA is built, IPA passes see the whole unit, then each function is optimised.
- pass_expand (passes.def:454) leaves SSA and builds RTL by asking the target for named patterns.
- RTL passes combine instructions, allocate registers with IRA and LRA, and schedule.
- pass_final (passes.def:564) prints each instruction through its output template.
- The machine description is the target in data form. Generator programs compile it into C++ that expand, recog and final call.
gcc.cc · collect2.cc
The driver is a spec-string interpreter that runs other programs
driver::main (gcc.cc:8335) picks a spec for each input file by suffix, expands it with do_spec, and runs the result with execute. The C entry is in default_compilers[]:
From the command line
gcc -### -c foo.c prints the commands without running them. gcc -save-temps -c foo.c keeps the intermediate files: foo.i from the preprocessor and foo.s from cc1.
{"@c", … cc1 %(cpp_unique_options) %(cc1_options) ← the compiler proper %{!fsyntax-only:%(invoke_as)} ← then the assembler … } gcc.cc:1456–1469, abridged
<lang>/lang-specs.h. The link step is LINK_COMMAND_SPEC (gcc.cc:1160), which runs collect2. collect2 runs ld, or runs lto-wrapper and relinks when the linker plugin is not in use.Spec playground · gcc.cc do_spec_1
A spec decides per switch, and a switch can be dead before the spec reads it
Edit the spec, the specs file or the command line. The expansion runs in this page with the matching rules ported from handle_braces (gcc.cc:7323), process_brace_body (:7539) and check_live_switch (:7630). Each preset is one rule that surprises people.
From the command line
gcc -dumpspecs prints the built-in specs. gcc -specs=my.specs reads a specs file that adds or overrides named specs. Some bare-metal toolchains select their C library this way.
switches as the driver stores them
expansion: one line per command, one chip per argument
why
prune_options, opts-common.cc:1150) can drop an earlier option that a later Negative() option cancels, and some options (-Wl,, -l) become linker inputs rather than switches. Not modelled: %:function(), target macros such as %a and %1, and -pipe.gcc/<lang>/
Every front end ends in the same handful of calls
A language fills struct lang_hooks lang_hooks = LANG_HOOKS_INITIALIZER; (default in langhooks-def.h:342). compile_file calls lang_hooks.parse_file (toplev.cc:453), and the front end hands each function to cgraph_node::finalize_function (cgraphunit.cc:450) as GENERIC.
From the command line
gcc -fsyntax-only foo.c stops cc1 after the front end, so errors are reported and no code is made. g++ is the same driver as gcc, with C++ defaults such as linking libstdc++.
c/ + c-family/
c_parse_file (c/c-parser.cc:29820) builds GENERIC directly. c-family holds the preprocessor glue, warnings and the attributes shared with C++.
cp/
The largest C-family front end. Templates are instantiated before lowering. cp_genericize (cp/cp-gimplify.cc:2409) removes C++-only tree codes.
gnat1 = GNAT + gigi
The GNAT front end is written in Ada. It builds its own tree, then gigi (ada/gcc-interface/trans.cc:298) calls gnat_to_gnu (:6482) on every node to make GENERIC.
fortran, rust, m2, go, d, cobol
Same contract. Go and D import their front end from an upstream project that other compilers also use.
lto/ and jit/
lto1 is a front end whose parse_file reads GIMPLE back from object files. libgccjit drives the same back end from an API.
finalize_function, nothing in the middle end knows which language it came from, apart from a few lang hooks.GENERIC · GIMPLE · RTL
One statement changes shape three times, and each shape has its dump flag
The function is int f (int a, int b) { return a + b * 4; } compiled for riscv32 at -O2. The outputs are illustrative and abridged.
From the command line
gcc -O2 -c -fdump-tree-original -fdump-tree-optimized -fdump-rtl-expand foo.c writes the three dumps that the cards below show, one file each, next to the object file.
GENERIC
return b * 4 + a;
A language-neutral tree of nested expressions: RETURN_EXPR, PLUS_EXPR, MULT_EXPR.
GIMPLE in SSA
_1 = b_2(D) * 4; _4 = _1 + a_3(D); return _4;
Tuples with at most one operation each. Every name is assigned once.
RTL
(set (reg:SI 137)
(ashift:SI (reg:SI 136)
(const_int 2)))
(set (reg:SI 138)
(plus:SI (reg:SI 137)
(reg:SI 135)))Machine modes and pseudo registers. The multiply became a shift because the target said a shift is cheaper.
Assembly
slli a1,a1,2 add a0,a1,a0 ret
Registers are hard now. Each line is one insn's output template.
-fdump-tree-all, -fdump-ipa-all and -fdump-rtl-all write one file per pass. -fdump-passes lists the passes that run, which is the fastest way to find a dump name.passes.def · cgraphunit.cc
passes.def is the whole optimiser, in order, in 569 lines
symbol_table::compile (cgraphunit.cc:2327) runs the IPA lists over the whole unit, then expand_all_functions runs all_passes once per function. With -flto the run stops after the small IPA passes and continues in the linker.
From the command line
gcc -Q --help=optimizers -O2 lists the -f options that -O2 turns on. -fdump-passes lists the passes. -fopt-info reports what the optimisers did, such as each loop that was vectorized.
config/<cpu>/
A port is a machine description, a hooks table and a stanza in config.gcc
The .md file says which RTL the machine can execute and how to print it. The hooks answer questions the .md cannot: costs, legal addresses, the calling convention. config.gcc picks the files for a triplet.
From the command line
gcc -Q --help=target lists the -m options of the port and their values. gcc -O2 -S -dp foo.c writes assembly with a comment after each instruction that names its pattern.
- expand meets PLUS_EXPR in SImode and calls expand_binop with add_optab.
- optabs.def:118 names the pattern "add$P$a3". For SImode that is addsi3. genopinit built the lookup table from the .md file.
- The define_expand body runs. On riscv64 it emits addsi3_extended and DONE. On riscv32 it falls through and emits its own RTL template.
- Every later pass that changes an insn asks recog whether the result is still a valid define_insn. genrecog built that decision tree.
- final looks up the matched insn's output template in insn_data.
- %i2 adds "i" when operand 2 is a constant, and %~ adds "w" on riscv64. riscv32 prints add a0,a0,a1.
(define_insn "*addsi3" riscv.md:702 [(set (match_operand:SI 0 "register_operand" "=r,r") (plus:SI (match_operand:SI 1 "register_operand" " r,r") (match_operand:SI 2 "arith_operand" " r,I")))] "" ① condition "add%i2%~\t%0,%1,%2" ② output template [(set_attr "type" "arith") (set_attr "mode" "SI")]) ③ attributes
- ①A C condition such as
"TARGET_64BIT". Empty means always available. - ②One template, or one per constraint alternative, or a C block that returns a string.
- ③
typedrives the scheduler'sdefine_insn_reservationautomata.lengthdrives branch shortening.
arith_operand is a define_predicate (predicates.md:26): which operands may match at all. "r,I" are constraints (constraints.md:48): which register class or constant range each alternative accepts, which the register allocator reads.
target.def → targetm
/* target.def:4001 */ DEFHOOK (rtx_costs, …) /* riscv.cc */ #define TARGET_RTX_COSTS riscv_rtx_costs … struct gcc_target targetm = TARGET_INITIALIZER;
genhooks writes the defaults into target-hooks-def.h. A port overrides only what it defines. Defaults live in targhooks.cc and hooks.cc.
tm.h
/* config/aarch64/aarch64.h */
#define UNITS_PER_WORD 8
#define FIRST_PSEUDO_REGISTER …The older interface: #defines gathered into tm.h from config.gcc's tm_file list. New interfaces are hooks. Documented in doc/tm.texi.in.
| config.gcc variable | aarch64-elf value | Role |
|---|---|---|
cpu_type | aarch64 | Directory under config/, and the default for the next three. |
tm_file | elfos.h newlib-stdint.h aarch64/aarch64-elf.h … | Headers concatenated into tm.h, in order. The OS stanza (config.gcc:1218) appends to the CPU default. |
md_file | aarch64/aarch64.md | Root of the machine description, read after common.md. |
out_file | aarch64/aarch64.cc | The port's C++ code and its targetm. |
tm_p_file | aarch64/aarch64-protos.h | Prototypes visible to generated code. |
tmake_file | aarch64/t-aarch64 | Makefile fragments: extra rules, multilib lists. |
extra_objs | aarch64-builtins.o aarch64-sve-builtins*.o … | Port objects linked into cc1. |
extra_options | aarch64/aarch64.opt | The port's -m options. |
libgcc/config.host, so a new target edits both. The variables are documented at config.gcc:67–158.gen*.cc · Makefile.in
33 generator programs turn the .md files into half of cc1's back end
They are built for the build machine with -DGENERATOR_FILE and run during the build. Their output is never committed.
From the command line
No option shows the generators. Their outputs are the insn-*.cc and tm-preds.h files in the gcc/ directory of a build tree.
match.pd
A pattern language for folding: (simplify (plus @0 integer_zerop) @0). genmatch compiles the 11,440 lines into both gimple-match-N.cc and generic-match-N.cc.
GTY markers
GTY(()) expands to nothing for the compiler. gengtype reads it and writes the garbage-collector walkers and PCH writers (gtype-desc.cc, gt-*.h).
.opt files
common.opt, c.opt and each port's .opt become options.cc and options.h, so one record defines the flag, its variable and its help text.
modes and hooks
machmode.def plus the port's *-modes.def become insn-modes.h. target.def becomes target-hooks-def.h and the tm.texi hook text.
lto/ · lto-wrapper.cc · lto-plugin/
With -flto, cc1 writes GIMPLE and the optimiser runs inside the link
The linker plugin is the bridge. It is binutils' plugin API (include/plugin-api.h) on one side and GCC's lto-wrapper on the other.
From the command line
gcc -flto -O2 a.c b.c compiles both files to GIMPLE and optimises them together during the link. For archives of such objects, use gcc-ar and gcc-nm: they run ar and nm with the plugin.
- cc1 streams summaries and function bodies into sections named .gnu.lto_* (lto-section-names.h:27). A fat object also keeps normal code.
- The plugin's claim_file_handler (lto-plugin.c:1407) reads .gnu.lto_.symtab and gives ld the IR symbols.
- After resolution, all_symbols_read_handler runs lto-wrapper with the list of claimed files and their resolutions.
- WPA reads every summary, runs the regular IPA passes over the whole program, and partitions it. lto_balanced_map is the default.
- Each LTRANS job is a normal back end run on one partition, in parallel under -flto=N or the jobserver.
- The plugin hands the real objects back to ld.
- ld links them as if the user had passed them.
lib/bfd-plugins.Makefile.def · configure
A native build compiles GCC three times and compares the last two
The build, host and target machines can all differ. Generators run on the build machine, cc1 runs on the host, and libgcc runs on the target.
From the command line
gcc -v prints the configure command of the compiler in use, after Configured with:. A native build bootstraps by default. --disable-bootstrap builds one stage only.
- The system compiler builds stage1 without optimisation.
- Stage1 builds stage2. Stage2 is the first GCC compiled by this GCC.
- Stage2 builds stage3. Both were produced by compilers with identical source.
- The top-level compare target checks stage2 and stage3 objects byte for byte. A difference means GCC miscompiled itself or is non-deterministic.
gen* programs
Compiled with BUILD_CFLAGS into build/ and run during the make.
gcc/: driver, cc1, lto1
Plus host libraries: libiberty, libcpp, libbacktrace, lto-plugin.
libgcc, libstdc++-v3, libada, libgomp
Built by the new compiler. libgcc implements the libcalls that optabs name: __muldi3, soft-float, unwinding, __emutls_get_address.
Makefile.def lists every host and target module and their dependencies. autogen turns it into Makefile.in.Infrastructure
Four subsystems run under every pass
From the command line
-fplugin=NAME.so loads a plugin into cc1. -fdiagnostics-format=sarif-file writes the warnings and errors as SARIF. --coverage adds the instrumentation that gcov reads.
Garbage collector
Trees, GIMPLE and RTL live in GC memory. ggc_collect runs only between passes and marks from GTY roots. The same walkers write precompiled headers.
Plugins
27 events in plugin.def, such as PLUGIN_PASS_MANAGER_SETUP to insert a pass. Plugins see the internal API, so they rebuild per GCC version.
Diagnostics
One engine for warnings and errors, with text, JSON and SARIF output, and caret locations from libcpp's line maps.
Coverage and profiling
-fprofile-arcs instruments in a GIMPLE pass. libgcov in libgcc writes .gcda files. gcov reads them.
gcc/testsuite · DejaGnu
A test carries its own instructions in comments
From the command line
make check-gcc runs the C suite from the build directory. The results go to gcc/testsuite/gcc/gcc.sum, with one PASS or FAIL line per test, and the commands go to gcc.log.
/* { dg-do compile } */ ① /* { dg-options "-O2 -fdump-tree-optimized" } */ ② /* { dg-require-effective-target int32plus } */ ③ int f (int a, int b) { return a + b * 4; } /* { dg-final { scan-tree-dump-times " \\* 4" 1 "optimized" } } */ ④
- ①preprocess, compile, assemble, link or run. A run test also checks the exit status.
- ②Extra options. The torture directories run every test under a list of option sets.
- ③Effective targets from lib/target-supports.exp skip a test where it cannot apply.
- ④Checks after the compile: scan-tree-dump (scantree.exp), scan-rtl-dump, scan-assembler (scanasm.exp).
make check-gcc RUNTESTFLAGS="dg.exp=pr12345.c". Compare two runs with contrib/compare_tests. gcc.dg and g++.dg hold about 18,500 and 19,000 files, gcc.target/aarch64 about 8,600.Scale
The front ends are larger than the optimiser
Background
What the back end must honour is on the main site
The machine description encodes an ISA. The hooks implement a psABI. The CFI directives that GCC prints feed the unwinder.
What an output template's text becomes once gas encodes it.
What TARGET_FUNCTION_ARG and friends must place, rule by rule.
What pass_thread_prologue_and_epilogue builds.
The .cfi_* directives that dwarf2cfi.cc emits from the prologue.
What except.cc builds call-site tables for.
What -mcmodel changes in the instructions GCC picks.
What %lo, %hi and @PLT operands turn into.
as, ld and the plugin API on the other side of LTO.
Sources
gcc/ of releases/gcc-15 at 15.3.1: gcc.cc · gcc-main.cc · collect2.cc · toplev.cc · langhooks-def.h · c/c-parser.cc · cp/cp-gimplify.cc · cgraphunit.cc · gimplify.cc · passes.def · tree.def · gimple.def · rtl.def · machmode.def · cfgexpand.cc · optabs.def · optabs.cc · recog.h · final.cc · target.def · targhooks.cc · config.gcc · config/riscv/riscv.md · config/riscv/predicates.md · config/riscv/constraints.md · config/riscv/riscv.cc · config/aarch64/aarch64.cc · Makefile.in · match.pd · lto-section-names.h · lto-wrapper.cc · lto/lto.cc · lto/lto-partition.cc · plugin.def · ggc-page.cc · testsuite/lib/scantree.exp · testsuite/lib/scanasm.exp; ../lto-plugin/lto-plugin.c · ../Makefile.def · ../include/plugin-api.h; ada/gcc-interface/trans.cc from FSF history. The IR samples in Fig. 7 are illustrative. Line counts: wc -l, testsuite excluded.