5.5 Expand and optabs: where the target first appears

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

Compile count.c for a Cortex-M4, and the assembly calls __aeabi_ldivmod, a function that your source never names. Compile the same file for x86-64, and there is no call. The v[i] % d is one division instruction. In GIMPLE, that line is the same % statement on both targets. Something after GIMPLE made the decision.

$ gcc -O2 -S -o - count.c | grep ldivmod          # no match
$ arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -S -o - count.c | grep ldivmod

That something is the expand pass. Expand asks the target how to do each operation, and it asks through optabs: one table per operation, indexed by machine mode, that holds an instruction pattern or a library function name. When the table has no pattern for the mode, expand builds the operation from other entries, and a library call is the last of them.

This chapter assumes Chapter 5.1, for count.c and the three representations, Chapter 5.2, for the dump file names, and Chapter 5.3, for the pass list that pass_expand belongs to. Chapter 4.1 explains the library that supplies __aeabi_ldivmod.

pass_expand::execute in cfgexpand.cc: out of SSA, then block by block

Chapter 5.1 showed the descriptor of pass_expand (Listing 5.1-12) and its place in passes.def (Listing 5.1-13). The pass requires SSA GIMPLE and a CFG, provides PROP_rtl, and destroys the GIMPLE. It belongs to all_passes, the same list as the RTL passes (passes.def:188, :453-457), and Chapter 5.3 explains the lists. It is an RTL_PASS, so the pass manager files its dump with the RTL dumps, under the option -fdump-rtl-expand (passes.cc:860-875).

These are the main steps of pass_expand::execute:

  1. It takes the function out of SSA form. rewrite_out_of_ssa groups the SSA names into partitions, and each partition gets one pseudo register (cfgexpand.cc:7011-7013). Chapter 5.1 explained pseudo registers. Register allocation assigns hardware registers to them later.
  2. It removes the PHI nodes. expand_phi_nodes puts RTL copies on the CFG edges instead (:7209, tree-outof-ssa.cc:1011-1014).
  3. It expands the basic blocks in order (cfgexpand.cc:7230-7232).

The CFG survives the change. The comment above the descriptor says that the conversion is "per basic block" and that it preserves and updates the tree CFG (:6962-6969).

expand_gimple_stmt and TER: where the RTL for a statement goes

Each statement in a block goes to expand_gimple_stmt, with one exception:

	      def_operand_p def_p;
	      def_p = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF);

	      if (def_p != NULL)
		{
		  /* Ignore this stmt if it is in the list of
		     replaceable expressions.  */
		  if (SA.values
		      && bitmap_bit_p (SA.values,
				       SSA_NAME_VERSION (DEF_FROM_PTR (def_p))))
		    continue;
		}
	      last = expand_gimple_stmt (stmt);
	      maybe_dump_rtl_for_gimple_stmt (stmt, last);

Listing 5.5-1: statements that TER forwarded are skipped (gcc/cfgexpand.cc:6471-6484).

SA.values holds the result of TER, temporary expression replacement. rewrite_out_of_ssa runs TER when -ftree-ter is in effect (tree-outof-ssa.cc:1408, :1082-1084). -O1 and higher turn that option on (opts.cc:606). The structure that carries the result says: "For an SSA name version V bit V is set iff TER decided that its definition should be forwarded" (tree-outof-ssa.h:31-33). Expand does not expand a forwarded statement at its own position. When expand finds that SSA name as an operand of a later statement, it gets the defining statement and expands it there (expr.cc:11374-11386). So expand can see v[i] % d == 0 as one expression, and not as two statements.

This is important when you read the dump. With the details option, expand writes each statement that it expands, and then the RTL that it emitted for that statement:

static void
maybe_dump_rtl_for_gimple_stmt (gimple *stmt, rtx_insn *since)
{
  if (dump_file && (dump_flags & TDF_DETAILS))
    {
      fprintf (dump_file, "\n;; ");
      print_gimple_stmt (dump_file, stmt, 0,
			 TDF_SLIM | (dump_flags & TDF_LINENO));
      fprintf (dump_file, "\n");

      print_rtl (dump_file, since ? NEXT_INSN (since) : since);
    }
}

