1 <!doctype linuxdoc system>
3 <!-- LinuxDoc file was created by LyX 1.0 (C) 1995-1999 by <sandeep> Thu Oct 14 02:37:55 1999
7 <title>SDCC Compiler User Guide
9 <author>Sandeep Dutta (sandeep.dutta@usa.net)
12 <p>SDCC is a Free ware , retargettable, optimizing ANSI-C compiler. The current
13 version targets Intel 8051 based MCUs, it can be retargetted for other 8 bit
14 MCUs or PICs. The entire source code for the compiler is distributed under
15 GPL. SDCC used ASXXXX & ASLINK a Free ware, retargettable assembler &
16 linker. SDCC has extensive MCU (8051) specific language extensions, which lets
17 it utilize the underlying hardware effectively. The front-end (parser) will
18 be enhanced to handle language extensions for other MCUs as and when they are
19 targetted. In addition to the MCU Specific optimizations SDCC also does a host
20 of standard optimizations like global sub expression elimination, loop optimizations
21 (loop invariant, strength reduction of induction variables and loop reversing),
22 constant folding & propagation, copy propagation, dead code elimination
23 and jumptables for 'switch' statements. For the back-end SDCC uses a global
24 register allocation scheme which should be well suited for other 8 bit MCUs
25 , the peep hole optimizer uses a rule based substitution mechanism which is
26 MCU independent. Supported data-types are short (8 bits, 1 byte), char (8 bits,
27 1 byte), int (16 bits, 2 bytes ), long (32 bit, 4 bytes) & float (4 byte
28 IEEE). The compiler also allows inline assembler code to be embedded anywhere
29 in a function. In addition routines developed in assembly can also be called.
30 SDCC also provides an option to report the relative complexity of a function,
31 these functions can then be further optimized , or hand coded in assembly if
32 need be. SDCC also comes with a companion source level debugger SDCDB, the
33 debugger currently uses S51 a freeware simulator for 8051, it can be easily
34 modified to use other simulators. The latest version can be downloaded from
35 <bf>http://www.geocities.com/ResearchTriangle/Forum/1353</bf>
37 <p>All packages used in this compiler system are opensource (freeware); source
38 code for all the sub-packages ( asxxxx assembler/linker , pre-processor and
39 gc a conservative garbage collector) are distributed with the package. Documentation
40 was created using a freeware word processor (LyX).
42 <p>This program is free software; you can redistribute it and/or modify it
43 under the terms of the GNU General Public License as published by the Free
44 Software Foundation; either version 2, or (at your option) any later version.
45 This program is distributed in the hope that it will be useful, but WITHOUT
46 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
47 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
48 You should have received a copy of the GNU General Public License along with
49 this program; if not, write to the Free Software Foundation, 59 Temple Place
50 - Suite 330, Boston, MA 02111-1307, USA. In other words, you are welcome to
51 use, share and improve this program. You are forbidden to forbid anyone else
52 to use, share and improve what you give them. Help stamp out software-hoarding!
55 <sect>Installation <label id="Installation" >
56 <p>What you need before you start installation of SDCC ? A C Compiler, not
57 just any C Compiler, gcc to be exact, you can get adventurous and try another
58 compiler , I HAVEN'T tried it. GCC is free , and is available for almost all
59 major platforms, if you are using linux you probably already have it, if you
60 are using Windows 95/NT go to www.cygnus.com and download CYGWIN32 you will
61 need the full development version of their tool (full.exe), follow their instructions
62 for installation (this is also free and is very easy to install), Windows 95/NT
63 users be aware that the compiler runs substantially slower on the Windows platform,
66 <p>After you have installed gcc you are ready to build the compiler (sorry
67 no binary distributions yet). SDCC is native to Linux but can be ported to
68 any platform on which GCC is available . Extract the source file package (.zip
69 or .tar.gz) into some directory , which we shall refer to as SDCCDIR from now
72 <sect1>Components of SDCC<label id="Components" >
73 <sect2>gc ( a conservative garbage collector)
74 <p>SDCC relies on this component to do all the memory management, this excellent
75 package is copyrighted by Jans J Boehm(boehm@sgi.com) and Alan J Demers but
76 can be used with minimum restrictions. The GC source will be extracted into
77 the directory SDCCDIR/gc.
79 <sect2>cpp ( C-Preprocessor)
80 <p>The preprocessor is extracted into the directory SDCCDIR/cpp, it is a modified
81 version of the GNU preprocessor.
83 <sect2>asxxxx & aslink ( The assembler and Linkage Editor)
84 <p>This is retargettable assembler & linkage editor, it was developed
85 by Alan Baldwin, John Hartman created the version for 8051, and I (Sandeep)
86 have some enhancements and bug fixes for it to work properly with the SDCC.
87 This component is extracted into the directory SDCCDIR/asxxxx.
89 <sect2>SDCC - The compiler.
90 <p>This is the actual compiler, it uses gc and invokes the assembler and linkage
91 editor. All files with the prefix SDCC are part of the compiler and is extracted
92 into the the directory SDCCDIR.
94 <sect2>S51 - Simulator
95 <p>Version 2.1.8 onwards contains s51 a freeware , opensource simulator developed
96 by Daniel Drotos <drdani@mazsola.iit.uni-miskolc.hu>. The executable
97 is built as part of build process, for more information visit Daniel's website
98 at <http://mazsola.iit.uni-miskolc.hu/˜drdani/embedded/s51/>.
100 <sect2>SDCDB - Source level Debugger.
101 <p>SDCDB is the companion source level debugger . The current version of the
102 debugger uses Daniel's Simulator S51, but can be easily changed to use other
105 <sect1>Installation for Version <= 2.1.7
106 <p>After the package is extracted (Windows 95/NT users start CYGWIN shell),
107 change to the directory where you extracted the package and give the command.
112 <p>This is a bash shell script, it will compile all the above mentioned components
113 and install the executables into the directory SDCCDIR/bin make sure you add
114 this directory to your PATH environment variable. This script will also compile
115 all the support routines ( library routines ) using SDCC. The support routines
116 are all developed in C and need to be compiled.
118 <sect1>Installation for Version >= 2.1.8a
119 <p>The distribution method from Version 2.1.8a has been changed to be conforment
120 with the "autoconf" utility. The source is now distributed as <bf>sdcc-<version
121 number>.tar.gz format</bf> , instead of the older .zip format. The steps for
122 installation are as follows.
124 <sect2>Unpack the sources.
125 <p>This is usually done by the following command "<bf>gunzip -c sdcc-<version
126 number>.tar.gz | tar -xv -</bf>"
128 <sect2>Change to the main source directory (usually sdcc or sdcc-<version number>)
129 <sect2>Issue command to configure your system
130 <p>The configure command has several options the most commonly used option
131 is --prefix=<directory name>, where <directory name> is the final
132 location for the sdcc executables and libraries, (default location is /usr/local).
133 The installation process will create the following directory structure under
134 the <directory name> specified.
137 <verb>bin/ - binary exectables (add to PATH environment variable)
140 - include header files
142 small/ - Object &
143 Library files for small model library
144 large/ - Object & library
145 files for large model library
149 <p><bf>'./configure --prefix=/usr/local" </bf>
151 <p>will create configure the compiler to be installed in directory /usr/local/bin.
154 <p>After configuration step issue the command
158 <p>This will compile the compiler
160 <sect2>"make install"
161 <p>Will install the compiler and libraries in the appropriate directories.
163 <sect2>Special Notes for Windows Users. Provided by Michael Jamet[ mjamet@computer.org]
167 <p> How to install SDCC from source on a Windows 95 or Windows NT 4 system
172 <p> This document describes how to install SDCC on a Win 95 or Win NT 4 system.
175 <p> These instructions probably work for Win 98 as well, but have not been
178 <p> tested on that platform.
182 <p> There are lots of little differences between UNIX and the Win32 Cygnus
185 <p> environment which make porting more difficult than it should be. If
188 <p> you want the details, please contact me. Otherwise just follow these
195 <p> 1. Install the Cygnus Software
197 <p> Go to http://sourceware.cygnus.com/cygwin. Cygnus provides a UNIX like
200 <p> environment for Win 32 systems. Download &dquot;full.exe&dquot; and
203 <p> MUST install it on your C drive. &dquot;full.exe&dquot; contains a shell
206 <p> common UNIX utilities.
210 <p> 2. Download and Extract the Latest SDCC
212 <p> The latest version can be found at
214 <p> www.geocities.com/ResearchTriange/Forum/1353.
216 <p> It can be uncompressed with winzip.
220 <p> 3. Start a Cygnus Shell
222 <p> There should be an entry in the Start Menu for Cygnus. Invoke the shell.
225 <p> This gives you a UNIX like environment. FROM THIS POINT ON, DIRECTORIES
228 <p> MUST BE SPECIFIED WITH FORWARD SLASHES (/) NOT THE DOS STYLE BACK
230 <p> SLASHES (\) BECAUSE THIS IS WHAT UNIX EXPECTS. -
232 <p> ex. &dquot;\winnt&dquot; would be &dquot;/winnt&dquot; under the
237 <p> 4. Change Directory to Where SDCC was extracted (referred to as INSTALLDIR)
242 <p> ex. cd /sdcc218Da. If you extracted to a drive OTHER THAN C, the drive
245 <p> must be specified as part of the path. For example, if you extracted
248 <p> your &dquot;g drive&dquot;, type the following: &dquot;cd //g/mydir&dquot;.
249 You must use &dquot;//&dquot;
251 <p> to specify the drive.
255 <p> 5. Make Dirs Which are Automatically Made During the UNIX Installation
258 <p> From the INSTALLDIR,
262 <p> mkdir -p bin (not a typo, just &dquot;bin&dquot;)
266 <p> mkdir -p /usr/local/bin
268 <p> mkdir -p /usr/local/share
270 <p> mkdir -p /usr/local/share/sdcc51lib
272 <p> mkdir -p /usr/local/share/sdcc51inc
278 <p> (When a path from the root directory is specified WITHOUT a drive, the
281 <p> drive defaults to c. For example /michael/newuser => c:\michael\newuser)
286 <p> 6. Add Programs to /bin Expected by the Installation Process
288 <p> - Look at your path: echo $PATH
290 <p> One of the fields is the diretory with the CYGNUS programs.
292 <p> ex. /CYGNUS/CYGWIN˜1/H-I586/BIN
296 <p> - cd to the directory found above. You may have to fiddle with the
299 <p> case (upper or lower) here because the PATH is SHOWN as all upper
302 <p> case, but is actually mixed. To help you along, you may type
304 <p> a letter or 2 followed by the escape key. The shell will fill
306 <p> out the remaining letters IF THEY describe a unique directory.
308 <p> If you have problems here, cd one directory and type &dquot;ls&dquot;.
311 <p> is the equivalent of &dquot;dir/w&dquot;.
315 <p> - Copy the following:
325 <p> 7. Go back to the INSTALLDIR
329 <p> ex. cd //d/sdcc218Da
333 <p> 8. Run the configure Program
337 <p> The &dquot;./&dquot; is important because your current directory is NOT
340 <p> Under DOS, your current directory was implicitly always the first entry
353 <p> This process takes quite some time under Win 32.
357 <p> 10. Install the Newly Built Software
363 <p> This will partially install the software into the /usr/local directories
366 <p> created in step 5. What it actually doing is copying the .c, .h and
369 <p> library files to directories under /usr/local/share.
373 <p> It will NOT be able to install the actual programs (binaries) because
376 <p> it does not know programs on Win32 systems have &dquot;.exe&dquot; extensions.
379 <p> For example, it tries to install sdcc instead of sdcc.exe.
383 <p> After the automated part is finished, you must manually copy the binaries:
386 <p> cd bin (This is the bin directory in your INSTALLDIR)
388 <p> cp * /usr/local/bin
392 <p> 11. Make sure /usr/local/bin is in Your PATH
394 <p> You may add c:\usr\local\bin to your path however your
395 Win32 system allows. For
397 <p> example you may add it to the PATH statement in autoexec.bat.
401 <p> Good luck. If you have any questions send them to me or post them
405 <sect>Compiling.<label id="Compiling" >
406 <sect1>Single Source file projects.<label id="One Source File" >
407 <p>For single source file projects the process is very simple. Compile your
408 programs with the following command
411 <verb>sdcc sourcefile.c
413 <p>The above command will compile ,assemble and link your source file. Output
414 files are as follows.
418 <item>sourcefile.asm - Assembler source file created by the compiler
419 <item>sourcefile.lst - Assembler listing file created by the Assembler
420 <item>sourcefile.rst - Assembler listing file updated with linkedit information
421 , created by linkage editor
422 <item>sourcefile.sym - symbol listing for the sourcefile, created by the assembler.
423 <item>sourcefile.rel - Object file created by the assembler, input to Linkage
425 <item>sourcefile.map - The memory map for the load module, created by the Linker.
426 <item>sourcefile.<ihx | s19> - The load module : ihx - Intel hex format
427 (default ), s19 - Motorola S19 format when compiler option --out-fmt-s19 is
430 <sect1>Projects with multiple source files.
431 <p>SDCC can compile only ONE file at a time. Let us for example assume that
432 you have a project containing the following files.
435 <verb>foo1.c ( contains some functions )foo2.c (contains some more functions)foomain.c (contains more functions and the function main)
437 <p>The first two files will need to be compiled separately with the commands
440 <verb>sdcc -c foo1.csdcc -c foo2.c
442 <p>Then compile the source file containing main and link the other files together
443 with the following command.
446 <verb>sdcc foomain.c foo1.rel foo2.rel
448 <p>Alternatively foomain.c can be separately compiled as well
451 <verb>sdcc -c foomain.c sdcc foomain.rel foo1.rel foo2.rel
453 <p>The file containing the main function MUST be the FIRST file specified
454 in the command line , since the linkage editor processes file in the order
455 they are presented to it.
457 <sect1>Projects with additional libraries.
458 <p>Some reusable routines may be compiled into a library, see the documentation
459 for the assembler and linkage editor in the directory SDCCDIR/asxxxx/asxhtm.htm
460 this describes how to create a .lib library file, the libraries created in
461 this manner may be included using the command line, make sure you include the
462 -L <library-path> option to tell the linker where to look for these files.
463 Here is an example, assuming you have the source file 'foomain.c' and a library
464 'foolib.lib' in the directory 'mylib'.
467 <verb>sdcc foomain.c foolib.lib -L mylib
469 <p>Note here that 'mylib' must be an absolute path name.
471 <p>The view of the way the linkage editor processes the library files, it
472 is recommended that you put each source routine in a separate file and combine
473 them using the .lib file. For an example see the standard library file 'libsdcc.lib'
474 in the directory SDCCDIR/sdcc51lib.
476 <sect>Command Line options<label id="Command Line Options" >
479 <item><bf>--model-large<label id="--model-large" ></bf> Generate code for Large model programs see section Memory
480 Models for more details. If this option is used all source files in the project
481 should be compiled with this option. In addition the standard library routines
482 are compiled with small model , they will need to be recompiled.
483 <item><bf>--model-small</bf> <label id="--model-small" >Generate code for Small Model programs see section Memory
484 Models for more details. This is the default model.
485 <item><bf>--stack-auto</bf> <label id="--stack-auto" >All functions in the source file will be compiled as reentrant,
486 i.e. the parameters and local variables will be allocated on the stack. see
487 section Parameters and Local Variables for more details. If this option is
488 used all source files in the project should be compiled with this option.
489 <item><bf>--xstack</bf><label id="--xstack" > Uses a pseudo stack in the first 256 bytes in the external ram
490 for allocating variables and passing parameters. See section on external stack
492 <item><bf>--nogcse</bf><label id="--nogcse" > Will not do global subexpression elimination, this option may
493 be used when the compiler creates undesirably large stack/data spaces to store
494 compiler temporaries. A warning message will be generated when this happens
495 and the compiler will indicate the number of extra bytes it allocated. It recommended
496 that this option NOT be used , #pragma NOGCSE can be used to turn off global
497 subexpression elimination for a given function only.
498 <item><bf>--noinvariant</bf><label id="--noinvariant" > Will not do loop invariant optimizations, this may be turned
499 off for reasons explained for the previous option . For more details of loop
500 optimizations performed see section Loop Invariants.It recommended that this
501 option NOT be used , #pragma NOINVARIANT can be used to turn off invariant
502 optimizations for a given function only.
503 <item><bf>--noinduction</bf><label id="--noinduction" > Will not do loop induction optimizations, see section Strength
504 reduction for more details.It recommended that this option NOT be used , #pragma
505 NOINDUCTION can be used to turn off induction optimizations for given function
507 <item><bf>--nojtbound </bf><label id="--nojtbound" > Will not generate boundary condition check when switch statements
508 are implemented using jump-tables. See section Switch Statements for more details.It
509 recommended that this option NOT be used , #pragma NOJTBOUND can be used
510 to turn off boundary checking for jump tables for a given function only.
511 <item><bf>--noloopreverse</bf> <label id="--noloopreverse" >Will not do loop reversal optimization
512 <item><bf>--noregparms</bf><label id="--noregparms" > By default the first parameter is passed using global registers
513 (DPL,DPH,B,ACC). This option will disable parameter passing using registers.
514 NOTE: if your program uses the 16/32 bit support routines (for multiplication/division)
515 these library routines will need to be recompiled with the --noregparms option
517 <item><bf>--callee-saves function1[,function2][,function3]....</bf>
518 <label id="--callee-saves" >The compiler by default uses a caller saves convention for register saving
519 across function calls, however this can cause unneccessary register pushing
520 & popping when calling small functions from larger functions. This option
521 can be used to switch the register saving convention for the function names
522 specified. The compiler will not save registers when calling these functions,
523 extra code will be generated at the entry & exit for these functions to
524 save & restore the registers used by these functions, this can SUBSTANTIALLY
525 reduce code & improve run time performance of the generated code. In future
526 the compiler (with interprocedural analysis) will be able to determine the
527 appropriate scheme to use for each function call. DO NOT use this option for
528 built-in functions such as _muluint..., if this option is used for a library
529 function the appropriate library function needs to be recompiled with the same
530 option. If the project consists of multiple source files then all the source
531 file should be compiled with the same --callee-saves option string. Also see
532 Pragma Directive<ref id="Pragmaa" name="" > CALLEE-SAVES.<ref id="pragma callee-saves" name="" > .
533 <item><bf>--debug </bf><label id="--debug" >When this option is used the compiler will generate debug information
534 , that can be used with the SDCDB. The debug information is collected in a
535 file with .cdb extension. For more information see documentation for SDCDB.
536 <item><bf>--regextend </bf><label id="--regextend" > This option will cause the compiler to define pseudo registers
537 , if this option is used, all source files in the project should be compiled
538 with this option. See section Register Extension for more details.
539 <item><bf>--compile-only</bf>(-c) <label id="--compile-only" > will compile and assemble the source only, will not
540 call the linkage editor.
541 <item><bf>--xram-loc </bf><label id="--xram-loc" ><Value> The start location of the external ram, default
542 value is 0. The value entered can be in Hexadecimal or Decimal format .eg.
543 --xram-loc 0x8000 or --xram-loc 32768.
544 <item><bf>--code-loc </bf><label id="--code-loc" ><Value> The start location of the code segment , default
545 value 0. Note when this option is used the interrupt vector table is also relocated
546 to the given address. The value entered can be in Hexadecimal or Decimal format
547 .eg. --code-loc 0x8000 or --code-loc 32768.
548 <item><bf>--stack-loc</bf><label id="--stack-loc" ><Value> The initial value of the stack pointer. The default
549 value of the stack pointer is 0x07 if only register bank 0 is used, if other
550 register banks are used then the stack pointer is initialized to the location
551 above the highest register bank used. eg. if register banks 1 & 2 are used
552 the stack pointer will default to location 0x18. The value entered can be in
553 Hexadecimal or Decimal format .eg. --stack-loc 0x20 or --stack-loc 32. If all
554 four register banks are used the stack will be placed after the data segment
555 (equivalent to --stack-after-data)
556 <item><bf>--stack-after-data</bf><label id="--stack-after-data" >This option will cause the stack to be located in the
557 internal ram after the data segment.
558 <item><bf>--data-loc</bf> <label id="--data-loc" ><Value> The start location of the internal ram data segment,
559 the default value is 0x30.The value entered can be in Hexadecimal or Decimal
560 format .eg. --data-loc 0x20 or --data-loc 32.
561 <item><bf>--idata-loc</bf><label id="--idata-loc" ><Value> The start location of the indirectly addressable
562 internal ram, default value is 0x80. The value entered can be in Hexadecimal
563 or Decimal format .eg. --idata-loc 0x88 or --idata-loc 136.
564 <item><bf>--peep-file<label id="--peep-file" > </bf><filename> This option can be used to use additional
565 rules to be used by the peep hole optimizer. See section Peep Hole optimizations
566 for details on how to write these rules.
567 <item><bf>--lib-path (-L) </bf><label id="--lib-path" ><absolute path to additional libraries> This option
568 is passed to the linkage editor, additional libraries search path. The path
569 name must be absolute. Additional library files may be specified in the command
570 line . See section Compiling programs for more details.
571 <item><bf>-I <path><label id="-I" ></bf> The additional location where the pre processor will look
572 for <..h> or "..h" files.
573 <item><bf>-D<macro[=value]></bf> <label id="-D" >Command line definition of macros. Passed
574 to the pre processor.
575 <item><bf>-E</bf><label id="-E" > Run only the C preprocessor. Preprocess all the C source files specified
576 and output the results to standard output.
577 <item><bf>-M<label id="-M" ></bf> Tell the preprocessor to output a rule suitable for make describing
578 the dependencies of each object file. For each source file, the preprocessor
579 outputs one make-rule whose target is the object file name for that source
580 file and whose dependencies are all the files `#include'd in it. This rule
581 may be a single line or may be continued with `\'-newline if it is long.
582 The list of rules is printed on standard output instead of the preprocessed
583 C program. `-M' implies `-E'.
584 <item><bf>-C</bf> <label id="-C" >Tell the preprocessor not to discard comments. Used with the `-E' option.
585 <item><bf>-MM </bf><label id="-MM" >Like `-M' but the output mentions only the user header files included
586 with `#include file&dquot;'. System header files included with `#include
587 <file>' are omitted.
588 <item><bf>-Aquestion(answer)</bf><label id="-Aquestion(answer)" > Assert the answer answer for question, in case it is
589 tested with a preprocessor conditional such as `#if #question(answer)'.
590 `-A-' disables the standard asser- tions that normally describe the target
592 <item><bf>-Aquestion</bf><label id="-Aquestion" > (answer) Assert the answer answer for question, in case it is
593 tested with a preprocessor conditional such as `#if #question(answer)'.
594 `-A-' disables the standard assertions that normally describe the target machine.
595 <item><bf>-Umacro</bf><label id="-Umacro" > Undefine macro macro. `-U' options are evaluated after all `-D'
596 options, but before any `-include' and `-imac- ros' options.
597 <item><bf>-dM</bf><label id="-dM" > Tell the preprocessor to output only a list of the mac- ro definitions
598 that are in effect at the end of prepro- cessing. Used with the `-E' option.
599 <item><bf>-dD</bf> <label id="-dD" >Tell the preprocessor to pass all macro definitions into the output,
600 in their proper sequence in the rest of the output.
601 <item><bf>-dN </bf><label id="-dN" >Like `-dD' except that the macro arguments and contents are omitted.
602 Only `#define name' is included in the output.
603 <item><bf>-S </bf><label id="-S" >Stop after the stage of compilation proper; do not as- semble. The output
604 is an assembler code file for the input file specified.
605 <item><bf>-Wa asmOption[,asmOption]</bf>... Pass the asmOption to the assembler
606 <item><bf>-Wl linkOption[,linkOption]</bf> .. Pass the linkOption to the linker.
607 <item><bf>--int-long-reent</bf> <label id="--int-long-rent" > Integer (16 bit) and long (32 bit) libraries have been
608 compiled as reentrant. Note by default these libraries are compiled as non-reentrant.
609 See section Installation for more details.
610 <item><bf>--cyclomatic </bf><label id="--cyclomatic" >This option will cause the compiler to generate an information
611 message for each function in the source file. The message contains some important
612 information about the function. The number of edges and nodes the compiler
613 detected in the control flow graph of the function, and most importantly the
614 cyclomatic complexity see section on Cyclomatic Complexity for more details.
615 <item><bf>--float-reent </bf><label id="--float-reent" > Floating point library is compiled as reentrant.See section
616 Installation for more details.
617 <item><bf>--out-fmt-ihx<label id="--out-fmt-ihx" > </bf>The linker output (final object code) is in Intel Hex format.
618 (This is the default option).
619 <item><bf>--out-fmt-s19 </bf><label id="--out-fmt-s19" >The linker output (final object code) is in Motorola S19
621 <item><bf>--nooverlay</bf> <label id="--nooverlay" > The compiler will not overlay parameters and local variables
622 of any function, see section Parameters and local variables for more details.
623 <item><bf>--main-return</bf><label id="--main-return" > This option can be used when the code generated is called
624 by a monitor program. The compiler will generate a 'ret' upon return from the
625 'main' function. The default option is to lock up i.e. generate a 'ljmp .'
627 <item><bf>--no-peep</bf> <label id="--no-peep" > Disable peep-hole optimization.
628 <item><bf>--peep-asm</bf> <label id="--peep-asm" > Pass the inline assembler code through the peep hole optimizer.
629 Can cause unexpected changes to inline assembler code , please go through the
630 peephole optimizer rules defnied in file 'SDCCpeeph.def' before using this
632 <item><bf>--iram-size</bf><label id="--iram-size" > <Value> Causes the linker to check if the interal ram
633 usage is within limits of the given value.
635 <p>The following options are provided for the purpose of retargetting and
636 debugging the compiler . These provided a means to dump the intermediate code
637 (iCode) generated by the compiler in human readable form at various stages
638 of the compilation process.
642 <item><bf>--dumpraw </bf><label id="--dumpraw" >. This option will cause the compiler to dump the intermediate
643 code into a file of named <source filename>.dumpraw just after the intermediate
644 code has been generated for a function , i.e. before any optimizations are
645 done. The basic blocks at this stage ordered in the depth first number, so
646 they may not be in sequence of execution.
647 <item><bf>--dumpgcse</bf>.<label id="--dumpgcse" > Will create a dump if iCode, after global subexpression elimination,
648 into a file named <source filename>.dumpgcse.
649 <item><bf>--dumpdeadcode </bf><label id="--dumpdeadcode" >.Will create a dump if iCode, after deadcode elimination,
650 into a file named <source filename>.dumpdeadcode.
651 <item><bf>--dumploop.</bf> <label id="--dumploop" >Will create a dump if iCode, after loop optimizations, into
652 a file named <source filename>.dumploop.
653 <item><bf>--dumprange.</bf> <label id="--dump-range" >Will create a dump if iCode, after live range analysis, into
654 a file named <source filename>.dumprange.
655 <item><bf>--dumpregassign. </bf><label id="--dumpregassign" >Will create a dump if iCode, after register assignment
656 , into a file named <source filename>.dumprassgn.
657 <item><bf>--dumpall. </bf><label id="--dumpall" >Will cause all the above mentioned dumps to be created.
659 <p>Note that the files created for the dump are appended to each time. So
660 the files should be deleted manually , before each dump is created.
662 <p>When reporting bugs, it will be very helpful if you could include these
663 dumps along with the portion of the code that is causing the problem.
665 <sect>Language Extensions<label id="Language Extension" >
666 <sect1>Storage Classes.<label id="Storage Classes" >
667 <p>In addition to the ANSI storage classes SDCC allows the following 8051
668 specific storage classes.
670 <sect2>xdata.<label id="xdata" >
671 <p>Variables declared with this storage class will be placed in the extern
672 RAM. This is the <bf>default</bf> storage class for Large Memory model .
674 <p>eg. xdata unsigned char xduc;
676 <sect2>data<label id="data" >
677 <p>This is the <bf>default</bf> storage class for Small Memory model. Variables declared
678 with this storage class will be allocated in the internal RAM.
680 <p>eg. data int iramdata;
682 <sect2>idata<label id="idata" >
683 <p>Variables declared with this storage class will be allocated into the indirectly
684 addressable portion of the internal ram of a 8051 .
688 <sect2>bit<label id="bit" >
689 <p>This is a data-type and a storage class specifier. When a variable is declared
690 as a bit , it is allocated into the bit addressable memory of 8051.
694 <sect2>sfr / sbit<label id="sfr / sbit" >
695 <p>Like the bit keyword, sfr / sbit signifies both a data-type and storage
696 class, they are used to describe the special function registers and special
697 bit variables of a 8051.
701 <p>sfr at 0x80 P0; /* special function register P0 at location 0x80 */
703 <p>sbit at 0xd7 CY; /* CY (Carry Flag) */
705 <sect>Optimizations<label id="Optimizations" >
706 <p>SDCC performs a a host of standard optimizations in addition to some MCU
707 specific optimizations.
709 <sect1>Sub-expression elimination<label id="Sub-expression Elimination" >
710 <p>The compiler does local and global common subexpression elimination.
718 <p>will be translated to
725 <p>Some subexpressions are not as obvious as the above example.
730 <verb>a->b[i].c = 10;
731 a->b[i].d = 11;
733 <p>In this case the address arithmetic a->b[i] will be computed
734 only once; the equivalent code in C would be.
737 <verb>iTemp = a->b[i];
741 <p>The compiler will try to keep these temporary variables in registers.
743 <sect1>Dead-Code elimination.<label id="Dead-code elimination" >
750 i = 1; /* dead store */
752 = 1; /* dead store */
755 global = 3; /* unreachable
759 <p>will be changed to
762 <verb>int global; void f ()
768 <sect1>Copy-Propagation:<label id="Copy-Propagation" >
779 <p>will be changed to
790 <p>Note: the dead stores created by this copy propagation will be eliminated
791 by dead-code elimination .
793 <sect1>Loop optimizations<label id="Loop Optimizations" >
794 <p>Two types of loop optimizations are done by SDCC loop invariant lifting
795 and strength reduction of loop induction variables.In addition to the strength
796 reduction the optimizer marks the induction variables and the register allocator
797 tries to keep the induction variables in registers for the duration of the
798 loop. Because of this preference of the register allocator , loop induction
799 optimization causes an increase in register pressure, which may cause unwanted
800 spilling of other temporary variables into the stack / data space . The compiler
801 will generate a warning message when it is forced to allocate extra space either
802 on the stack or data space. If this extra space allocation is undesirable then
803 induction optimization can be eliminated either for the entire source file
804 ( with --noinduction option) or for a given function only (#pragma NOINDUCTION).
806 <sect2>Loop Invariant:<label id="Loop Invariant" >
810 <verb>for (i = 0 ; i < 100 ; i ++)
817 for ( i = 0; i < 100; i++ ) f += itemp;
819 <p>As mentioned previously some loop invariants are not as apparent, all static
820 address computations are also moved out of the loop.
822 <sect2>Strength reduction :<label id="Strength Reduction" >
823 <p>This optimization substitutes an expression by a cheaper expression.
828 <verb>for (i=0;i < 100; i++) ar[i*5] = i*3;
835 for (i=0;i< 100;i++) {
842 <p>The more expensive multiplication is changed to a less expensive addition.
844 <sect2>Loop reversing:<label id="Loop reversing" >
845 <p>This optimization is done to reduce the overhead of checking loop boundaries
846 for every iteration. Some simple loops can be reversed and implemented using
847 a "decrement and jump if not zero" instruction. SDCC checks for the following
848 criterion to determine if a loop is reversible (note: more sophisticated compiers
849 use data-dependency analysis to make this determination, SDCC uses a more simple
854 <item>The 'for' loop is of the form
855 "for ( <symbol> = <expression>
856 ; <sym> [< | <=] <expression> ; [<sym>++
857 | <sym> += 1])
859 <item>The <for body> does not contain "continue" or 'break".
860 <item>All goto's are contained within the loop.
861 <item>No function calls within the loop.
862 <item>The loop control variable <sym> is not assigned any value within
864 <item>The loop control variable does NOT participate in any arithmetic operation
866 <item>There are NO switch statements in the loop.
868 <p>Note djnz instruction can be used for 8-bit values ONLY, therefore it is
869 advantageous to declare loop control symbols as either 'char' or 'short', ofcourse
870 this may not be possible on all situations.
872 <sect1>Algebraic simplifications:<label id="Algebraic Simplifications" >
873 <p>SDCC does numerous algebraic simplifications, the following is a small
874 sub-set of these optimizations.
878 i = j + 0 ; /* changed to */ i = j;
879 i /= 2; /* changed to */ i >>=
881 i = j - j ; /* changed to */ i = 0;
882 i = j / 1 ; /* changed to */ i = j;
884 <p>Note the subexpressions given above are generally introduced by macro expansions
885 or as a result of copy/constant propagation.
887 <sect1>'switch' statements.<label id="Switch Statement" >
888 <p>SDCC changes switch statements to jump tables when the following conditions
893 <item>The case labels are in numerical sequence , the labels need not be in order,
894 and the starting number need not be one or zero.
899 <verb>switch(i) { switch (i) {
904 case 3:... case 3: ...
909 <p>Both the above switch statements will be implemented using a jump-table.
913 <item>The number of case labels is at least three, since it takes two conditional
914 statements to handle the boundary conditions.
915 <item>The number of case labels is less than 84, since each label takes 3 bytes
916 and a jump-table can be utmost 256 bytes long.
918 <p>Switch statements which have gaps in the numeric sequence or those that
919 have more that 84 case labels can be split into more than one switch statement
920 for efficient code generation.
925 <verb>switch (i) {
937 <p>If the above switch statement is broken down into two switch statements
940 <verb>switch (i) {
945 }switch (i) {
953 <p>then both the switch statements will be implemented using jump-tables whereas
954 the unmodified switch statement will not be .
956 <sect1>bit-shifting operations.<label id="bit shifting" >
957 <p>Bit shifting is one of the most frequently used operation in embedded programming
958 . SDCC tries to implement bit-shift operations in the most efficient way possible.
963 <verb>unsigned short i;...
967 <p>generates the following code.
975 <p>In general SDCC will never setup a loop if the shift count is known. Another
979 <verb>unsigned int i;
988 mov (_i + 1),#0x00
993 <p>Note that SDCC stores numbers in little-endian format (i.e. lowest order
996 <sect2>Bit-rotation:<label id="bit rotation" >
997 <p>A special case of the bit-shift operation is bit rotation, SDCC recognizes
998 the following expression to be a left bit-rotation.
1001 <verb>unsigned char i;
1003 i = ( ( i << 1) | ( i >> 7));
1006 <p>will generate the following code.
1013 <p>SDCC uses pattern matching on the parse tree to determine this operation
1014 .Variations of this case will also be recognized as bit-rotation i.e i = ((i
1015 >> 7) | (i << 1)); /* left-bit rotation */
1017 <sect1>Highest Order Bit.<label id="Highest Order Bit" >
1018 <p>It is frequently required to obtain the highest order bit of an integral
1019 type (int,long,short or char types). SDCC recognizes the following expression
1020 to yield the highest order bit and generates optimized code for it.
1029 = (gint >> 15) & 1;
1033 <p>Will generate the following code.
1038 62 mov a,(_gint + 1)
1044 000F F5*02 66 mov _foo_hob_1_1,a
1046 <p>Variations of this case however will NOT be recognized . It is a standard
1047 C expression , so I heartily recommend this be the only way to get the highest
1048 order bit, (it is portable). Of course it will be recognized even if it is
1049 embedded in other expressions.
1052 <verb>eg.xyz = gint + ((gint >> 15) & 1);
1054 <p>will still be recognized.
1056 <sect1>Peep-hole optimizer.<label id="Peep-Hole" >
1057 <p>The compiler uses a rule based , pattern matching and re-writing mechanism
1058 for peep-hole optimization . It is inspired by 'copt' a peep-hole optimizer
1059 by Christopher W. Fraser (cwfraser@microsoft.com). A default set of rules are
1060 compiled into the compiler, additional rules may be added with the --peep-file
1061 <filename> option. The rule language is best illustrated with examples.
1064 <verb>replace {
1066 mov a,%1 } by { mov %1,a
1069 <p>The above rule will the following assembly sequence
1080 <p>Note: All occurrences of a '%n' ( pattern variable ) must denote
1081 the same string. With the above rule, the assembly sequence
1087 <p>will remain unmodified. Other special case optimizations may be added by
1088 the user (via --peep-file option), eg. some variants of the 8051 MCU allow
1089 only 'AJMP' and 'ACALL' , the following two rules will change all 'LJMP' &
1090 'LCALL' to 'AJMP' & 'ACALL'.
1093 <verb>replace { lcall %1 } by { acall %1 }
1095 replace { ljmp %1 } by { ajmp %1 }
1097 <p>The inline-assembler' code is also passed through the peep hole optimizer,
1098 thus the peephole optimizer can also be used as an assembly level macro expander.
1099 The rules themselves are MCU dependent whereas the rule language infra-structure
1100 is MCU independent. Peephole optimization rules for other MCU can be easily
1101 programmed using the rule language.
1103 <p>The syntax for a rule is as follows ,
1106 <verb>rule := replace [ restart ] '{' <assembly sequence>
1108 '}' by '{' '\n'
1110 <assembly sequence> '\n'
1112 '}' [if <functionName> ] '\n'
1114 sequence> := assembly instruction (each instruction including labels must
1115 be on a separate line).
1117 <p>The optimizer will apply to the rules one by one from the top in the sequence
1118 of their appearance, it will terminate when all rules are exhausted. If the
1119 'restart' option is specified, then the optimizer will start matching the rules
1120 again from the top, this option for a rule is expensive (performance), it is
1121 intended to be used in situations where a transformation will trigger the same
1122 rule again. A good example of this the following rule.
1125 <verb>replace restart {
1127 push %1 } by {
1132 <p>Note that the replace pattern cannot be a blank, but can be a comment line.
1133 Without the 'restart' option only the inner most 'pop' 'push' pair would be
1149 <p>with the 'restart' option the rule will be applied again to the resulting
1150 code and the all the 'pop' 'push' pairs will be eliminated to yield
1156 <p>A conditional function can be attached to a rule. Attaching rules are somewhat
1157 more involved, let me illustrate this with an example.
1160 <verb>replace {
1162 %2:} by {
1165 %2:} if labelInRange
1167 <p>The optimizer does a look-up of a function name table defined in function
1168 'callFuncByName' in the source file SDCCpeeph.c , with the name 'labelInRange',
1169 if it finds a corresponding entry the function is called. Note there can be
1170 no parameters specified for these functions, in this case the use of '%5'
1171 is crucial, since the function labelInRange expects to find the label in that
1172 particular variable (the hash table containing the variable bindings is passed
1173 as a parameter). If you want to code more such functions , take a close look
1174 at the function labelInRange and the calling mechanism in source file SDCCpeeph.c.
1175 I know this whole thing is a little kludgey , may be some day we will have
1176 some better means. If you are looking at this file, you will also see the default
1177 rules that are compiled into the compiler, you can your own rules in the default
1178 set there if you get tired of specifying the --peep-file option.
1180 <sect>Pointers<label id="Pointers" >
1181 <p>SDCC allows (via language extensions) pointers to explicitly point to any
1182 of the memory spaces of the 8051. In addition to the explicit pointers, the
1183 compiler also allows a _generic class of pointers which can be used to point
1184 to any of the memory spaces.
1186 <p>Pointer declaration examples.
1189 <verb>/* pointer physically in xternal ram pointing to object in internal ram
1191 data unsigned char * xdata p;
1192 /* pointer physically in code rom pointing to data in xdata space */
1194 unsigned char * code p;
1195 /* pointer physically in code space pointing to data in code space */
1197 unsigned char * code p;
1199 /* the folowing is a generic pointer physically located
1203 <p>Well you get the idea. For compatibility with the previous version of the
1204 compiler, the following syntax for pointer declaration is also supported. Note
1205 the above examples will be portable to other commercially available compilers.
1208 <verb>unsigned char _xdata *ucxdp; /* pointer to data in external ram */
1210 char _data *ucdp ; /* pointer to data in internal ram */
1212 *uccp ; /* pointer to data in R/O code space */
1213 unsigned char _idata *uccp;
1214 /* pointer to upper 128 bytes of ram */
1216 <p>All unqualified pointers are treated as 3 - byte '_generic' pointers. These
1217 type of pointers can also to be explicitly declared.
1220 <verb>unsigned char _generic *ucgp;
1222 <p>The highest order byte of the generic pointers contains the data space
1223 information. Assembler support routines are called whenever data is stored
1224 or retrieved using _generic pointers. These are useful for developing reusable
1225 library routines. Explicitly specifying the pointer type will generate the
1226 most efficient code. Pointers declared using a mixture of OLD/NEW style could
1227 have unpredictable results.
1229 <sect>Parameters & Local Variables<label id="Auto Variables" >
1230 <p>Automatic (local) variables and parameters to functions can either be placed
1231 on the stack or in data-space. The default action of the compiler is to place
1232 these variables in the internal RAM ( for small model) or external RAM (for
1233 Large model). They can be placed on the stack either by using the --stack-auto
1234 compiler option or by using the 'reentrant' keyword in the function declaration.
1239 <verb>unsigned short foo( short i) reentrant {
1243 <p>Note that when the parameters & local variables are declared in the
1244 internal/external ram the functions are non-reentrant. Since stack space on
1245 8051 is limited the 'reentrant' keyword or the --stack-auto option should be
1246 used sparingly. Note the reentrant keyword just means that the parameters &
1247 local variables will be allocated to the stack, it DOES NOT mean that the function
1248 is register bank independent.
1250 <p>When compiled with the default option (i.e. non-reentrant ), local variables
1251 can be assigned storage classes and absolute addresses.
1256 <verb>unsigned short foo() {
1257 xdata unsigned short i;
1260 data at 0x31 unsiged short j;
1264 <p>In the above example the variable i will be allocated in the external ram,
1265 bvar in bit addressable space and j in internal ram. When compiled with the
1266 --stack-auto or when a function is declared as 'reentrant' local variables
1267 cannot be assigned storage classes or absolute addresses.
1269 <p>Parameters however are not allowed any storage class, (storage classes
1270 for parameters will be ignored), their allocation is governed by the memory
1271 model in use , and the reentrancy options.
1273 <sect1>Overlaying<label id="Overlaying" >
1274 <p>For non-reentrant functions SDCC will try to reduce internal ram space
1275 usage by overlaying parameters and local variables of a function (if possible).
1276 Parameters and local variables of a function will be allocated to an overlayable
1277 segment if the function has no other function calls and the function is non-reentrant
1278 and the memory model is small. If an explicit storage class is specified for
1279 a local variable , it will NOT be overplayed.
1281 <p>Note that the compiler (not the linkage editor) makes the decision for
1282 overlaying the data items. Functions that are called from an interrupt service
1283 routine should be preceded by a #pragma NOOVERLAY if they are not reentrant
1284 Along the same lines the compiler does not do any processing with the inline
1285 assembler code so the compiler might incorrectly assign local variables and
1286 parameters of a function into the overlay segment if the only function call
1287 from a function is from inline assembler code, it is safe to use the #pragma
1288 NOOVERLAY for functions which call other functions using inline assembler code.
1290 <p>Parameters and Local variables of functions that contain 16 or 32 bit multiplication
1291 or division will NOT be overlayed since these are implemented using external
1297 <verb>#pragma SAVE
1298 #pragma NOOVERLAY
1299 void set_error( unsigned short
1306 () interrupt 2 using 1
1313 <p>In the above example the parameter errcd for the function set_error would
1314 be assigned to the overlayable segment (if the #pragma NOOVERLAY was not
1315 present) , this could cause unpredictable runtime behavior. The pragma NOOVERLAY
1316 ensures that the parameters and local variables for the function are NOT overlayed.
1318 <sect>critical Functions.<label id="Critical" >
1319 <p>A special keyword may be associated with a function declaring it as 'critical'.
1320 SDCC will generate code to disable all interrupts upon entry to a critical
1321 function and enable them back before returning . Note that nesting critical
1322 functions may cause unpredictable results.
1327 <verb>int foo () critical
1333 <p>The critical attribute maybe used with other attributes like reentrant.
1335 <sect>Absolute addressing.<label id="Absolute Addressing" >
1336 <p>Data items can be assigned an absolute address with the at <address>
1337 keyword, in addition to a storage class.
1340 <verb>eg. xdata at 0x8000 unsigned char PORTA_8255 ;
1342 <p>In the above example the PORTA_8255 will be allocated to the location 0x8000
1343 of the external ram.
1345 <p>Note that is this feature is provided to give the programmer access to
1346 memory mapped devices attached to the controller. The compiler does not actually
1347 reserve any space for variables declared in this way (they are implemented
1348 with an equate in the assembler), thus it is left to the programmer to make
1349 sure there are no overlaps with other variables that are declared without the
1350 absolute address, the assembler listing file (.lst) and the linker output files
1351 (<filename>.rst) and (<filename>.map) are a good places to look
1354 <p>Absolute address can be specified for variables in all storage classes.
1357 <verb>eg.bit at 0x02 bvar;
1359 <p>The above example will allocate the variable at offset 0x02 in the bit-addressable
1360 space. There is no real advantage to assigning absolute addresses to variables
1361 in this manner , unless you want strict control over all the variables allocated.
1363 <sect>Interrupt Service Routines<label id="Interrupt Service Rouines" >
1364 <p>SDCC allows interrupt service routines to be coded in C, with some extended
1368 <verb>void timer_isr (void) interrupt 2 using 1
1373 <p>The number following the 'interrupt' keyword is the interrupt number this
1374 routine will service. The compiler will insert a call to this routine in the
1375 interrupt vector table for the interrupt number specified. The 'using' keyword
1376 is used to tell the compiler to use the specified register bank (8051 specific)
1377 when generating code for this function. Note that when some function is called
1378 from an interrupt service routine it should be preceded by a #pragma NOOVERLAY
1379 (if it is not reentrant) . A special note here, int (16 bit) and long (32 bit)
1380 integer division, multiplication & modulus operations are implemented using
1381 external support routines developed in ANSI-C, if an interrupt service routine
1382 needs to do any of these operations then the support routines (as mentioned
1383 in a following section) will have to recompiled using the --stack-auto option
1384 and the source file will need to be compiled using the --int-long-rent compiler
1387 <p>If you have multiple source files in your project, interrupt service routines
1388 can be present in any of them, but a prototype of the isr MUST be present in
1389 the file that contains the function 'main'.
1391 <p>Interrupt Numbers and the corresponding address & descriptions for
1392 the Standard 8051 are listed below. SDCC will automatically adjust the interrupt
1393 vector table to the maximum interrupt number specified.
1396 <verb>Interrupt # Description Vector Address
1406 <p>If the interrupt service routine is defined without a register bank or
1407 with register bank 0 (using 0), the compiler will save the registers used by
1408 itself on the stack (upon entry and restore them at exit), however if such
1409 an interrupt service routine calls another function then the entire register
1410 bank will be saved on the stack. This scheme may be advantageous for small
1411 interrupt service routines which have low register usage.
1413 <p>If the interrupt service routine is defined to be using a specific register
1414 bank then only "a","b" & "dptr" are save and restored, if such an interrupt service
1415 routine calls another function (using another register bank) then the entire
1416 register bank of the called function will be saved on the stack. This scheme
1417 is recommended for larger interrupt service routines.
1419 <p>Calling other functions from an interrupt service routine is not recommended
1420 avoid it if possible.
1422 <sect>Startup Code<label id="Startup" >
1423 <p>The compiler inserts a jump to the C routine <bf>_sdcc__external__startup()
1424 </bf>at the start of the CODE area. This routine can be found in the file <bf>SDCCDIR/sdcc51lib/_startup.c</bf>
1425 , by default this routine returns 0, if this routine returns a non-zero value
1426 , the static & global variable initialization will be skipped and the function
1427 main will be invoked, other wise static & global variables will be initialized
1428 before the function main is invoked.
1430 <sect>Inline assembler code.<label id="Inline" >
1431 <p>SDCC allows the use of in-line assembler with a few restriction as regards
1432 labels. All labels defined within inline assembler code HAS TO BE of the form
1433 nnnnn$ where nnnn is a number less than 100 (which implies a limit of
1434 utmost 100 inline assembler labels per function). It is strongly recommended
1435 that each assembly instruction (including labels) be placed in a separate line
1436 ( as the example shows). When the <bf>--peep-asm</bf> command line option is used, the
1437 inline assembler code will be passed through the peephole optimizer, this might
1438 cause some unexpected changes in the inline assembler code, please go throught
1439 the peephole optimizer rules defined in file 'SDCCpeeph.def' carefully before
1446 djnz b,00001$
1450 <p>The inline assembler code can contain any valid code understood by the
1451 assembler (this includes any assembler directives and comment lines ) . The
1452 compiler does not do any validation of the code within the _asm ... _endasm;
1455 <p>Inline assembler code cannot reference any C-Labels however it can reference
1456 labels defined by the inline assembler.
1459 <verb>egfoo() {
1460 ... /* some c code */
1462 ; some assembler code
1466 ... /* some more c code */
1468 assembler cannot reference this label */
1470 $0003: ;label (can
1471 be reference by inline assembler only)
1476 <p>In other words inline assembly code can access labels defined in inline
1477 assembly. The same goes the other way, ie. labels defines in inline assembly
1478 CANNOT be accessed by C statements.
1480 <sect>int (16 bit) and long (32 bit ) support.<label id="int and long" >
1481 <p>For signed & unsigned int (16 bit) and long (32 bit) variables, division,
1482 multiplication and modulus operations are implemented by support routines.
1483 These support routines are all developed in ANSI-C to facilitate porting to
1484 other MCUs. The following files contain the described routine, all of them
1485 can be found in the directory SDCCDIR/sdcc51lib
1489 <item>_mulsint.c - signed 16 bit multiplication (calls _muluint)
1490 <item>_muluint.c - unsigned 16 bit multiplication
1491 <item>_divsint.c - signed 16 bit division (calls _divuint)
1492 <item>_divuint.c - unsigned 16 bit division.
1493 <item>_modsint.c - signed 16 bit modulus (call _moduint)
1494 <item>_moduint.c - unsigned 16 bit modulus.
1495 <item>_mulslong.c - signed 32 bit multiplication (calls _mululong)
1496 <item>_mululong.c - unsigned32 bit multiplication.
1497 <item>_divslong.c - signed 32 division (calls _divulong)
1498 <item>_divulong.c - unsigned 32 division.
1499 <item>_modslong.c - signed 32 bit modulus (calls _modulong).
1500 <item>_modulong.c - unsigned 32 bit modulus.
1502 <p>All these routines are compiled as non-reentrant and small model. Since
1503 they are compiled as non-reentrant, interrupt service routines should not do
1504 any of the above operations, if this unavoidable then the above routines will
1505 need to ne compiled with the --stack-auto option, after which the source program
1506 will have to be compiled with --int-long-rent option.
1508 <sect>Floating point support<label id="Float" >
1509 <p>SDCC supports IEEE (single precision 4bytes) floating point numbers.The
1510 floating point support routines are derived from gcc's floatlib.c and consists
1511 of the following routines.
1515 <item>_fsadd.c - add floating point numbers.
1516 <item>_fssub.c - subtract floating point numbers
1517 <item>_fsdiv.c - divide floating point numbers
1518 <item>_fsmul.c - multiply floating point numbers
1519 <item>_fs2uchar.c - convert floating point to unsigned char
1520 <item>_fs2char.c - convert floating point to signed char.
1521 <item>_fs2uint.c - convert floating point to unsigned int.
1522 <item>_fs2int.c - convert floating point to signed int.
1523 <item>_fs2ulong.c - convert floating point to unsigned long.
1524 <item>_fs2long.c - convert floating point to signed long.
1525 <item>_uchar2fs.c - convert unsigned char to floating point
1526 <item>_char2fs.c - convert char to floating point number
1527 <item>_uint2fs.c - convert unsigned int to floating point
1528 <item>_int2fs.c - convert int to floating point numbers
1529 <item>_ulong2fs.c - convert unsigned long to floating point number
1530 <item>_long2fs.c - convert long to floating point number.
1532 <p>Note if all these routines are used simultaneously the data space might
1533 overflow. For serious floating point usage it is strongly recommended that
1534 the Large model be used (in which case the floating point routines mentioned
1535 above will need to recompiled with the --model-Large option).
1537 <sect>Memory Models<label id="Memory Models" >
1538 <p>SDCC allows two memory models, modules compiled with different memory models
1539 should be combined together, the results would be unpredictable. The support
1540 routines supplied with the compiler are compiled in small-model by default,
1541 and will need to be recompiled using the large model if the large model is
1542 used. In general the use of the large model is discouraged.
1544 <p>When the large model is used all variables declared without a storage class
1545 will be allocated into the external ram, this includes all parameters and local
1546 variables (for non-reentrant functions). When the small model is used variables
1547 without storage class are allocated in the internal ram.
1549 <p>Judicious usage of the processor specific storage classes and the 'reentrant'
1550 function type will yield much more efficient code, than using the large-model.
1551 Several optimizations are disabled when the program is compiled using the large
1552 model, it is therefore strongly recommdended that the small model be used unless
1553 absolutely required.
1555 <sect>Defines created by the compiler.<label id="Defines." >
1556 <p>The compiler creates the following #defines .
1560 <item>SDCC - this Symbol is always defined.
1561 <item>SDCC_STACK_AUTO - this symbol is defined when --stack-auto option is used.
1562 <item>SDCC_MODEL_SMALL - when small model is used.
1563 <item>SDCC_MODEL_LARGE - when --model-large is used.
1564 <item>SDCC_USE_XSTACK - when --xstack option is used.
1566 <sect>Pragmas<label id="Pragmaa" >
1567 <p>SDCC supports the following #pragma directives. This directives are
1568 applicable only at a function level.
1572 <item><bf>SAVE</bf><label id="pragma save" > - this will save all the current options .
1573 <item><bf>RESTORE </bf><label id="pragma restore" >- will restore the saved options from the last save. Note that
1574 SAVES & RESTOREs cannot be nested. SDCC uses the same buffer to save the
1575 options each time a SAVE is called.
1576 <item><bf>NOGCSE</bf><label id="pragma nogcse" > - will stop global subexpression elimination.
1577 <item><bf>NOINDUCTION</bf> <label id="pragma noinduction" >- will stop loop induction optimizations .
1578 <item><bf>NOJTBOUND</bf> <label id="pragma nojtbound" >- will not generate code for boundary value checking , when switch
1579 statements are turned into jump-tables.
1580 <item><bf>NOOVERLAY </bf><label id="pragma nooverlay" >- the compiler will not overlay the parameters and local variables
1582 <item><bf>NOLOOPREVERSE</bf> <label id="pragma noloopreverse" >- Will not do loop reversal optimization
1583 <item><bf>EXCLUDE NONE | {acc[,b[,dpl[,dph]]]</bf><label id="pragma exclude" >
1584 - The exclude pragma disables generation of pair of push/pop instruction in
1585 ISR function (using interrupt keyword). The directive should be placed immediately
1586 before the ISR function definition and it affects ALL ISR functions following
1587 it. To enable the normal register saving for ISR functions use "#pragma
1589 <item><bf>CALLEE-SAVES function1[,function2[,function3...]]</bf><label id="pragma callee-saves" > -
1590 The compiler by default uses a caller saves convention for register saving
1591 across function calls, however this can cause unneccessary register pushing
1592 & popping when calling small functions from larger functions. This option
1593 can be used to switch the register saving convention for the function names
1594 specified. The compiler will not save registers when calling these functions,
1595 extra code will be generated at the entry & exit for these functions to
1596 save & restore the registers used by these functions, this can SUBSTANTIALLY
1597 reduce code & improve run time performance of the generated code. In future
1598 the compiler (with interprocedural analysis) will be able to determine the
1599 appropriate scheme to use for each function call. If --callee-saves<ref id="--callee-saves" name="" > command
1600 line option is used, the function names specified in #pragma CALLEE-SAVES
1601 is appended to the list of functions specified inthe command line.
1603 <p>The pragma's are intended to be used to turn-off certain optimizations
1604 which might cause the compiler to generate extra stack / data space to store
1605 compiler generated temporary variables. This usually happens in large functions.
1606 Pragma directives should be used as shown in the following example, they are
1607 used to control options & optimizations for a given function; pragmas should
1608 be placed before and/or after a function, placing pragma's inside a function
1609 body could have unpredictable results.
1612 <verb>eg#pragma SAVE /* save the current settings */
1614 /* turnoff global subexpression elimination */
1615 #pragma NOINDUCTION /*
1616 turn off induction optimizations */
1624 #pragma RESTORE /* turn the optimizations back
1627 <p>The compiler will generate a warning message when extra space is allocated.
1628 It is strongly recommended that the SAVE and RESTORE pragma's be used when
1629 changing options for a function.
1631 <sect>Library routines.<label id="Library" >
1632 <p>The following library routines are provided for your convenience.
1634 <p><bf>stdio.h </bf>- Contains the following functions printf & sprintf these routines
1635 are developed by Martijn van Balen <balen@natlab.research.philips.com>.
1639 <verb>%[flags][width][b|B|l|L]type flags: - left justify output in specified field width
1641 + prefix output with +/- sign if output is signed
1643 space prefix output with a blank if it's a signed
1645 width: specifies minimum number of characters
1646 outputted for numbers
1649 - For numbers, spaces are added on the left when needed.
1651 If width starts with a zero character, zeroes and used
1654 - For strings, spaces are are
1655 added on the left or right (when
1660 (used by d, u, o, x, X)
1661 l/L: long argument (used by d,
1663 type: d decimal number
1665 unsigned decimal number
1666 o unsigned octal number
1668 x unsigned hexadecimal number (0-9, a-f)
1670 unsigned hexadecimal number (0-9, A-F)
1673 s string (generic pointer)
1675 generic pointer (I:data/idata, C:code, X:xdata, P:paged)
1677 f float (still to be implemented)
1679 <p>Also contains a very simple version of printf (<bf>printf_small</bf>). This simplified
1680 version of printf supports only the following formats.
1683 <verb>format output type argument-type <bf>
1684 </bf>%d decimal
1686 %ld decimal long
1687 %hd decimal short/char
1689 %x hexadecimal int
1690 %lx hexadecimal long
1692 %hx hexadecimal short/char
1695 %lo octal long
1696 %ho octal short/char
1698 %c character char/short
1699 %s character _generic
1701 <p><tt>The routine is </tt><tt><bf>very stack intesive </bf>, --stack-after-data parameter should
1702 be used when using this routine, the routine also takes about 1K of code space
1703 .It also expects an external function named putchar(char ) to be present (this
1704 can be changed). When using the %s format the string / pointer should
1705 be cast to a generic pointer. eg.</tt>
1707 <verb>printf_small("my str %s, my int %d\n",(char _generic *)mystr,myint);
1712 <item><bf>stdarg.h </bf>- contains definition for the following macros to be used for
1713 variable parameter list, note that a function can have a variable parameter
1714 list if and only if it is 'reentrant'
1715 <p>va_list, va_start, va_arg, va_end.
1717 <item><bf>setjmp.h </bf>- contains defintion for ANSI<bf> setjmp </bf>& <bf>longjmp</bf> routines. Note
1718 in this case setjmp & longjmp can be used between functions executing within
1719 the same register bank, if long jmp is executed from a function that is using
1720 a different register bank from the function issuing the setjmp function, the
1721 results may be unpredictable. The jump buffer requires 3 bytes of data (the
1722 stack pointer & a 16 byte return address), and can be placed in any address
1724 <item><bf>stdlib.h</bf> - contains the following functions.
1727 <item><bf>string.h </bf>- contains the following functions.
1728 <p>strcpy, strncpy, strcat, strncat, strcmp, strncmp, strchr, strrchr, strspn,
1729 strcspn, strpbrk, strstr, strlen, strtok, memcpy, memcmp, memset.
1731 <item><bf>ctype.h</bf> - contains the following routines.
1732 <p>iscntrl, isdigit, isgraph, islower, isupper, isprint, ispunct, isspace,
1733 isxdigit, isalnum, isalpha.
1735 <item><bf>malloc.h</bf> - The malloc routines are developed by Dmitry S. Obukhov (dso@usa.net).
1736 These routines will allocate memory from the external ram. Here is a description
1737 on how to use them (as described by the author).
1739 // #define DYNAMIC_MEMORY_SIZE 0x2000
1742 // unsigned char xdata dynamic_memory_pool[DYNAMIC_MEMORY_SIZE];
1744 // unsigned char xdata * current_buffer;
1751 init_dynamic_memory(dynamic_memory_pool,DYNAMIC_MEMORY_SIZE);
1753 //Now it's possible to use malloc.
1759 <item><bf>serial.h</bf> - Serial IO routines are also developed by Dmitry S. Obukhov (dso@usa.net).
1760 These routines are interrupt driven with a 256 byte circular buffer, they also
1761 expect external ram to be present. Please see documentation in file SDCCDIR/sdcc51lib/serial.c
1762 . Note the header file "serial.h" MUST be included in the file containing the
1764 <item><bf>ser.h </bf>- Alternate serial routine provided by Wolfgang Esslinger <wolfgang@WiredMinds.com>
1765 these routines are more compact and faster. Please see documentation in file
1766 SDCCDIR/sdcc51lib/ser.c
1767 <item><bf>ser_ir.h </bf>- Another alternate set of serial routines provided by Josef Wolf
1768 <jw@raven.inka.de> , these routines do not use the external ram.
1769 <item><bf>reg51.h</bf> - contains register definitions for a standard 8051
1770 <item><bf>reg552.h </bf>- contains register definitions for 80C552.
1771 <item><bf>float.h</bf> - contains min, max and other floating point related stuff.
1773 <p>All library routines are compiled as --model-small , they are all non-reentrant,
1774 if you plan to use the large model or want to make these routines reentrant,
1775 then they will have to be recompiled with the appropriate compiler option.
1777 <p>Have not had time to do the more involved routines like printf, will get
1780 <sect>Interfacing with assembly routines.<label id="Interface_asm" >
1781 <sect1>Global registers used for parameter passing.
1782 <p>By default the compiler uses the global registers "DPL,DPH,B,ACC" to pass
1783 the first parameter to a routine, the second parameter onwards is either allocated
1784 on the stack (for reentrant routines or --stack-auto is used) or in the internal
1785 / external ram (depending on the memory model).
1787 <sect2>Assembler routine non-reentrant
1788 <p>In the following example the function<bf> cfunc</bf> calls an assembler routine
1789 <bf>asm_func</bf>, which takes two parameters.
1791 <p>extern int asm_func( unsigned short, unsigned short);
1795 int c_func (unsigned short i, unsigned short j)
1802 return c_func(10,9);
1805 <p>The corresponding assembler function is:-
1808 <verb> .globl _asm_func_PARM_2
1812 _asm_func_PARM_2: .ds 1
1817 add a,_asm_func_PARM_2
1823 <p>Note here that the return values are placed in 'dpl' - One byte return
1824 value, 'dpl' LSB & 'dph' MSB for two byte values. 'dpl', 'dph' and 'b'
1825 for three byte values (generic pointers) and 'dpl','dph','b' & 'acc' for
1828 <p>The parameter naming convention is <bf>_<function_name>_PARM_<n>,</bf>
1829 where n is the parameter number starting from 1, and counting from the left.
1830 The first parameter is passed in "dpl" for One bye parameter, "dptr" if two bytes,
1831 "b,dptr" for three bytes and "acc,b,dptr" for four bytes, the <tt></tt><tt><bf>varaible name for
1832 the second parameter will be _<function_name>_PARM_2.</bf></tt>
1834 <p>Assemble the assembler routine with the following command.
1837 <verb>asx8051 -losg asmfunc.asm
1839 <p>Then compile and link the assembler routine to the C source file with the
1843 <verb>sdcc cfunc.c asmfunc.rel
1845 <sect2>Assembler routine is reentrant
1846 <p>In this case the second parameter onwards will be passed on the stack ,
1847 the parameters are pushed from right to left i.e. after the call the left most
1848 parameter will be on the top of the stack. Here is an example.
1850 <p>extern int asm_func( unsigned short, unsigned short);
1853 <verb> int c_func (unsigned short i, unsigned short j) reentrant
1856 return asm_func(i,j);
1860 return c_func(10,9);
1864 <p>The corresponding assembler routine is.
1867 <verb> .globl _asm_func
1890 <p>The compiling and linking procedure remains the same, however note the
1891 extra entry & exit linkage required for the assembler code, _bp is the
1892 stack frame pointer and is used to compute the offset into the stack for parameters
1893 and local variables.
1895 <sect1>With --noregparms option.
1896 <p>When the source is compiled with --noregparms option , space is allocated
1897 for each of the parameters passed to a routine.
1899 <sect2>Assembler routine non-reentrant.
1900 <p>In the following example the function<bf> cfunc</bf> calls an assembler routine
1901 <bf>asm_func</bf>, which takes two parameters.
1904 <verb>extern int asm_func( unsigned short, unsigned short);
1905 int c_func (unsigned short i, unsigned short j)
1912 return c_func(10,9);
1915 <p>The corresponding assembler function is:-
1918 <verb> .globl _asm_func_PARM_1
1919 .globl _asm_func_PARM_2
1923 _asm_func_PARM_1: .ds 1
1928 mov a,_asm_func_PARM_1
1930 add a,_asm_func_PARM_2
1936 <p>Note here that the return values are placed in 'dpl' - One byte return
1937 value, 'dpl' LSB & 'dph' MSB for two byte values. 'dpl', 'dph' and 'b'
1938 for three byte values (generic pointers) and 'dpl','dph','b' & 'acc' for
1941 <p>The parameter naming convention is <bf>_<function_name>_PARM_<n>,</bf>
1942 where n is the parameter number starting from 1, and counting from the left.
1943 i.e. the <tt></tt><tt><bf>left-most parameter name will be _<function_name>_PARM_1.
1946 <p>Assemble the assembler routine with the following command.
1949 <verb>asx8051 -losg asmfunc.asm
1951 <p>Then compile and link the assembler routine to the C source file with the
1955 <verb>sdcc cfunc.c asmfunc.rel
1957 <sect2>Assembler routine is reentrant.
1958 <p>In this case the parameters will be passed on the stack , the parameters
1959 are pushed from right to left i.e. after the call the left most parameter will
1960 be on the top of the stack. Here is an example.
1962 <p>extern int asm_func( unsigned short, unsigned short);
1965 <verb> int c_func (unsigned short i, unsigned short j) reentrant
1968 return asm_func(i,j);
1972 return c_func(10,9);
1976 <p>The corresponding assembler routine is.
1979 <verb> .globl _asm_func
2003 <p>The compiling and linking procedure remains the same, however note the
2004 extra entry & exit linkage required for the assembler code, _bp is the
2005 stack frame pointer and is used to compute the offset into the stack for parameters
2006 and local variables.
2008 <sect>External Stack.<label id="xstack" >
2009 <p>The external stack is located at the start of the external ram segment
2010 , and is 256 bytes in size. When --xstack option is used to compile the program
2011 , the parameters and local variables of all reentrant functions are allocated
2012 in this area. This option is provided for programs with large stack space requirements.
2013 When used with the --stack-auto option, all parameters and local variables
2014 are allocated on the external stack (note support libraries will need to be
2015 recompiled with the same options).
2017 <p>The compiler outputs the higher order address byte of the external ram
2018 segment into PORT P2, therefore when using the External Stack option, this
2019 port MAY NOT be used by the application program.
2021 <sect>ANSI-Compliance.<label id="ANSI_Compliance" >
2022 <p>Deviations from the compliancy.
2026 <item>functions are not always reentrant.
2027 <item>structures cannot be assigned values directly, cannot be passed as function
2028 parameters or assigned to each other and cannot be a return value from a function.
2033 <verb>struct s { ... };
2039 s2 ; /* is invalid in SDCC although allowed in ANSI */
2041 }struct s foo1 (struct s parms) /* is invalid in SDCC although allowed in
2046 return rets;/* is invalid in SDCC although
2052 <item>'long long' (64 bit integers) not supported.
2053 <item>'double' precision floating point not supported.
2054 <item>integral promotions are suppressed. What does this mean ? The compiler
2055 will not implicitly promote an integer expression to a higher order integer,
2056 exception is an assignment or parameter passing.
2057 <item>No support for setjmp and longjmp (for now).
2058 <item>Old K&R style function declarations are NOT allowed.
2061 <verb>foo( i,j) /* this old style of function declarations */
2063 valid in ANSI .. not valid in SDCC */
2070 <item>functions declared as pointers must be dereferenced during the call.
2076 /* has to be called like this */
2077 (*foo)();/* ansi standard
2078 allows calls to be made like 'foo()' */
2080 <sect>Cyclomatic Complexity<label id="Cyclomatic" >
2081 <p>Cyclomatic complexity of a function is defined as the number of independent
2082 paths the program can take during execution of the function. This is an important
2083 number since it defines the number test cases you have to generate to validate
2084 the function . The accepted industry standard for complexity number is 10,
2085 if the cyclomatic complexity reported by SDCC exceeds 10 you should think about
2086 simplification of the function logic.
2088 <p>Note that the complexity level is not related to the number of lines of
2089 code in a function. Large functions can have low complexity, and small functions
2090 can have large complexity levels. SDCC uses the following formula to compute
2094 <verb>complexity = (number of edges in control flow graph) -
2096 of nodes in control flow graph) + 2;
2098 <p>Having said that the industry standard is 10, you should be aware that
2099 in some cases it may unavoidable to have a complexity level of less than 10.
2100 For example if you have switch statement with more than 10 case labels, each
2101 case label adds one to the complexity level. The complexity level is by no
2102 means an absolute measure of the algorithmic complexity of the function, it
2103 does however provide a good starting point for which functions you might look
2104 at for further optimization.
2106 <sect>TIPS<label id="Tips" >
2107 <p>Here are a few guide-lines that will help the compiler generate more efficient
2108 code, some of the tips are specific to this compiler others are generally good
2109 programming practice.
2113 <item>Use the smallest data type to represent your data-value. If it is known
2114 in advance that the value is going to be less than 256 then use a 'short' or
2115 'char' instead of an 'int'.
2116 <item>Use unsigned when it is known in advance that the value is not going to
2117 be negative. This helps especially if you are doing division or multiplication.
2118 <item>NEVER jump into a LOOP.
2119 <item>Declare the variables to be local whenever possible, especially loop control
2120 variables (induction).
2121 <item>Since the compiler does not do implicit integral promotion, the programmer
2122 should do an explicit cast when integral promotion is required.
2123 <item>Reducing the size of division , multiplication & modulus operations
2124 can reduce code size substantially. Take the following code for example.
2125 <verb>foobar( unsigned int p1, unsigned char ch)
2132 <p>For the modulus operation the variable ch will be promoted to unsigned
2133 int first then the modulus operation will be performed (this will lead to a
2134 call to a support routine). If the code is changed to
2136 <verb>foobar( unsigned int p1, unsigned char ch)
2139 = (unsigned char)p1 % ch ;
2143 <p>It would substantially reduce the code generated (future versions of the
2144 compiler will be smart enough to detect such optimization oppurtunities).
2147 <p><bf>Notes from an USER ( Trefor@magera.freeserve.co.uk )</bf>
2149 <p>The 8051 family of micro controller have a minimum of 128 bytes of internal
2150 memory which is structured as follows
2152 <p>- Bytes 00-1F - 32 bytes to hold up to 4 banks of the registers R7 to R7
2155 <p>- Bytes 20-2F - 16 bytes to hold 128 bit variables and
2157 <p>- Bytes 30-7F - 60 bytes for general purpose use.
2159 <p>Normally the SDCC compiler will only utilise the first bank of registers,
2160 but it is possible to specify that other banks of registers should be used
2161 in interrupt routines. By default, the compiler will place the stack after
2162 the last bank of used registers, i.e. if the first 2 banks of registers are
2163 used, it will position the base of the internal stack at address 16 (0X10).
2164 This implies that as the stack grows, it will use up the remaining register
2165 banks, and the 16 bytes used by the 128 bit variables, and 60 bytes for general
2168 <p>By default, the compiler uses the 60 general purpose bytes to hold &dquot;near
2169 data&dquot;. The compiler/optimiser may also declare some Local Variables in
2170 this area to hold local data.
2172 <p>If any of the 128 bit variables are used, or near data is being used then
2173 care needs to be taken to ensure that the stack does not grow so much that
2174 it starts to over write either your bit variables or &dquot;near data&dquot;.
2175 There is no runtime checking to prevent this from happening.
2177 <p>The amount of stack being used is affected by the use of the &dquot;internal
2178 stack&dquot; to save registers before a subroutine call is made, - --stack-auto
2179 will declare parameters and local variables on the stack - the number of nested
2182 <p>If you detect that the stack is over writing you data, then the following
2183 can be done. --xstack will cause an external stack to be used for saving registers
2184 and (if --stack-auto is being used) storing parameters and local variables.
2185 However this will produce more and code which will be slower to execute.
2187 <p>--stack-loc will allow you specify the start of the stack, i.e. you could
2188 start it after any data in the general purpose area. However this may waste
2189 the memory not used by the register banks and if the size of the &dquot;near
2190 data&dquot; increases, it may creep into the bottom of the stack.
2192 <p>--stack-after-data, similar to the --stack-loc, but it automatically places
2193 the stack after the end of the &dquot;near data&dquot;. Again this could waste
2194 any spare register space.
2196 <p>--data-loc allows you to specify the start address of the near data. This
2197 could be used to move the &dquot;near data&dquot; further away from the stack
2198 giving it more room to grow. This will only work if no bit variables are being
2199 used and the stack can grow to use the bit variable space.
2203 <p>If you find that the stack is over writing your bit variables or &dquot;near
2204 data&dquot; then the approach which best utilised the internal memory is to
2205 position the &dquot;near data&dquot; after the last bank of used registers
2206 or, if you use bit variables, after the last bit variable by using the --data-loc,
2207 e.g. if two register banks are being used and no data variables, --data-loc
2208 16, and - use the --stack-after-data option.
2210 <p>If bit variables are being used, another method would be to try and squeeze
2211 the data area in the unused register banks if it will fit, and start the stack
2212 after the last bit variable.
2214 <sect>Retargetting for other MCUs.<label id="Retargetting" >
2215 <p>The issues for retargetting the compiler are far too numerous to be covered
2216 by this document. What follows is a brief description of each of the seven
2217 phases of the compiler and its MCU dependency.
2221 <item>Parsing the source and building the annotated parse tree. This phase is
2222 largely MCU independent (except for the language extensions). Syntax &
2223 semantic checks are also done in this phase , along with some initial optimizations
2224 like back patching labels and the pattern matching optimizations like bit-rotation
2226 <item>The second phase involves generating an intermediate code which can be
2227 easy manipulated during the later phases. This phase is entirely MCU independent.
2228 The intermediate code generation assumes the target machine has unlimited number
2229 of registers, and designates them with the name iTemp. The compiler can be
2230 made to dump a human readable form of the code generated by using the --dumpraw
2232 <item>This phase does the bulk of the standard optimizations and is also MCU
2233 independent. This phase can be broken down into several sub-phases.
2235 <item>Break down intermediate code (iCode) into basic blocks.
2236 <item>Do control flow & data flow analysis on the basic blocks.
2237 <item>Do local common subexpression elimination, then global subexpression elimination
2238 <item>dead code elimination
2239 <item>loop optimizations
2240 <item>if loop optimizations caused any changes then do 'global subexpression
2241 elimination' and 'dead code elimination' again.
2243 <item>This phase determines the live-ranges; by live range I mean those iTemp
2244 variables defined by the compiler that still survive after all the optimizations.
2245 Live range analysis is essential for register allocation, since these computation
2246 determines which of these iTemps will be assigned to registers, and for how
2248 <item>Phase five is register allocation. There are two parts to this process
2251 <item>The first part I call 'register packing' (for lack of a better term) .
2252 In this case several MCU specific expression folding is done to reduce register
2254 <item>The second part is more MCU independent and deals with allocating registers
2255 to the remaining live ranges. A lot of MCU specific code does creep into this
2256 phase because of the limited number of index registers available in the 8051.
2258 <item>The Code generation phase is (unhappily), entirely MCU dependent and very
2259 little (if any at all) of this code can be reused for other MCU. However the
2260 scheme for allocating a homogenized assembler operand for each iCode operand
2262 <item>As mentioned in the optimization section the peep-hole optimizer is rule
2263 based system, which can reprogrammed for other MCUs.
2265 <sect>Reporting Bugs<label id="Bugs" >
2266 <p>Shoot of an email to 'sandeep.dutta@usa.net', as a matter of principle
2267 I always reply to all email's sent to me. Bugs will be fixed ASAP. When reporting
2268 a bug , it is useful to include a small snippet of code that is causing the
2269 problem, if possible compile your program with the --dumpall option and send
2270 the dump files along with the bug report.
2272 <sect>SDCDB - Source level debugger.
2273 <p>SDCC is distributed with a source level debugger. The debugger uses a command
2274 line interface, the command repertoire of the debugger has been kept as close
2275 to gdb ( the GNU debugger) as possible. The configuration and build process
2276 of the compiler see Installation <ref id="Installation" name="" > also builds and installs the debugger in
2277 the target directory specified during configuration. The debugger allows you
2278 debug BOTH at the C source and at the ASM source level.
2280 <sect1>Compiling for debugging.
2281 <p>The --debug option must be specified for all files for which debug information
2282 is to be generated. The complier generates a .cdb file for each of these files.
2283 The linker updates the .cdb file with the address information. This .cdb is
2284 used by the debugger .
2286 <sect1>How the debugger works.
2287 <p>When the --debug option is specified the compiler generates extra symbol
2288 information some of which are put into the the assembler source and some are
2289 put into the .cdb file, the linker updates the .cdb file with the address information
2290 for the symbols. The debugger reads the symbolic information generated by the
2291 compiler & the address information generated by the linker. It uses the
2292 SIMULATOR (Daniel's S51) to execute the program, the program execution is controlled
2293 by the debugger. When a command is issued for the debugger, it translates it
2294 into appropriate commands for the simulator .
2296 <sect1>Starting the debugger.
2297 <p>The debugger can be started using the following command line. (Assume the
2298 file you are debugging has
2300 <p>the file name foo).
2305 <p>The debugger will look for the following files.
2309 <item>foo.c - the source file.
2310 <item>foo.cdb - the debugger symbol information file.
2311 <item>foo.ihx - the intel hex format object file.
2313 <sect1>Command line options.
2316 <item>--directory=<source file directory> this option can used to specify
2317 the directory search list. The debugger will look into the directory list specified
2318 for source , cdb & ihx files. The items in the directory list must be separated
2319 by ':' , e.g. if the source files can be in the directories /home/src1 and
2320 /home/src2, the --directory option should be --directory=/home/src1:/home/src2
2321 . Note there can be no spaces in the option.
2322 <item>-cd <directory> - change to the <directory>.
2323 <item>-fullname - used by GUI front ends.
2324 <item>-cpu <cpu-type> - this argument is passed to the simulator please
2325 see the simulator docs for details.
2326 <item>-X <Clock frequency > this options is passed to the simulator please
2327 see simulator docs for details.
2328 <item>-s <serial port file> passed to simulator see simulator docs for
2330 <item>-S <serial in,out> passed to simulator see simulator docs for details.
2332 <sect1>Debugger Commands.
2333 <p>As mention earlier the command interface for the debugger has been deliberately
2334 kept as close the GNU debugger gdb , as possible, this will help int integration
2335 with existing graphical user interfaces (like ddd, xxgdb or xemacs) existing
2336 for the GNU debugger.
2338 <sect2>break [line | file:line | function | file:function]
2339 <p>Set breakpoint at specified line or function.
2342 <verb>sdcdb>break 100
2343 sdcdb>break foo.c:100
2344 sdcdb>break funcfoo
2348 <sect2>clear [line | file:line | function | file:function ]
2349 <p>Clear breakpoint at specified line or function.
2352 <verb>sdcdb>clear 100
2353 sdcdb>clear foo.c:100
2354 sdcdb>clear funcfoo
2359 <p>Continue program being debugged, after breakpoint.
2362 <p>Execute till the end of the current function.
2364 <sect2>delete [n]
2365 <p>Delete breakpoint number 'n'. If used without any option clear ALL user
2366 defined break points.
2368 <sect2>info [break | stack | frame | registers ]
2371 <item>info break - list all breakpoints
2372 <item>info stack - show the function call stack.
2373 <item>info frame - show information about the current execution frame.
2374 <item>info registers - show content of all registers.
2377 <p>Step program until it reaches a different source line.
2380 <p>Step program, proceeding through subroutine calls.
2383 <p>Start debugged program.
2385 <sect2>ptype variable
2386 <p>Print type information of the variable.
2388 <sect2>print variable
2389 <p>print value of variable.
2391 <sect2>file filename
2392 <p>load the given file name. Note this is an alternate method of loading file
2396 <p>print information about current frame.
2399 <p>Toggle between C source & assembly source.
2401 <sect2>! simulator command
2402 <p>Send the string following '!' to the simulator, the simulator response
2403 is displayed. Note the debugger does not interpret the command being sent to
2404 the simulator, so if a command like 'go' is sent the debugger can loose its
2405 execution context and may display incorrect values.
2408 <p>&dquot;Watch me now. Iam going Down. My name is Bobby Brown&dquot;
2410 <sect1>Interfacing with XEmacs.
2411 <p>Two files are (in emacs lisp) are provided for the interfacing with XEmacs,
2412 sdcdb.el and sdcdbsrc.el. These two files can be found in the $(prefix)/bin
2413 directory after the installation is complete. These files need to be loaded
2414 into XEmacs for the interface to work, this can be done at XEmacs startup time
2415 by inserting the following into your '.xemacs' file (which can be found in
2416 your HOME directory) (load-file sdcdbsrc.el) [ .xemacs is a lisp file
2417 so the () around the command is REQUIRED), the files can also be loaded dynamically
2418 while XEmacs is running, set the environment variable 'EMACSLOADPATH' to the
2419 installation bin directory [$(prefix)/bin], then enter the
2420 following command ESC-x load-file sdcdbsrc . To start the interface enter the
2421 following command ESC-x sdcdbsrc , you will prompted to enter the file name
2424 <p>The command line options that are passed to the simulator directly are
2425 bound to default values in the file sdcdbsrc.el the variables are listed below
2426 these values maybe changed as required.
2430 <item>sdcdbsrc-cpu-type '51
2431 <item>sdcdbsrc-frequency '11059200
2432 <item>sdcdbsrc-serial nil
2434 <p>The following is a list of key mapping for the debugger interface.
2438 ;; Current Listing ::
2439 ;;key binding Comment
2441 ;;--- ------- -------
2444 sdcdb-next-from-src SDCDB next command
2445 ;; b sdcdb-back-from-src SDCDB
2447 ;; c sdcdb-cont-from-src SDCDB continue
2449 ;; s sdcdb-step-from-src SDCDB step command
2451 ;; ? sdcdb-whatis-c-sexp SDCDB ptypecommand for data
2455 sdcdbsrc-delete SDCDB Delete all breakpoints if no arg
2457 or delete arg (C-u arg x)
2458 ;; m sdcdbsrc-frame SDCDB
2459 Display current frame if no arg,
2461 or display frame arg
2464 ;; ! sdcdbsrc-goto-sdcdb Goto the SDCDB output
2466 ;; p sdcdb-print-c-sexp SDCDB print command
2470 g sdcdbsrc-goto-sdcdb Goto the SDCDB output buffer
2472 t sdcdbsrc-mode Toggles Sdcdbsrc mode (turns it
2475 ;; C-c C-f sdcdb-finish-from-src SDCDB finish command
2478 ;; C-x SPC sdcdb-break Set break for line with
2480 ;; ESC t sdcdbsrc-mode Toggle Sdcdbsrc mode
2482 ;; ESC m sdcdbsrc-srcmode Toggle list mode
2486 <sect>Conclusion<label id="Conclusion" >
2487 <p>SDCC is a large project , the compiler alone (without the Assembler Package
2488 , Preprocessor & garbage collector) is about 40,000 lines of code (blank
2489 stripped). As with any project of this size there are bound to be bugs, I am
2490 more than willing to work to fix these bugs , of course all the source code
2491 is included with the package.
2493 <p>Where does it go from here ? I am planning to target the Atmel AVR 8-bit
2494 MCUs which seems to have a lot of users. I am also planning to include an alias
2495 analysis system with this compiler (it does not currently have one).
2497 <sect>Acknowledgments<label id="Acknowledgements" >
2498 <p>Alan Baldwin (baldwin@shop-pdp.kent.edu) - Initial version of ASXXXX &
2501 <p>John Hartman (jhartman@compuserve.com) - Porting ASXXX & ASLINK for
2504 <p>Dmitry S. Obukhov (dso@usa.net) - malloc & serial i/o routines.
2506 <p>Daniel Drotos <drdani@mazsola.iit.uni-miskolc.hu> - for his Freeware
2509 <p>Jans J Boehm(boehm@sgi.com) and Alan J Demers - Conservative garbage collector
2512 <p>Malini Dutta(malini_dutta@hotmail.com) - my wife for her patience and support.
2514 <p>Unknown - for the GNU C - preprocessor.