Linux Kernel Architecture

(Jacob Rumans) #1
Mauerer app03.tex V1 - 09/04/2008 6:11pm Page 1196

Appendix C: Notes on C


This code copies the value inatob— not a very demanding task. This could also have been formu-
lated asb=ato enable the compiler to generate equivalent or better code. The code makes use of an
input register, an output register, and a temporary register. While the input and output register are
selected by the compiler and are denoted as%1and%0in the assembler code (all the code does is to
define the conditions applied to the registers), the name of the temporary register must be specified
explicitly. This example useseax. Recall that two percent symbols must be entered in the source code
in order to produce one percent symbol in the compiler output, which is why the register is given
as%%eax.

The example generates the following assembler output in AT&T syntax (only the relevant part of the
output is shown here.)

movl -4(%ebp), %edx
#APP
movl %edx, %eax;
movl %eax, %edx;
#NO_APP
movl %edx, %eax
movl %eax, -8(%ebp)

The assembler code generated by theasmstatement is embedded between#APPand#NO_APPin the
compiler output.

The effect of the code is as anticipated. The compiler first copies the value of the local variablea
held at positionebp-4in the local activation record into a register (edx). The assembler code is
executed and copies the value (pointlessly) into registereax;itthencopiesthevalueofeaxinto output
registeredx. The subsequent code is again generated by the compiler — it copies the result value of
the assembler code (via registereax) into the local target variableblocated at positionebp - 8in the
activation record.

Neither the assembler code nor the output generated by the compiler is particularly intelligent in this
example. If the GCC is requested to produce optimized code, it generates the following assembler
output:

movl $5, %edx
#APP
movl %edx, %eax;
movl %eax, %ecx;
#NO_APP

The local variables are now no longer stored on thestack (they are not needed there) but are held in
registers.edxis used foraand is initialized directly with the constant 5.bis held in registerecx.Both
registers can be used in user-specified assembler code and this dispenses with the need for unwieldy
copy operations between registers and the stack.

GCC cannot check whether correct assembler instructions for the specific platform
are used in the code part ofasm, or whether the registers used are really suitable for
the particular application. This is the sole responsibility of the programmer.
Free download pdf