Listing 5.5-2: the ;; header in the expand dump (gcc/cfgexpand.cc:2754-2765).

A forwarded statement gets no ;; header. If TER forwards the % into the comparison that tests its result, the RTL for the modulo is under the if. The same dump tells you which names TER forwarded. Before the first block, it lists them under the heading Replacing Expressions, one replace with --> line for each name (tree-ssa-ter.cc:745-761, called at tree-outof-ssa.cc:1085-1086).

From the statement, the path to the division code is short. An assignment to an SSA name goes to expand_expr_real_gassign (cfgexpand.cc:4301), which collects the operation code and its operands and calls expand_expr_real_2 (expr.cc:11200-11203). That function is one large switch on the tree code. For TRUNC_MOD_EXPR it expands the two operands and calls expand_expr_divmod (expr.cc:10381-10406). That helper has one special case. At -O2, if both operands are "known to be positive when interpreted as signed", it expands the operation as signed and as unsigned. Then it keeps the cheaper sequence (:9698-9740). In count.c, nothing tells the compiler that v[i] and d are positive. So the remainder goes directly to expand_divmod in expmed.cc (:9742).

The optab table: optabs.def and optab_handler

Each operation that expand can ask about has an entry in optabs.def. These are the entries for division:

OPTAB_NL(sdiv_optab, "div$a3", DIV, "div", '3', gen_int_fp_signed_fixed_libfunc)
...
OPTAB_NC(sdivmod_optab, "divmod$a4", UNKNOWN)
OPTAB_NC(udivmod_optab, "udivmod$a4", UNKNOWN)
OPTAB_NL(smod_optab, "mod$a3", MOD, "mod", '3', gen_int_libfunc)
OPTAB_NL(umod_optab, "umod$a3", UMOD, "umod", '3', gen_int_libfunc)

Listing 5.5-3: the division optabs, abridged (gcc/optabs.def:139, :146-149).

An OPTAB_NL line gives the optab, the standard pattern name, the RTL code, and three fields that make a default library function name. $a stands for the mode, so "mod$a3" in DImode is the pattern name moddi3. The comment at the top of the file explains the letters (optabs.def:20-46). An OPTAB_NC line has no library fields. So sdivmod_optab has a pattern name, divmod$a4, but no default library function (gensupport.cc:3768).

One function asks the question:

/* Return the insn used to implement mode MODE of OP, or CODE_FOR_nothing
   if the target does not have such an insn.  */

inline enum insn_code
optab_handler (optab op, machine_mode mode)
{
  unsigned scode = (op << 20) | mode;
  gcc_assert (op > LAST_CONV_OPTAB);
  return raw_optab_handler (scode);
}

Listing 5.5-4: optab_handler (gcc/optabs-query.h:34-43).

The answer is an insn_code, which is the number of one named pattern in the machine description of the target, or CODE_FOR_nothing. The build generates the table behind raw_optab_handler from the .md files. The table gives a pattern only while the condition of that pattern is true for the target options of the current function (genopinit.cc:405, :461-468). Thus -mcpu and -m32 can change the answer. Chapter 5.6 explains how a define_expand named divmoddi4 becomes CODE_FOR_divmoddi4.

The internals manual documents the contract of each standard name, under Standard Pattern Names For Generation: what each operand means, and which names a port should define. That node is the list of questions that expand can ask. Read it together with optabs.def.

optab_libfunc and set_optab_libfunc: the library column

The table has a second column. optab_libfunc (optab, mode) gives the library function for the operation, or null (optabs-libfuncs.cc:102-135). GCC makes the default names when it first needs them, from the fields in optabs.def: two underscores, the operation name, the mode name in lower case, and the number of operands (:137-149). Thus smod_optab in DImode is __moddi3. For an integer operation, gen_int_libfunc makes a name only for modes between one word and two words wide, or as wide as long long if that is wider (:187-205).

A port changes this column in its TARGET_INIT_LIBFUNCS hook. init_optabs fills the pattern column from the machine description, sets some fixed names, and then calls the hook (optabs-libfuncs.cc:871, :905). The hook calls set_optab_libfunc, which accepts a null name (:807-829). A null entry stays null, because GCC makes a default name only when the table has no entry for that optab and mode (:120-131). So a port can remove a default name, and not only change it. The internals manual documents the hook under Implicit Calls to Library Routines.

