5.7 How a pseudo becomes %rdx: IRA, LRA and final

Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).

The expand dump of count.c is full of registers such as (reg:DI 101). The .s file has %rax, %rdx and sometimes an operand such as 8(%rsp). Between the two, the pseudo registers of RTL became the general registers of x86-64, and some values went to the stack. You look in the dump list for the pass that did it and find one called reload. On x86-64 at the pin, the old reload pass never runs. The dump named reload is written by LRA, and the pass before it, ira, made most of the decisions.

This chapter assumes Chapter 5.2 for dump file names, Chapter 5.3 for how a pass name becomes a -fdump- flag, and Chapter 5.6 for constraints and alternatives in a define_insn. It uses count.c from Chapter 5.1. Register allocation is a deep subject. This chapter does not teach its algorithms. It shows which file decided where a value lives, which dump line records that decision, and how final turns the result into text.

pass_ira and pass_reload: two passes, one table

The two passes are adjacent in passes.def, late in the RTL list (passes.def:511-512):

      NEXT_PASS (pass_ira);
      NEXT_PASS (pass_reload);

Listing 5.7-1: the register allocation passes in the pass list (gcc/passes.def:511-512).

Both are defined in ira.cc. Their descriptors give the names "ira" and "reload" (ira.cc:6103-6136, :6148-6179), so the dump flags are -fdump-rtl-ira and -fdump-rtl-reload. Both gates return !targetm.no_register_allocation, so a target that does not allocate registers at all skips both.

The ira pass is the integrated register allocator. For each pseudo it chooses a hard register, or decides that the pseudo lives in memory. The header comment of ira.cc names the method: "a regional register allocator performing graph coloring on a top-down traversal of nested regions", where a region is the whole function or a loop (ira.cc:21-38). The internals manual describes the same allocator under RTL passes.

IRA does not rewrite the RTL with its answer. It writes the answer into a table:

      hard_regno = ALLOCNO_HARD_REGNO (a);
      regno = ALLOCNO_REGNO (a);
      reg_renumber[regno] = (hard_regno < 0 ? -1 : hard_regno);

Listing 5.7-2: IRA's answer, one entry per pseudo, -1 for memory (gcc/ira.cc:2486-2488), in setup_reg_renumber.

reg_renumber is the "Vector of substitutions of register numbers, used to map pseudo regs into hardware regs" (regs.h:179-186). So the RTL at the end of the .ira dump still uses pseudos. The assignment is in the side table, and the next pass reads it.

The next pass is reload, and its execute calls do_reload. That function picks one of two implementations:

  if (ira_use_lra_p)
    {
      ...
      ira_destroy ();

      lra (ira_dump_file, internal_flag_ira_verbose);
      ...
    }
  else
    {
      df_set_flags (DF_NO_INSN_RESCAN);
      build_insn_chain ();

      need_dce = reload (get_insns (), ira_conflicts_p);
    }

Listing 5.7-3: one pass, two allocators, abridged (gcc/ira.cc:5974-6000).

ira_use_lra_p is set once from a target hook, ira_use_lra_p = targetm.lra_p () (ira.cc:1659). The hook's documentation in target.def says that "The default version of this target hook returns true. New ports should use LRA, and existing ports are encouraged to convert" (target.def:5792-5800), and default_lra_p does return true (targhooks.cc:1317-1320). The x86, Arm and AArch64 back ends at the pin do not override the hook, so they use LRA. LRA reads IRA's table through lra_get_regno_hard_regno, which returns reg_renumber[regno] (lra-int.h:446-450).

Why there are two allocators: ira.cc and lra.cc

The split is a division of work, not two rival algorithms. IRA works on the whole function and decides where each pseudo lives. It knows register classes and costs, but it does not make each instruction valid. LRA, the local register allocator, takes IRA's answer and works one instruction at a time. Its job is in its header comment:

   In brief LRA works by iterative insn process with the final goal is
   to satisfy all insn and address constraints:
     o New reload insns (in brief reloads) and reload pseudos might be
       generated;
     o Some pseudos might be spilled to assign hard registers to
       new reload pseudos;
     o Recalculating spilled pseudo values (rematerialization);
     o Changing spilled pseudos to stack memory or their equivalences;
     o Allocation stack memory changes the address displacement and
       new iteration is needed.

Listing 5.7-4: what LRA is for (gcc/lra.cc:34-43).

The same comment opens with "The Local Register Allocator (LRA) is a replacement of former reload pass" (lra.cc:22-23). That is where the dump name comes from. The pass kept the name reload when LRA replaced the old implementation behind it. Listing 5.7-3 shows that the old implementation is still there for targets that ask for it.