optab_methods: pattern, wider mode, library call

The functions that read the table do not stop at the first "no". Each caller passes a method that says how far the fallback can go:

/* Passed to expand_simple_binop and expand_binop to say which options
   to try to use if the requested operation can't be open-coded on the
   requisite mode.  Either OPTAB_LIB or OPTAB_LIB_WIDEN says try using
   a library call.  Either OPTAB_WIDEN or OPTAB_LIB_WIDEN says try
   using a wider mode.  OPTAB_MUST_WIDEN says try widening and don't
   try anything else.  */

enum optab_methods
{
  OPTAB_DIRECT,
  OPTAB_LIB,
  OPTAB_WIDEN,
  OPTAB_LIB_WIDEN,
  OPTAB_MUST_WIDEN
};

Listing 5.5-5: the fallback methods (gcc/optabs.h:168-183).

expand_binop expands most operations with two operands. It tries these in order, and the method limits each step:

  1. A pattern in the requested mode (optabs.cc:1529-1548).
  2. A pattern in a wider mode (:1647-1652).
  3. A sequence of word-sized operations. GCC has sequences for logical operations one word at a time, double-word shifts, additions with carries, multiplications, and a modulo by a constant (:1720, :1773, :1975, :2097, :2145).
  4. A library function in the requested mode (:2193-2238).
  5. A library function in a wider mode (:2240-2268).

A library call does not appear in the RTL as a plain call. Expand puts the call in a block. The last instruction in the block has a REG_EQUAL note with the operation, for example (mod:DI a b) (optabs.cc:2228-2233, :4164-4173). In the words of the comment on emit_libcall_block, the result is "logically equivalent to" that operation, and the note tells the RTL passes so.

expand_divmod: the remainder ladder

Division and modulo do not go to expand_binop directly. They go to expand_divmod, because a target can have a division pattern, a modulo pattern, one pattern that gives both results, or none. For a constant divisor, expand_divmod has long special cases. In count.c, d is a parameter, so expand gets to the general code at the end.

First, expand_divmod selects a compute mode. This is the first mode, from the mode of the operands upwards, that has a pattern for division or for division-and-modulo. If there is none, it is the first mode that has a library function for one of them (expmed.cc:4366-4386). Then it starts on the remainder:

	  /* Try to produce the remainder without producing the quotient.
	     If we seem to have a divmod pattern that does not require widening,
	     don't try widening here.  We should really have a WIDEN argument
	     to expand_twoval_binop, since what we'd really like to do here is
	     1) try a mod insn in compute_mode
	     2) try a divmod insn in compute_mode
	     3) try a div insn in compute_mode and multiply-subtract to get
	        remainder
	     4) try the same things with widening allowed.  */
	  remainder
	    = sign_expand_binop (compute_mode, umod_optab, smod_optab,
				 op0, op1, target,
				 unsignedp,
				 ((optab_handler (optab2, compute_mode)
				   != CODE_FOR_nothing)
				  ? OPTAB_DIRECT : OPTAB_WIDEN));
	  if (remainder == 0)
	    {
	      /* No luck there.  Can we do remainder and divide at once
		 without a library call?  */
	      remainder = gen_reg_rtx (compute_mode);
	      if (! expand_twoval_binop ((unsignedp
					  ? udivmod_optab
					  : sdivmod_optab),
					 op0, op1,
					 NULL_RTX, remainder, unsignedp))
		remainder = 0;
	    }

Listing 5.5-6: patterns first (gcc/expmed.cc:5272-5299).

If both fail, expand_divmod tries a division pattern, "but not a library call" (:5305-5333). With a quotient, it computes the remainder as X - Y * (X / Y) (:5365-5371). Without a quotient, only library functions are left:

	  /* No divide instruction either.  Use library for remainder.  */
	  remainder = sign_expand_binop (compute_mode, umod_optab, smod_optab,
					 op0, op1, target,
					 unsignedp, methods);
	  /* No remainder function.  Try a quotient-and-remainder
	     function, keeping the remainder.  */
	  if (!remainder
	      && (methods == OPTAB_LIB || methods == OPTAB_LIB_WIDEN))
	    {
	      remainder = gen_reg_rtx (compute_mode);
	      if (!expand_twoval_binop_libfunc
		  (unsignedp ? udivmod_optab : sdivmod_optab,
		   op0, op1,
		   NULL_RTX, remainder,
		   unsignedp ? UMOD : MOD))
		remainder = NULL_RTX;
	    }

Listing 5.5-7: library functions last (gcc/expmed.cc:5345-5361).

methods is OPTAB_LIB_WIDEN here, which is the default value of that parameter (expmed.h:713-714). For the long long remainder in count.c, the two targets give these answers:

StepQuestionx86-64arm-none-eabi, Cortex-M4
1mod pattern in DImode?nono
2divmod pattern in DImode?divmoddi4no
3div pattern in DImode?not askedno
4mod library function?not askednull, set by the port
5divmod library function?not asked__aeabi_ldivmod

The next two sections show where each answer comes from.

x86-64: divmoddi4 answers step 2

Chapter 5.1 showed the pattern that answers step 2, as Listing 5.1-11: one <u>divmod<mode>4 expander in i386.md that sets a div and a mod in one parallel, with a DImode form only for TARGET_64BIT. In the optab table, its DImode signed form is the entry for sdivmod_optab, divmoddi4 (optabs.def:146). i386.md has no mod pattern, and its div<mode>3 pattern is for floating-point modes only (i386.md:11346-11350). The internals manual recommends this design for a machine with an instruction that gives both results. Such a port defines divmodm4, and it does not define divm3 or modm3 (md.texi:6209-6213).

So step 1 fails and step 2 succeeds. expand_twoval_binop gets the pattern from the optab and calls maybe_expand_insn (optabs.cc:2475-2493). That call is the boundary between expand and the machine description:

rtx_insn *
maybe_gen_insn (enum insn_code icode, unsigned int nops,
		class expand_operand *ops)
{
  gcc_assert (nops == (unsigned int) insn_data[(int) icode].n_generator_args);
  if (!maybe_legitimize_operands (icode, 0, nops, ops))
    return NULL;