Reading IRA's answer: Disposition: in the .ira dump

Run the allocator dumps on the shared example:

$ gcc -O2 -c -fdump-rtl-ira -fdump-rtl-reload count.c
$ grep -n -A8 '^Disposition:' count.c.*r.ira

The GCC manual lists -fdump-rtl-ira under Developer Options, with the description "Dump after iterated register allocation". The pass is the integrated allocator, as its own header comment says. The same node does not list -fdump-rtl-reload. The flag exists because the pass is named reload.

The Disposition: block is IRA's assignment, printed by one function:

	fprintf (f, " %4d:r%-4d", ALLOCNO_NUM (a), ALLOCNO_REGNO (a));
	if ((bb = ALLOCNO_LOOP_TREE_NODE (a)->bb) != NULL)
	  fprintf (f, "b%-3d", bb->index);
	else
	  fprintf (f, "l%-3d", ALLOCNO_LOOP_TREE_NODE (a)->loop_num);
	if (ALLOCNO_HARD_REGNO (a) >= 0)
	  fprintf (f, " %3d", ALLOCNO_HARD_REGNO (a));
	else
	  fprintf (f, " mem");

Listing 5.7-5: one entry of the Disposition: list (gcc/ira.cc:714-722), in ira_print_disposition.

Each entry is an allocno, IRA's name for the live range of one pseudo in one region (ira.cc:59-60). An entry has four fields: the allocno number, then r and the pseudo number, then b and a basic block or l and a loop, then the hard register. An entry that ends in mem is a pseudo IRA left in memory. The hard register is a number, not a name. On x86-64 the numbers are the constants at the top of i386.md: AX_REG is 0, DX_REG is 1, CX_REG is 2, and R8_REG to R15_REG are 36 to 43 (i386.md:417-460).

Two conditions control the block. It is printed at the end of do_coloring when internal_flag_ira_verbose > 1 (ira-color.cc:3863-3864). That flag comes from -fira-verbose=, whose default is 5 (common.opt:2222-2224), so a plain -fdump-rtl-ira prints it. The GCC manual documents -fira-verbose under Developer Options, including the rule that a value of 10 or more sends the same text to standard error. Also, ira_color runs color, and so do_coloring, only when ira_conflicts_p is true (ira-color.cc:5400-5403). The value is ira_conflicts_p = optimize > 0 (ira.cc:5646). At -O0 the cheaper fast_allocation prints the list instead (ira-color.cc:5377-5378).

The block is IRA's first answer, not its last. color runs move_spill_restore after do_coloring (ira-color.cc:5258-5268), and LRA can still change an assignment. The final word is in the .reload dump.

The constraint that IRA does not settle: *divmod<mode>4

On x86-64, count.c's 64-bit modulo is an instruction with fixed registers. Chapter 5.6 showed how a pattern like this becomes a recogniser. Here are its operand constraints:

(define_insn_and_split "*divmod<mode>4"
  [(set (match_operand:SWIM248 0 "register_operand" "=a")
	(div:SWIM248 (match_operand:SWIM248 2 "register_operand" "0")
		    (match_operand:SWIM248 3 "nonimmediate_operand" "rm")))
   (set (match_operand:SWIM248 1 "register_operand" "=&d")
	(mod:SWIM248 (match_dup 2) (match_dup 3)))
   (clobber (reg:CC FLAGS_REG))]

Listing 5.7-6: the signed divide-and-modulo pattern (gcc/config/i386/i386.md:11607-11613).

The quotient must be in a. The dividend must be in the same register as the quotient (0). The remainder must be in d, and it is an earlyclobber operand (&), written before the instruction has finished with its inputs. The divisor can be in any general register or in memory (rm). The internals manual documents these letters in Simple Constraints, Constraint Modifier Characters and, for a and d, the x86 entry of Machine Constraints.

This is why the chapter title says %rdx. The remainder of v[i] % d cannot go anywhere else. IRA uses constraints to set costs and preferences, and it does not change the instruction. Its header comment says that it "creates copies for operands of an insn which should be assigned to the same hard-register due to constraints in the machine description (it usually results in removing a move generated in reload to satisfy the constraints)" (ira.cc:119-123). So IRA tries to put the dividend and the quotient in one register. When its choice still does not match a constraint, LRA makes the instruction valid with a copy, for example into %rax before the division or out of %rdx after it.

Inside the reload dump: lra_constraints, lra_assign, lra_spill

LRA is a loop. The inner loop fixes instructions and assigns registers until no instruction needs a change. The outer loop then turns any pseudo that is still without a register into memory, which changes addresses, so it goes round again:

  for (;;)
    {
      for (;;)
	{
	  bool reloads_p = lra_constraints (lra_constraint_iter == 0);
	  ...
	    lra_inheritance ();
	  ...
		  bool spill_p = !lra_assign (fails_p);
	  ...
	}
      ...
      if (! lra_need_for_spills_p ())
	break;
      ...
      if (lra_remat ())
      ...
      lra_spill ();
      ...
    }
  ...
  lra_final_code_change ();

Listing 5.7-7: the shape of lra, abridged (gcc/lra.cc:2451-2601).

Each sub-pass writes to the .reload dump whenever the dump is open. Three kinds of line answer most questions.

Choosing alt N in insn U: is written by lra-constraints.cc when it settles which constraint alternative an instruction uses, followed by the pattern name in braces (lra-constraints.cc:4483-4500). final does not read this choice. It finds an alternative again through constrain_operands_cached (recog.cc:2798-2806), as the final.cc section shows.

Inserting insn reload before: and after: follow an instruction that needed a copy to satisfy a constraint. lra_process_new_insns prints the instruction, then the new copies, in slim RTL (lra.cc:1918-1968). The title string comes from its caller, for example lra-constraints.cc:4944. If IRA's choice for the modulo in Listing 5.7-6 does not match 0 or =&d, the copy that fixes it is recorded here.

Slot N regnos (width = W): R... means pseudos went to the stack. It is printed by lra_spill after it gives stack slots to the pseudos that have no hard register:

  if (lra_dump_file != NULL)
    {
      for (i = 0; i < slots_num; i++)
	{
	  fprintf (lra_dump_file, "  Slot %d regnos (width = ", i);
	  print_dec (slots[i].size, lra_dump_file, SIGNED);
	  fprintf (lra_dump_file, "):");

Listing 5.7-8: the spill record (gcc/lra-spills.cc:664-670).

lra_spill runs only when lra_need_for_spills_p finds a referenced pseudo whose reg_renumber entry is still negative (lra-spills.cc:603-614). So a Slot line in the .reload dump is the proof that a value lives on the stack. The numbers after the colon are the pseudos that share that slot. A pseudo can share a slot with another only when they do not conflict, as the file's header comment explains (lra-spills.cc:22-35).

At the end, lra_final_code_change replaces each pseudo with its hard register in place, by SET_REGNO (regno_reg_rtx[i], hard_regno) (lra-spills.cc:741-744). The register keeps its old number in ORIGINAL_REGNO, which "for a pseudo register turned into a hard reg ... will hold the old pseudo register number" (rtl.h:1928-1931). The RTL printer shows both: the hard register number and name (print-rtl.cc:549-554), then the old pseudo number in brackets (:603-604). That is how you follow pseudo 101 from the expand dump to %rdx in the RTL at the end of the .reload dump.

Forcing a spill with -ffixed-reg

count.c has few live values, and x86-64 has enough registers for them. To see a Slot line, take registers away. -ffixed-reg makes the register named reg unavailable to generated code. The GCC manual documents it under Code Gen Options, and says that the names come from the target's REGISTER_NAMES:

$ gcc -O2 -S -dp -fdump-rtl-ira -fdump-rtl-reload \
      -ffixed-rbx -ffixed-rbp -ffixed-r8 -ffixed-r9 -ffixed-r10 \
      -ffixed-r11 -ffixed-r12 -ffixed-r13 -ffixed-r14 -ffixed-r15 \
      count.c
$ grep -n ' mem' count.c.*r.ira
$ grep -n 'Slot' count.c.*r.reload
$ grep -n 'idiv' count.s

This book did not run these commands at the pin. The machine it was written on has no GCC. What follows is what the source says about them, not an output transcript. Your pseudo numbers and stack offsets will be your own.

The names are accepted. decode_reg_name_and_count matches r8 to r15 against REGISTER_NAMES, and rbx and rbp against the x86 ADDITIONAL_REGISTER_NAMES table (varasm.cc:1012-1047, i386.h:2079-2084). fix_register rejects a request for the stack or frame pointer only when it is not "fixed and call-used". -ffixed- asks for exactly that (opts-global.cc:427-430, reginfo.cc:674-720). A fixed register reaches IRA through fixed_reg_set and fixed_nonglobal_reg_set, and IRA copies the second into no_unit_alloc_regs (reginfo.cc:377-378, :410, ira.cc:516).

That leaves five general registers: %rax, %rdx, %rcx, %rsi and %rdi. At the division, Listing 5.7-6 takes two of them. The loop needs at least four more values across the division: something that says where it is in v, something that says where to stop, count, and d. Six values do not fit in five registers, so at that point at least one value lives somewhere else. The divisor's rm constraint means idiv can read d from memory directly.

"Somewhere else" can mean a register of another class. lra-spills.cc can spill a general register into a vector register when the target's TARGET_SPILL_CLASS hook allows it. The dump then says Spill rN into hrM (lra-spills.cc:48-53, :298-299). The x86 hook never allows it at the pin, because its condition starts with a literal 0 &&:

ix86_spill_class (reg_class_t rclass, machine_mode mode)
{
  if (0 && TARGET_GENERAL_REGS_SSE_SPILL

Listing 5.7-9: x86 spilling to SSE registers, switched off (gcc/config/i386/i386.cc:25103-25105).

So on x86-64 the value goes to a stack slot, and you can expect a Slot line in the .reload dump. Expect a mem entry in IRA's Disposition: too, unless the decision to spill was LRA's and not IRA's.

final.cc: from RTL to text, and -dp

final is the last pass inside pass_late_compilation (passes.def:549-564). It is not the last RTL pass: pass_df_finish follows it (passes.def:565), with the dump name dfinish (df-core.cc:831). The execute of pass_final calls rest_of_handle_final, which calls final_start_function_1 for the start of the function and final_1 for the body (final.cc:4235-4250). final_1 walks the instructions in order and calls final_scan_insn on each (final.cc:1963-1983). For an ordinary instruction, the work is in this order:

	/* Try to recognize the instruction.
	   If successful, verify that the operands satisfy the
	   constraints for the instruction.  Crash if they don't,
	   since `reload' should have changed them so that they do.  */

	insn_code_number = recog_memoized (insn);
	...
	if (! constrain_operands_cached (insn, 1))
	  fatal_insn_not_found (insn);
	...
	/* Find the proper template for this insn.  */
	templ = get_insn_template (insn_code_number, insn);
	...
	/* Output assembler code from the template.  */
	output_asm_insn (templ, recog_data.operand);

Listing 5.7-10: one instruction becomes text, abridged (gcc/final.cc:2741-2846), in final_scan_insn_1.

The comment states the contract between the allocator and final. After reload, which on most targets means LRA, every instruction satisfies one alternative of its pattern. constrain_operands finds it and sets which_alternative (recog.cc:3096-3104). get_insn_template uses that number to pick the alternative's output template (final.cc:2022-2038). Templates come from the .md file through the generated insn-output.cc, which genoutput writes. The internals manual names that file in its RTL passes entry for Final.

output_asm_insn copies the template and expands each %N through output_operand (final.cc:3543-3553). output_operand asserts that no pseudo reaches it:

  /* X must not be a pseudo reg.  */
  if (!targetm.no_register_allocation)
    gcc_assert (!x || !REG_P (x) || REGNO (x) < FIRST_PSEUDO_REGISTER);

Listing 5.7-11: the last check on the allocator (gcc/final.cc:3637-3639).

The target's TARGET_PRINT_OPERAND hook then prints the operand. The template of *divmod<mode>4 in Listing 5.7-6 is "#", and its split condition is "reload_completed" (i386.md:11614-11616). After reload it becomes a sign extension and an instruction that matches *<u>divmod<mode>4_noext, whose template is "<sgnprefix>div{<imodesuffix>}\t%3" (i386.md:11868-11878). With div and DImode the iterators give idiv and the suffix q (i386.md:1101-1103, :1239). %3 is the divisor. If d was spilled, %3 prints as a stack address and not a register name.

-dp: which pattern and which alternative

-dp makes final write a comment after each instruction. The GCC manual documents it under Developer Options, with -dP, which also prints the RTL. -dp sets flag_print_asm_name (opts.cc:3657-3659). The comment is written by output_asm_name:

      fprintf (asm_out_file, "\t%s %d\t",
	       ASM_COMMENT_START, INSN_UID (debug_insn));

      fprintf (asm_out_file, "[c=%d",
	       insn_cost (debug_insn, optimize_insn_for_speed_p ()));
      if (HAVE_ATTR_length)
	fprintf (asm_out_file, " l=%d",
		 get_attr_length (debug_insn));
      fprintf (asm_out_file, "]  ");

      int num = INSN_CODE (debug_insn);
      fprintf (asm_out_file, "%s", insn_data[num].name);
      if (insn_data[num].n_alternatives > 1)
	fprintf (asm_out_file, "/%d", which_alternative);

Listing 5.7-12: the -dp comment (gcc/final.cc:3213-3226).

So each annotated line has this form, with # as the comment start on x86-64 (x86-64.h:26-27):

	<instruction>	# <insn UID>	[c=<cost> l=<length>]  <pattern name>/<alternative>

The UID is the number of the instruction in the RTL dumps. The /N part appears only for a pattern with more than one alternative. It is the alternative that constrain_operands found in final, so it can differ from a Choosing alt line if passes after reload changed the instruction, or if two alternatives match. With -dp, a line of assembly leads back to a pattern in the .md file and to an instruction in the dumps.

reload1.cc is still in the tree

The old pass is still built. Its header comment in reload1.cc describes the method. Reload frees some hard registers as "reload regs" and copies values into them where an instruction needs a register. It spills the pseudos that lived in those registers (reload1.cc:47-79). A target gets it by returning false from TARGET_LRA_P. Alpha does so with hook_bool_void_false (alpha.cc:10813-10814). SH returns sh_lra_flag (sh.cc:12611-12614), which is the -mlra option with an initial value of 0 (sh.opt:301-303). So SH uses reload unless you pass -mlra. The GCC manual's target pages show the state of a few more. The PDP-11 Options and VAX Options say that -mlra selects LRA and that reload is the default there. The ARC Options and FT32 Options say that -mlra "Does nothing" now.

On such a target the .reload dump is written by reload1.cc, and the LRA lines in this chapter do not appear in it. The Disposition: block in the .ira dump is the same on both.

Three things to carry away

IRA decides, LRA makes it valid. IRA writes one hard register or -1 per pseudo into reg_renumber, and LRA fixes each instruction to its constraints, adding copies and stack slots.

The reload dump is LRA's on most targets. do_reload runs lra when targetm.lra_p () is true, which is the default.

final trusts the allocator. It picks the alternative that the operands satisfy, prints that alternative's template, and crashes if a pseudo or an invalid operand reaches it.

Things that surprise people

Disposition: is not the final allocation. It is printed after coloring, before move_spill_restore and before LRA. Check the .reload dump for the final answer.

x86 never spills general registers to SSE registers at the pin. The tuning flag X86_TUNE_GENERAL_REGS_SSE_SPILL is still defined (x86-tune.def:432-435), but ix86_spill_class disables it with 0 &&.

Documentation coverage

The internals manual describes the allocator, reload, LRA and final in its RTL passes node (gcc/doc/passes.texi:1057-1118 and :1160-1164). Its file list for LRA names lra-assign.c, but the file at the pin is lra-assigns.cc. The TARGET_LRA_P and TARGET_SPILL_CLASS hooks are in the Register Classes node (gcc/doc/tm.texi:3050 and :3113). Constraint letters are in Simple Constraints (gcc/doc/md.texi:1293), Constraint Modifier Characters (md.texi:1773) and Machine Constraints (md.texi:1916, the x86 entry at :4042).

The GCC manual documents -ffixed-reg in Code Gen Options (gcc/doc/invoke.texi:20059). Developer Options documents -fdump-rtl-ira (invoke.texi:20526), -fdump-rtl-postreload (:20560), -dp and -dP (:20660, :20666) and -fira-verbose (:21443). The -mlra entries are at invoke.texi:23282 (ARC), :26859 (FT32), :30922 (PDP-11) and :34802 (VAX).

What is not documented:

  • That -fdump-rtl-reload exists, and that on LRA targets it dumps LRA. The Developer Options list skips it, and calls IRA "iterated" register allocation.
  • The format of IRA's Disposition: block, and that a hard register appears there as a number from the target's register constants.
  • The LRA dump vocabulary: Choosing alt, Inserting insn reload, Slot, Spill rN into hrM.
  • That reg_renumber is the handoff from IRA to LRA, and that RTL after ira still uses pseudos.
  • The -dp comment format beyond "pattern and alternative", including the insn UID that links it to the RTL dumps.
  • That the x86 spill class is disabled in the source.
  • SH's -mlra. The SH Options node does not list it.

Next: Part VI starts with the testsuite, where a dg-final line scans the dumps and assembly that this part taught you to read.


All source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0). Line numbers in other releases will differ; the surrounding code rarely does. Where behaviour itself changed across a major version, it is flagged inline.