  switch (nops)
    {
    ...
    case 4:
      return GEN_FCN (icode) (ops[0].value, ops[1].value, ops[2].value,
			      ops[3].value);

Listing 5.5-8: expand calls the generator of the pattern, abridged (gcc/optabs.cc:8177-8197).

maybe_legitimize_operands tries to make each operand satisfy the predicate of the pattern, and fails without emitting code if it cannot (:8131-8170). GEN_FCN (icode) is insn_data[icode].genfun (genopinit.cc:275), a function that the build generates from the pattern. Here expand stops and the machine description starts. Chapter 5.6 follows the generator.

The expander has no C body, so the RTL that it emits is its template: the parallel of Listing 5.1-11, with a div:DI and a mod:DI in two pseudo registers. count.c uses only the mod:DI result.

Cortex-M4: __aeabi_ldivmod from arm_init_libfuncs

Chapter 5.1 showed that the Arm port defines integer division only in SImode (arm.md:5129-5153). Its modsi3 pattern is also for SImode only, and it accepts only a constant divisor (arm.md:12459-12470). So steps 1 to 3 fail for DImode.

Step 4 asks for a modulo library function, and the port removed it:

  /* Long long.  Table 9.  */
  set_optab_libfunc (smul_optab, DImode, "__aeabi_lmul");
  set_optab_libfunc (sdivmod_optab, DImode, "__aeabi_ldivmod");
  set_optab_libfunc (udivmod_optab, DImode, "__aeabi_uldivmod");
  ...
  /* We don't have mod libcalls.  Fortunately gcc knows how to use the
     divmod libcalls instead.  */
  set_optab_libfunc (smod_optab, DImode, NULL);
  set_optab_libfunc (umod_optab, DImode, NULL);
  set_optab_libfunc (smod_optab, SImode, NULL);
  set_optab_libfunc (umod_optab, SImode, NULL);

Listing 5.5-9: arm_init_libfuncs, abridged (gcc/config/arm/arm.cc:2637-2640, :2668-2673).

arm_init_libfuncs is the TARGET_INIT_LIBFUNCS hook of the port (arm.cc:540-541). It sets these names only for the BPABI (:2573-2576), which arm-none-eabi uses, as Chapter 5.1 showed. Without the null entries, step 4 would find the default name __moddi3.

Step 5 finds __aeabi_ldivmod and keeps half of its result:

  /* The value returned by the library function will have twice as
     many bits as the nominal MODE.  */
  auto return_size = 2 * GET_MODE_BITSIZE (mode);
  if (!smallest_int_mode_for_size (return_size).exists (&libval_mode))
    return false;

  start_sequence ();
  libval = emit_library_call_value (libfunc, NULL_RTX, LCT_CONST,
				    libval_mode,
				    op0, mode,
				    op1, mode);
  /* Get the part of VAL containing the value that we want.  */
  libval = simplify_gen_subreg (mode, libval, libval_mode,
				targ0 ? 0 : GET_MODE_SIZE (mode));
  insns = get_insns ();
  end_sequence ();
  /* Move the into the desired location.  */
  emit_libcall_block (insns, targ0 ? targ0 : targ1, libval,
		      gen_rtx_fmt_ee (code, mode, op0, op1));

Listing 5.5-10: expand_twoval_binop_libfunc (gcc/optabs.cc:2553-2571).

For two DImode operands, the call returns a TImode value, and the remainder is the second half. The function in libgcc has the same contract. For a 32-bit Arm core, libgcc builds it from bpabi.S (lib1funcs.S:2258-2264). The comment there says that the quotient comes back in r0:r1 and the remainder in r2:r3 (libgcc/config/arm/bpabi.S:174-184). The REG_EQUAL note on the final move records (mod:DI op0 op1).

The calling convention is in the RTL from this point. emit_library_call_value_1 asks the target hook function_arg for the register of each argument (calls.cc:4412) and hard_libcall_value for the register of the result (:4776). Then emit_call_1 emits the call instruction (:4794). So the expand dump for the Cortex-M4 has moves into hard registers, a call_insn to a symbol_ref named __aeabi_ldivmod, and a move out of the TImode result.

The mode changes the answer: int on Cortex-M4 and Cortex-M0

Change the type of v and d to int, and the Cortex-M4 answer changes. The divsi3 pattern has the condition TARGET_IDIV (arm.md:5129-5140). For Thumb code, that condition is the hardware-divide bit of the architecture (arm.h:354-355, arm.cc:3933). The Cortex-M4 is an armv7e-m core. Its feature group, ARMv7em, includes ARMv7m, which includes tdiv (arm-cpus.in:1266-1274, :568-573, :293-294). Step 1 finds the modsi3 pattern, but that pattern wants a constant divisor, and d is in a register. maybe_legitimize_operands rejects the operand, and expand continues. Step 2 finds no pattern. Step 3 succeeds, and expand emits a 32-bit division, a multiplication and a subtraction.

The Cortex-M0 is an armv6s-m core, and its feature group has no tdiv (arm-cpus.in:474-478, :285). There, steps 1 to 4 fail, and step 5 finds __aeabi_idivmod (arm.cc:2648). It is the same C, the same ladder, and a different answer for each core.

Before expand: .DIVMOD in pass_optimize_widening_mul

Expand is where the target first changes the representation. It is not the only pass that reads the optab tables. If a function computes a / b and a % b, the widening_mul pass (passes.def:364) can replace both with one call to the internal function DIVMOD. It does this only when target_supports_divmod_p agrees (tree-ssa-math-opts.cc:5650-5673). That needs a divmod pattern, or a divmod library function together with the TARGET_EXPAND_DIVMOD_LIBFUNC hook and no division pattern in that mode or a wider one. The Arm port defines the hook (arm.cc:800-801).

count.c has a % and no /. The pass does not change a modulo that has no matching division (tree-ssa-math-opts.cc:5797, :5823-5824). That is why the GIMPLE for count.c has the same % statement on both targets. If the loop also used v[i] / d, both targets would pass that test: x86-64 has divmoddi4, and the Cortex-M4 has __aeabi_ldivmod and the hook. The GIMPLE could then change before expand runs.

Seeing it: -fdump-rtl-expand-details

The GCC manual documents -fdump-rtl-expand ("Dump after RTL generation") and the details option under Developer Options, and -mcpu under ARM Options. Compile count.c once for each target, in two directories. A compile with -c and no -o writes its dumps to the current directory (gcc.cc:5113-5118). Both compilers give the expand dump the same name, because both ports insert their own passes after expand (i386-passes.def:27-39, arm-passes.def:21). Chapter 5.2 explains the numbers.

$ mkdir x86 cm4
$ (cd x86 && gcc -O2 -c -fdump-rtl-expand-details ../count.c)
$ (cd cm4 && arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -c \
      -fdump-rtl-expand-details ../count.c)
$ grep -n 'mod:DI' x86/count.c.*r.expand cm4/count.c.*r.expand
$ grep -n 'ldivmod' cm4/count.c.*r.expand

The two dumps were not produced for this chapter. The source shows what to look for. Both files contain mod:DI. In x86, it is in the parallel of Listing 5.1-11. In cm4, it is in the REG_EQUAL note after the call, and the second grep finds the symbol_ref in the call_insn. Search for the ;; header of each statement to find the GIMPLE that the RTL came from.

Three things to carry away

Expand asks the target about each operation, through one table. optab_handler gives a pattern or CODE_FOR_nothing, and optab_libfunc gives a function name or null.

A library call is the last step of the ladder, not a separate mechanism. expand_divmod tries a modulo pattern, a division-and-modulo pattern and a division pattern before it asks for a library function.

The port supplies the library names. TARGET_INIT_LIBFUNCS replaces the default names, and a null entry removes one. That is why the Cortex-M4 calls __aeabi_ldivmod and never __moddi3.

Things that surprise people

-O0 does not remove the call. The ladder in expand_divmod is the only way that expand can compute a long long remainder on the Cortex-M4. It is not an optimisation. At -O0 TER is off, so the % gets its own ;; header in the details dump.

A core with a division instruction can still call a library function. The Cortex-M4 divides 32-bit values in hardware. A long long modulo is still a call.

The RTL still says mod. After the call, a REG_EQUAL note records the operation that the call computes.

x86-64 has no moddi3 pattern. The remainder is the second output of divmoddi4.

Documentation coverage

The GCC manual documents -fdump-rtl-expand and the details option in Developer Options (gcc/doc/invoke.texi:20496-20498 and :20931-20933), and -mcpu in ARM Options (:24131). The internals manual documents the standard pattern names in Standard Names (gcc/doc/md.texi:4798), with divmodm4 at :6203-6219 and modm3 at :5551. It documents TARGET_INIT_LIBFUNCS and TARGET_EXPAND_DIVMOD_LIBFUNC in Library Calls (gcc/doc/tm.texi:5866-5874 and :7905-7908), and the default __moddi3 in Integer library routines (gcc/doc/libgcc.texi:84). Its RTL passes node lists the source files of RTL generation (gcc/doc/passes.texi:878-898).

What is not documented:

  • That cfgexpand.cc is the entry point of RTL generation. The list in the RTL passes node does not name it.
  • That TER moves the RTL of a forwarded statement under the statement that uses it, in the details dump, and that the same dump lists the forwarded names under Replacing Expressions.
  • The order in which expand_binop tries a pattern, a wider mode, word-sized operations and library functions.
  • The order of the remainder ladder in expand_divmod, and that it asks for a library function only after three pattern attempts.
  • That a null set_optab_libfunc entry stops GCC from making the default name.
  • That the Arm port has no modulo library functions and uses the remainder half of __aeabi_ldivmod. The Arm Run-time ABI defines that function, and no GCC manual names it.
  • The TARGET_INIT_LIBFUNCS text says that set_optab_libfunc and init_one_libfunc are in optabs.cc. At the pin they are in optabs-libfuncs.cc (:781, :807). The text comes from target.def:2658.

Next: how the divmod<mode>4 text in i386.md becomes the CODE_FOR_divmoddi4 and the generator function that expand called.


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.