1 #LyX 1.1 created this file. For more info see http://www.lyx.org/
14 \paperorientation portrait
17 \paragraph_separation indent
19 \quotes_language swedish
27 SDCC Compiler User Guide
31 \begin_inset LatexCommand \tableofcontents{}
48 is a Freeware, retargettable, optimizing ANSI-C compiler by
52 designed for 8 bit Microprocessors.
53 The current version targets Intel MCS51 based Microprocessors(8051,8052,
54 etc), Zilog Z80 based MCUs, and the Dallas DS80C390 variant.
55 It can be retargetted for other microprocessors, support for PIC, AVR and
56 186 is under development.
57 The entire source code for the compiler is distributed under GPL.
58 SDCC uses ASXXXX & ASLINK, a Freeware, retargettable assembler & linker.
59 SDCC has extensive language extensions suitable for utilizing various microcont
60 rollers and underlying hardware effectively.
65 In addition to the MCU specific optimizations SDCC also does a host of standard
69 global sub expression elimination,
72 loop optimizations (loop invariant, strength reduction of induction variables
76 constant folding & propagation,
92 For the back-end SDCC uses a global register allocation scheme which should
93 be well suited for other 8 bit MCUs.
98 The peep hole optimizer uses a rule based substitution mechanism which is
104 Supported data-types are:
107 char (8 bits, 1 byte),
110 short and int (16 bits, 2 bytes),
113 long (32 bit, 4 bytes)
120 The compiler also allows
122 inline assembler code
124 to be embedded anywhere in a function.
125 In addition, routines developed in assembly can also be called.
129 SDCC also provides an option (--cyclomatic) to report the relative complexity
131 These functions can then be further optimized, or hand coded in assembly
137 SDCC also comes with a companion source level debugger SDCDB, the debugger
138 currently uses ucSim a freeware simulator for 8051 and other micro-controllers.
143 The latest version can be downloaded from
144 \begin_inset LatexCommand \htmlurl{http://sdcc.sourceforge.net/}
156 All packages used in this compiler system are
164 ; source code for all the sub-packages (asxxxx assembler/linker, pre-processor)
165 is distributed with the package.
166 This documentation is maintained using a freeware word processor (LyX).
170 This program is free software; you can redistribute it and/or modify it
171 under the terms of the GNU General Public License as published by the Free
172 Software Foundation; either version 2, or (at your option) any later version.
173 This program is distributed in the hope that it will be useful, but WITHOUT
174 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
175 FOR A PARTICULAR PURPOSE.
176 See the GNU General Public License for more details.
177 You should have received a copy of the GNU General Public License along
178 with this program; if not, write to the Free Software Foundation, 59 Temple
179 Place - Suite 330, Boston, MA 02111-1307, USA.
180 In other words, you are welcome to use, share and improve this program.
181 You are forbidden to forbid anyone else to use, share and improve what
183 Help stamp out software-hoarding!
186 Typographic conventions
189 Throughout this manual, we will use the following convention.
190 Commands you have to type in are printed in
198 Code samples are printed in
203 Interesting items and new terms are printed in
208 Compatibility with previous versions
211 This version has numerous bug fixes compared with the previous version.
212 But we also introduced some incompatibilities with older versions.
213 Not just for the fun of it, but to make the compiler more stable, efficient
220 short is now equivalent to int (16 bits), it used to be equivalent to char
224 the default directory where include, library and documention files are stored
225 is no in /usr/local/share
228 char type parameters to vararg functions are casted to int unless explicitly
245 will push a as an int and as a char resp.
248 option --regextend has been removed
251 option --noreparms has been removed
256 <pending: more incompatibilities?>
262 What do you need before you start installation of SDCC? A computer, and
264 The preferred method of installation is to compile SDCC from source using
266 For Windows some pre-compiled binary distributions are available for your
268 You should have some experience with command line tools and compiler use.
274 The SDCC home page at
275 \begin_inset LatexCommand \htmlurl{http://sdcc.sourceforge.net/}
279 is a great place to find distribution sets.
280 You can also find links to the user mailing lists that offer help or discuss
281 SDCC with other SDCC users.
282 Web links to other SDCC related sites can also be found here.
283 This document can be found in the DOC directory of the source package as
285 Some of the other tools (simulator and assembler) included with SDCC contain
286 their own documentation and can be found in the source distribution.
287 If you want the latest unreleased software, the complete source package
288 is available directly by anonymous CVS on cvs.sdcc.sourceforge.net.
291 Wishes for the future
294 There are (and always will be) some things that could be done.
295 Here are some I can think of:
303 sdcc -c --model-large -o large _atoi.c
306 (where large could be a different basename or a directory)
313 char KernelFunction3(char p) at 0x340;
319 If you can think of some more, please send them to the list.
325 <pending: And then of course a proper index-table
326 \begin_inset LatexCommand \index{index}
336 Linux/Unix Installation
341 Download the source package, it will be named something like sdcc-2.x.x.tgz.
346 Bring up a command line terminal, such as xterm.
351 Unpack the file using a command like:
354 "tar -xzf sdcc-2.x.x.tgz
359 , this will create a sub-directory called sdcc with all of the sources.
362 Change directory into the main SDCC directory, for example type:
379 This configures the package for compilation on your system.
395 All of the source packages will compile, this can take a while.
411 This copies the binary executables, the include files, the libraries and
412 the documentation to the install directories.
420 <pending: is this complete? where is borland, mingw>
426 For installation under Windows you first need to pick between a pre-compiled
427 binary package, or installing the source package along with the Cygwin
429 The binary package is the quickest to install, while the Cygwin package
430 includes all of the open source power tools used to compile the complete
431 SDCC source package in the Windows environment.
432 If you are not familiar with the Unix command line environment, you may
433 want to read the section on additional information for Windows users prior
434 to your initial installation.
435 \layout Subsubsection
437 Windows Install Using a Binary Package
440 Download the binary package and unpack it using your favorite unpacking
441 tool (gunzip, WinZip, etc).
442 This should unpack to a group of sub-directories.
443 An example directory structure after unpacking is: c:
449 bin for the executables, c:
469 lib for the include and libraries.
472 Adjust your environment PATH to include the location of the bin directory.
473 For example, make a setsdcc.bat file with the following: set PATH=c:
482 When you compile with sdcc, you may need to specify the location of the
483 lib and include folders.
484 For example, sdcc -I c:
507 \layout Subsubsection
509 Windows Install Using Cygwin
514 Download and install the cygwin package from the redhat site
517 \begin_inset LatexCommand \htmlurl{http://sources.redhat.com/cygwin/}
524 Currently, this involved downloading a small install program which then
525 automates downloading and installing
531 (a large 80M byte sized dowload for the whole thing)
545 command line terminal from the Cygwin menu.
550 Follow the instructions in the preceding Linux/Unix installation section.
553 Testing out the SDCC Compiler
556 The first thing you should do after installing your SDCC compiler is to
564 at the prompt, and the program should run and tell you the version.
565 If it doesn't run, or gives a message about not finding sdcc program, then
566 you need to check over your installation.
567 Make sure that the sdcc bin directory is in your executable search path
568 defined by the PATH environment setting (see the Trouble-shooting section
570 Make sure that the sdcc program is in the bin folder, if not perhaps something
571 did not install correctly.
577 SDCC binaries are commonly installed in a directory arrangement like this:
585 <lyxtabular version="2" rows="3" columns="2">
586 <features rotate="false" islongtable="false" endhead="0" endfirsthead="0" endfoot="0" endlastfoot="0">
587 <column alignment="left" valignment="top" leftline="true" rightline="false" width="" special="">
588 <column alignment="left" valignment="top" leftline="true" rightline="true" width="" special="">
589 <row topline="true" bottomline="true" newpage="false">
590 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
600 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
607 Holds executables(sdcc, s51, aslink,
615 <row topline="true" bottomline="false" newpage="false">
616 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
623 usr/local/share/sdcc/lib
626 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
639 <row topline="true" bottomline="true" newpage="false">
640 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
647 usr/local/share/sdcc/include
650 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
657 Holds common C header files
671 Make sure the compiler works on a very simple example.
672 Type in the following test.c program using your favorite editor:
702 Compile this using the following command:
711 If all goes well, the compiler will generate a test.asm and test.rel file.
712 Congratulations, you've just compiled your first program with SDCC.
713 We used the -c option to tell SDCC not to link the generated code, just
714 to keep things simple for this step.
722 The next step is to try it with the linker.
732 If all goes well the compiler will link with the libraries and produce
733 a test.ihx output file.
738 (no test.ihx, and the linker generates warnings), then the problem is most
739 likely that sdcc cannot find the
743 usr/local/share/sdcc/lib directory
747 (see the Install trouble-shooting section for suggestions).
755 The final test is to ensure sdcc can use the
759 header files and libraries.
760 Edit test.c and change it to the following:
778 strcpy(str1, "testing");
787 Compile this by typing
794 This should generate a test.ihx output file, and it should give no warnings
795 such as not finding the string.h file.
796 If it cannot find the string.h file, then the problem is that sdcc cannot
797 find the /usr/local/share/sdcc/include directory
801 (see the Install trouble-shooting section for suggestions).
804 Install Trouble-shooting
805 \layout Subsubsection
807 SDCC cannot find libraries or header files.
810 The default installation assumes the libraries and header files are located
812 \begin_inset Quotes eld
815 /usr/local/share/sdcc/lib
816 \begin_inset Quotes erd
820 \begin_inset Quotes eld
823 /usr/local/share/sdcc/include
824 \begin_inset Quotes erd
828 An alternative is to specify these locations as compiler options like this:
834 /usr/local/sdcc/lib/small\SpecialChar ~
836 /usr/local/sdcc/include\SpecialChar ~
841 \layout Subsubsection
843 SDCC does not compile correctly.
846 A thing to try is starting from scratch by unpacking the .tgz source package
847 again in an empty directory.
848 Confure it again and build like:
855 make 2&>1 | tee make.log
862 After this you can review the make.log file to locate the problem.
863 Or a relevant part of this be attached to an email that could be helpful
864 when requesting help from the mailing list.
865 \layout Subsubsection
868 \begin_inset Quotes sld
872 \begin_inset Quotes srd
879 \begin_inset Quotes sld
883 \begin_inset Quotes srd
886 command is a script that analyzes your system and performs some configuration
887 to ensure the source package compiles on your system.
888 It will take a few minutes to run, and will compile a few tests to determine
889 what compiler features are installed.
890 \layout Subsubsection
893 \begin_inset Quotes sld
897 \begin_inset Quotes srd
903 This runs the GNU make tool, which automatically compiles all the source
904 packages into the final installed binary executables.
905 \layout Subsubsection
908 \begin_inset Quotes sld
912 \begin_inset Quotes erd
918 This will install the compiler, other executables and libraries in to the
919 appropriate system directories.
920 The default is to copy the executables to /usr/local/bin and the libraries
921 and header files to /usr/local/share/sdcc/lib and /usr/local/share/sdcc/include.
924 Additional Information for Windows Users
929 <pending: is this up to date?>
935 The standard method of installing on a Unix system involves compiling the
937 This is easily done under Unix, but under Windows it can be a more difficult
939 The Cygwin is a large package to download, and the compilation runs considerabl
940 y slower under Windows due to the overhead of the Cygwin tool set.
941 An alternative is to install a pre-compiled Windows binary package.
942 There are various trade-offs between each of these methods.
946 The Cygwin package allows a Windows user to run a Unix command line interface
947 (bash shell) and also implements a Unix like file system on top of Windows.
948 Included are many of the famous GNU software development tools which can
949 augment the SDCC compiler.This is great if you have some experience with
950 Unix command line tools and file system conventions, if not you may find
951 it easier to start by installing a binary Windows package.
952 The binary packages work with the Windows file system conventions.
953 \layout Subsubsection
955 Getting started with Cygwin
958 SDCC is typically distributed as a tarred/gzipped file (.tgz).
959 This is a packed file similar to a .zip file.
960 Cygwin includes the tools you will need to unpack the SDCC distribution
962 To unpack it, simply follow the instructions under the Linux/Unix install
964 Before you do this you need to learn how to start a cygwin shell and some
965 of the basic commands used to move files, change directory, run commands
967 The change directory command is
971 \begin_inset Quotes eld
975 \begin_inset Quotes erd
981 , the move command is
985 \begin_inset Quotes eld
989 \begin_inset Quotes erd
996 To print the current working directory, type
1000 \begin_inset Quotes eld
1004 \begin_inset Quotes erd
1011 To make a directory, use
1015 \begin_inset Quotes eld
1019 \begin_inset Quotes erd
1028 There are some basic differences between Unix and Windows file systems you
1030 When you type in directory paths, Unix and the Cygwin bash prompt uses
1031 forward slashes '/' between directories while Windows traditionally uses
1035 So when you work at the Cygwin bash prompt, you will need to use the forward
1037 Unix does not have a concept of drive letters, such as
1038 \begin_inset Quotes eld
1042 \begin_inset Quotes eld
1045 , instead all files systems attach and appear as directories.
1046 \layout Subsubsection
1048 Running SDCC as Native Compiled Executables
1051 If you use the pre-compiled binaries, the install directories for the libraries
1052 and header files may need to be specified on the sdcc command line like
1077 if you are running outside of a Unix bash shell.
1080 If you have successfully installed and compiled SDCC with the Cygwin package,
1081 it is possible to compile into native .exe files by using the additional
1082 makefiles included for this purpose.
1083 For example, with the Borland 32-bit compiler you would run
1086 "make -f Makefile.bcc"
1090 A command line version of the Borland 32-bit compiler can be downloaded
1091 from the Inprise web site.
1094 SDCC on Other Platforms
1099 FreeBSD and other non-GNU Unixes
1101 - Make sure the GNU make is installed as the default make tool.
1104 SDCC has been ported to run under a variety of operating systems and processors.
1105 If you can run GNU GCC/make then chances are good SDCC can be compiled
1106 and run on your system.
1109 Advanced Install Options
1113 \begin_inset Quotes eld
1117 \begin_inset Quotes erd
1120 command has several options.
1121 The most commonly used option is --prefix=<directory name>, where <directory
1122 name> is the final location for the sdcc executables and libraries, (default
1123 location is /usr/local).
1124 The installation process will create the following directory structure
1125 under the <directory name> specified (if they do not already exist).
1130 bin/ - binary exectables (add to PATH environment variable)
1134 bin/share/sdcc/include/ - include header files
1138 bin/share/sdcc/lib/small/ - Object & library files for small model library
1140 bin/share/sdcc/lib/large/ - Object & library files for large model library
1142 bin/share/sdcc/lib/ds390/ - Object & library files forDS80C390 library
1150 \begin_inset Quotes sld
1153 ./configure --prefix=/usr/local
1154 \begin_inset Quotes erd
1160 will configure the compiler to be installed in directory /usr/local.
1166 SDCC is not just a compiler, but a collection of tools by various developers.
1167 These include linkers, assemblers, simulators and other components.
1168 Here is a summary of some of the components.
1169 Note that the included simulator and assembler have separate documentation
1170 which you can find in the source package in their respective directories.
1171 As SDCC grows to include support for other processors, other packages from
1172 various developers are included and may have their own sets of documentation.
1176 You might want to look at the files which are installed in <installdir>.
1177 At the time of this writing, we find the following programs:
1181 In <installdir>/bin:
1184 sdcc - The compiler.
1187 sdcpp - The C preprocessor.
1190 asx8051 - The assembler for 8051 type processors.
1197 as-gbz80 - The Z80 and GameBoy Z80 assemblers.
1200 aslink -The linker for 8051 type processors.
1207 link-gbz80 - The Z80 and GameBoy Z80 linkers.
1210 s51 - The ucSim 8051 simulator.
1213 sdcdb - The source debugger.
1216 packihx - A tool to pack Intel hex files.
1219 In <installdir>/share/sdcc/include
1225 In <installdir>/share/sdcc/lib
1228 the sources of the runtime library and the subdirs small large and ds390
1229 with the precompiled relocatables.
1232 In <installdir>/share/sdcc/doc
1238 As development for other processors proceeds, this list will expand to include
1239 executables to support processors like AVR, PIC, etc.
1240 \layout Subsubsection
1245 This is the actual compiler, it in turn uses the c-preprocessor and invokes
1246 the assembler and linkage editor.
1247 \layout Subsubsection
1249 sdcpp (C-Preprocessor)
1252 The preprocessor is a modified version of the GNU preprocessor.
1253 The C preprocessor is used to pull in #include sources, process #ifdef
1254 statements, #defines and so on.
1255 \layout Subsubsection
1257 asx8051, as-z80, as-gbz80, aslink, link-z80, link-gbz80 (The Assemblers
1258 and Linkage Editors)
1261 This is retargettable assembler & linkage editor, it was developed by Alan
1263 John Hartman created the version for 8051, and I (Sandeep) have made some
1264 enhancements and bug fixes for it to work properly with the SDCC.
1265 \layout Subsubsection
1270 S51 is a freeware, opensource simulator developed by Daniel Drotos (
1271 \begin_inset LatexCommand \url{mailto:drdani@mazsola.iit.uni-miskolc.hu}
1276 The simulator is built as part of the build process.
1277 For more information visit Daniel's website at:
1278 \begin_inset LatexCommand \url{http://mazsola.iit.uni-miskolc.hu/~drdani/embedded/s51}
1283 \layout Subsubsection
1285 sdcdb - Source Level Debugger
1288 Sdcdb is the companion source level debugger.
1289 The current version of the debugger uses Daniel's Simulator S51, but can
1290 be easily changed to use other simulators.
1297 \layout Subsubsection
1299 Single Source File Projects
1302 For single source file 8051 projects the process is very simple.
1303 Compile your programs with the following command
1306 "sdcc sourcefile.c".
1310 This will compile, assemble and link your source file.
1311 Output files are as follows
1315 sourcefile.asm - Assembler source file created by the compiler
1317 sourcefile.lst - Assembler listing file created by the Assembler
1319 sourcefile.rst - Assembler listing file updated with linkedit information,
1320 created by linkage editor
1322 sourcefile.sym - symbol listing for the sourcefile, created by the assembler
1324 sourcefile.rel - Object file created by the assembler, input to Linkage editor
1326 sourcefile.map - The memory map for the load module, created by the Linker
1328 sourcefile.ihx - The load module in Intel hex format (you can select the
1329 Motorola S19 format with --out-fmt-s19)
1331 sourcefile.cdb - An optional file (with --debug) containing debug information
1334 \layout Subsubsection
1336 Projects with Multiple Source Files
1339 SDCC can compile only ONE file at a time.
1340 Let us for example assume that you have a project containing the following
1345 foo1.c (contains some functions)
1347 foo2.c (contains some more functions)
1349 foomain.c (contains more functions and the function main)
1357 The first two files will need to be compiled separately with the commands:
1389 Then compile the source file containing the
1393 function and link the files together with the following command:
1401 foomain.c\SpecialChar ~
1402 foo1.rel\SpecialChar ~
1414 can be separately compiled as well:
1425 sdcc foomain.rel foo1.rel foo2.rel
1432 The file containing the
1447 file specified in the command line, since the linkage editor processes
1448 file in the order they are presented to it.
1449 \layout Subsubsection
1451 Projects with Additional Libraries
1454 Some reusable routines may be compiled into a library, see the documentation
1455 for the assembler and linkage editor (which are in <installdir>/share/sdcc/doc)
1461 Libraries created in this manner can be included in the command line.
1462 Make sure you include the -L <library-path> option to tell the linker where
1463 to look for these files if they are not in the current directory.
1464 Here is an example, assuming you have the source file
1476 (if that is not the same as your current project):
1483 sdcc foomain.c foolib.lib -L mylib
1494 must be an absolute path name.
1498 The most efficient way to use libraries is to keep seperate modules in seperate
1500 The lib file now should name all the modules.rel files.
1501 For an example see the standard library file
1505 in the directory <installdir>/share/lib/small.
1508 Command Line Options
1509 \layout Subsubsection
1511 Processor Selection Options
1513 \labelwidthstring 00.00.0000
1519 Generate code for the MCS51 (8051) family of processors.
1520 This is the default processor target.
1522 \labelwidthstring 00.00.0000
1528 Generate code for the DS80C390 processor.
1530 \labelwidthstring 00.00.0000
1536 Generate code for the Z80 family of processors.
1538 \labelwidthstring 00.00.0000
1544 Generate code for the GameBoy Z80 processor.
1546 \labelwidthstring 00.00.0000
1552 Generate code for the Atmel AVR processor(In development, not complete).
1554 \labelwidthstring 00.00.0000
1560 Generate code for the PIC 14-bit processors(In development, not complete).
1562 \labelwidthstring 00.00.0000
1568 Generate code for the Toshiba TLCS-900H processor(In development, not complete).
1569 \layout Subsubsection
1571 Preprocessor Options
1573 \labelwidthstring 00.00.0000
1579 The additional location where the pre processor will look for <..h> or
1580 \begin_inset Quotes eld
1584 \begin_inset Quotes erd
1589 \labelwidthstring 00.00.0000
1595 Command line definition of macros.
1596 Passed to the pre processor.
1598 \labelwidthstring 00.00.0000
1604 Tell the preprocessor to output a rule suitable for make describing the
1605 dependencies of each object file.
1606 For each source file, the preprocessor outputs one make-rule whose target
1607 is the object file name for that source file and whose dependencies are
1608 all the files `#include'd in it.
1609 This rule may be a single line or may be continued with `
1611 '-newline if it is long.
1612 The list of rules is printed on standard output instead of the preprocessed
1616 \labelwidthstring 00.00.0000
1622 Tell the preprocessor not to discard comments.
1623 Used with the `-E' option.
1625 \labelwidthstring 00.00.0000
1636 Like `-M' but the output mentions only the user header files included with
1638 \begin_inset Quotes eld
1642 System header files included with `#include <file>' are omitted.
1644 \labelwidthstring 00.00.0000
1650 Assert the answer answer for question, in case it is tested with a preprocessor
1651 conditional such as `#if #question(answer)'.
1652 `-A-' disables the standard assertions that normally describe the target
1655 \labelwidthstring 00.00.0000
1661 (answer) Assert the answer answer for question, in case it is tested with
1662 a preprocessor conditional such as `#if #question(answer)'.
1663 `-A-' disables the standard assertions that normally describe the target
1666 \labelwidthstring 00.00.0000
1672 Undefine macro macro.
1673 `-U' options are evaluated after all `-D' options, but before any `-include'
1674 and `-imacros' options.
1676 \labelwidthstring 00.00.0000
1682 Tell the preprocessor to output only a list of the macro definitions that
1683 are in effect at the end of preprocessing.
1684 Used with the `-E' option.
1686 \labelwidthstring 00.00.0000
1692 Tell the preprocessor to pass all macro definitions into the output, in
1693 their proper sequence in the rest of the output.
1695 \labelwidthstring 00.00.0000
1706 Like `-dD' except that the macro arguments and contents are omitted.
1707 Only `#define name' is included in the output.
1708 \layout Subsubsection
1712 \labelwidthstring 00.00.0000
1722 <absolute path to additional libraries> This option is passed to the linkage
1723 editor's additional libraries search path.
1724 The path name must be absolute.
1725 Additional library files may be specified in the command line.
1726 See section Compiling programs for more details.
1728 \labelwidthstring 00.00.0000
1734 <Value> The start location of the external ram, default value is 0.
1735 The value entered can be in Hexadecimal or Decimal format, e.g.: --xram-loc
1736 0x8000 or --xram-loc 32768.
1738 \labelwidthstring 00.00.0000
1744 <Value> The start location of the code segment, default value 0.
1745 Note when this option is used the interrupt vector table is also relocated
1746 to the given address.
1747 The value entered can be in Hexadecimal or Decimal format, e.g.: --code-loc
1748 0x8000 or --code-loc 32768.
1750 \labelwidthstring 00.00.0000
1756 <Value> The initial value of the stack pointer.
1757 The default value of the stack pointer is 0x07 if only register bank 0
1758 is used, if other register banks are used then the stack pointer is initialized
1759 to the location above the highest register bank used.
1761 if register banks 1 & 2 are used the stack pointer will default to location
1763 The value entered can be in Hexadecimal or Decimal format, eg.
1764 --stack-loc 0x20 or --stack-loc 32.
1765 If all four register banks are used the stack will be placed after the
1766 data segment (equivalent to --stack-after-data)
1768 \labelwidthstring 00.00.0000
1774 This option will cause the stack to be located in the internal ram after
1777 \labelwidthstring 00.00.0000
1783 <Value> The start location of the internal ram data segment, the default
1784 value is 0x30.The value entered can be in Hexadecimal or Decimal format,
1786 --data-loc 0x20 or --data-loc 32.
1788 \labelwidthstring 00.00.0000
1794 <Value> The start location of the indirectly addressable internal ram, default
1796 The value entered can be in Hexadecimal or Decimal format, eg.
1797 --idata-loc 0x88 or --idata-loc 136.
1799 \labelwidthstring 00.00.0000
1808 The linker output (final object code) is in Intel Hex format.
1809 (This is the default option).
1811 \labelwidthstring 00.00.0000
1820 The linker output (final object code) is in Motorola S19 format.
1821 \layout Subsubsection
1825 \labelwidthstring 00.00.0000
1831 Generate code for Large model programs see section Memory Models for more
1833 If this option is used all source files in the project should be compiled
1835 In addition the standard library routines are compiled with small model,
1836 they will need to be recompiled.
1838 \labelwidthstring 00.00.0000
1849 Generate code for Small Model programs see section Memory Models for more
1851 This is the default model.
1852 \layout Subsubsection
1856 \labelwidthstring 00.00.0000
1867 Generate 24-bit flat mode code.
1868 This is the one and only that the ds390 code generator supports right now
1869 and is default when using
1874 See section Memory Models for more details.
1876 \labelwidthstring 00.00.0000
1882 Generate code for the 10 bit stack mode of the Dallas DS80C390 part.
1883 This is the one and only that the ds390 code generator supports right now
1884 and is default when using
1889 In this mode, the stack is located in the lower 1K of the internal RAM,
1890 which is mapped to 0x400000.
1891 Note that the support is incomplete, since it still uses a single byte
1892 as the stack pointer.
1893 This means that only the lower 256 bytes of the potential 1K stack space
1894 will actually be used.
1895 However, this does allow you to reclaim the precious 256 bytes of low RAM
1896 for use for the DATA and IDATA segments.
1897 The compiler will not generate any code to put the processor into 10 bit
1899 It is important to ensure that the processor is in this mode before calling
1900 any re-entrant functions compiled with this option.
1901 In principle, this should work with the
1905 option, but that has not been tested.
1906 It is incompatible with the
1911 It also only makes sense if the processor is in 24 bit contiguous addressing
1914 --model-flat24 option
1917 \layout Subsubsection
1919 Optimization Options
1921 \labelwidthstring 00.00.0000
1927 Will not do global subexpression elimination, this option may be used when
1928 the compiler creates undesirably large stack/data spaces to store compiler
1930 A warning message will be generated when this happens and the compiler
1931 will indicate the number of extra bytes it allocated.
1932 It recommended that this option NOT be used, #pragma\SpecialChar ~
1934 to turn off global subexpression elimination for a given function only.
1936 \labelwidthstring 00.00.0000
1942 Will not do loop invariant optimizations, this may be turned off for reasons
1943 explained for the previous option.
1944 For more details of loop optimizations performed see section Loop Invariants.It
1945 recommended that this option NOT be used, #pragma\SpecialChar ~
1946 NOINVARIANT can be used
1947 to turn off invariant optimizations for a given function only.
1949 \labelwidthstring 00.00.0000
1955 Will not do loop induction optimizations, see section strength reduction
1956 for more details.It is recommended that this option is NOT used, #pragma\SpecialChar ~
1958 ION can be used to turn off induction optimizations for a given function
1961 \labelwidthstring 00.00.0000
1972 Will not generate boundary condition check when switch statements are implement
1973 ed using jump-tables.
1974 See section Switch Statements for more details.
1975 It is recommended that this option is NOT used, #pragma\SpecialChar ~
1977 used to turn off boundary checking for jump tables for a given function
1980 \labelwidthstring 00.00.0000
1989 Will not do loop reversal optimization.
1990 \layout Subsubsection
1994 \labelwidthstring 00.00.0000
2001 will compile and assemble the source, but will not call the linkage editor.
2003 \labelwidthstring 00.00.0000
2009 Run only the C preprocessor.
2010 Preprocess all the C source files specified and output the results to standard
2013 \labelwidthstring 00.00.0000
2024 All functions in the source file will be compiled as
2029 the parameters and local variables will be allocated on the stack.
2030 see section Parameters and Local Variables for more details.
2031 If this option is used all source files in the project should be compiled
2035 \labelwidthstring 00.00.0000
2041 Uses a pseudo stack in the first 256 bytes in the external ram for allocating
2042 variables and passing parameters.
2043 See section on external stack for more details.
2045 \labelwidthstring 00.00.0000
2049 --callee-saves function1[,function2][,function3]....
2052 The compiler by default uses a caller saves convention for register saving
2053 across function calls, however this can cause unneccessary register pushing
2054 & popping when calling small functions from larger functions.
2055 This option can be used to switch the register saving convention for the
2056 function names specified.
2057 The compiler will not save registers when calling these functions, no extra
2058 code will be generated at the entry & exit for these functions to save
2059 & restore the registers used by these functions, this can SUBSTANTIALLY
2060 reduce code & improve run time performance of the generated code.
2061 In the future the compiler (with interprocedural analysis) will be able
2062 to determine the appropriate scheme to use for each function call.
2063 DO NOT use this option for built-in functions such as _muluint..., if this
2064 option is used for a library function the appropriate library function
2065 needs to be recompiled with the same option.
2066 If the project consists of multiple source files then all the source file
2067 should be compiled with the same --callee-saves option string.
2068 Also see #pragma\SpecialChar ~
2071 \labelwidthstring 00.00.0000
2080 When this option is used the compiler will generate debug information, that
2081 can be used with the SDCDB.
2082 The debug information is collected in a file with .cdb extension.
2083 For more information see documentation for SDCDB.
2085 \labelwidthstring 00.00.0000
2095 This option is obsolete and isn't supported anymore.
2097 \labelwidthstring 00.00.0000
2104 This option is obsolete and isn't supported anymore.
2106 \labelwidthstring 00.00.0000
2112 <filename> This option can be used to use additional rules to be used by
2113 the peep hole optimizer.
2114 See section Peep Hole optimizations for details on how to write these rules.
2116 \labelwidthstring 00.00.0000
2127 Stop after the stage of compilation proper; do not assemble.
2128 The output is an assembler code file for the input file specified.
2130 \labelwidthstring 00.00.0000
2134 -Wa_asmOption[,asmOption]
2137 Pass the asmOption to the assembler.
2139 \labelwidthstring 00.00.0000
2143 -Wl_linkOption[,linkOption]
2146 Pass the linkOption to the linker.
2148 \labelwidthstring 00.00.0000
2157 Integer (16 bit) and long (32 bit) libraries have been compiled as reentrant.
2158 Note by default these libraries are compiled as non-reentrant.
2159 See section Installation for more details.
2161 \labelwidthstring 00.00.0000
2170 This option will cause the compiler to generate an information message for
2171 each function in the source file.
2172 The message contains some
2176 information about the function.
2177 The number of edges and nodes the compiler detected in the control flow
2178 graph of the function, and most importantly the
2180 cyclomatic complexity
2182 see section on Cyclomatic Complexity for more details.
2184 \labelwidthstring 00.00.0000
2193 Floating point library is compiled as reentrant.See section Installation
2196 \labelwidthstring 00.00.0000
2202 The compiler will not overlay parameters and local variables of any function,
2203 see section Parameters and local variables for more details.
2205 \labelwidthstring 00.00.0000
2211 This option can be used when the code generated is called by a monitor
2213 The compiler will generate a 'ret' upon return from the 'main' function.
2214 The default option is to lock up i.e.
2217 \labelwidthstring 00.00.0000
2223 Disable peep-hole optimization.
2225 \labelwidthstring 00.00.0000
2231 Pass the inline assembler code through the peep hole optimizer.
2232 This can cause unexpected changes to inline assembler code, please go through
2233 the peephole optimizer rules defined in the source file tree '<target>/peeph.def
2234 ' before using this option.
2236 \labelwidthstring 00.00.0000
2242 <Value> Causes the linker to check if the interal ram usage is within limits
2245 \labelwidthstring 00.00.0000
2251 This will prevent the compiler from passing on the default include path
2252 to the preprocessor.
2254 \labelwidthstring 00.00.0000
2260 This will prevent the compiler from passing on the default library path
2263 \labelwidthstring 00.00.0000
2269 Shows the various actions the compiler is performing.
2271 \labelwidthstring 00.00.0000
2277 Shows the actual commands the compiler is executing.
2278 \layout Subsubsection
2280 Intermediate Dump Options
2283 The following options are provided for the purpose of retargetting and debugging
2285 These provided a means to dump the intermediate code (iCode) generated
2286 by the compiler in human readable form at various stages of the compilation
2290 \labelwidthstring 00.00.0000
2296 This option will cause the compiler to dump the intermediate code into
2299 <source filename>.dumpraw
2301 just after the intermediate code has been generated for a function, i.e.
2302 before any optimizations are done.
2303 The basic blocks at this stage ordered in the depth first number, so they
2304 may not be in sequence of execution.
2306 \labelwidthstring 00.00.0000
2312 Will create a dump of iCode's, after global subexpression elimination,
2315 <source filename>.dumpgcse.
2317 \labelwidthstring 00.00.0000
2323 Will create a dump of iCode's, after deadcode elimination, into a file
2326 <source filename>.dumpdeadcode.
2328 \labelwidthstring 00.00.0000
2337 Will create a dump of iCode's, after loop optimizations, into a file named
2340 <source filename>.dumploop.
2342 \labelwidthstring 00.00.0000
2351 Will create a dump of iCode's, after live range analysis, into a file named
2354 <source filename>.dumprange.
2356 \labelwidthstring 00.00.0000
2362 Will dump the life ranges for all symbols.
2364 \labelwidthstring 00.00.0000
2373 Will create a dump of iCode's, after register assignment, into a file named
2376 <source filename>.dumprassgn.
2378 \labelwidthstring 00.00.0000
2384 Will create a dump of the live ranges of iTemp's
2386 \labelwidthstring 00.00.0000
2397 Will cause all the above mentioned dumps to be created.
2400 MCS51/DS390 Storage Class Language Extensions
2403 In addition to the ANSI storage classes SDCC allows the following MCS51
2404 specific storage classes.
2405 \layout Subsubsection
2410 Variables declared with this storage class will be placed in the extern
2416 storage class for Large Memory model, e.g.:
2422 xdata unsigned char xduc;
2423 \layout Subsubsection
2432 storage class for Small Memory model.
2433 Variables declared with this storage class will be allocated in the internal
2441 \layout Subsubsection
2446 Variables declared with this storage class will be allocated into the indirectly
2447 addressable portion of the internal ram of a 8051, e.g.:
2454 \layout Subsubsection
2459 This is a data-type and a storage class specifier.
2460 When a variable is declared as a bit, it is allocated into the bit addressable
2461 memory of 8051, e.g.:
2468 \layout Subsubsection
2473 Like the bit keyword,
2477 signifies both a data-type and storage class, they are used to describe
2478 the special function registers and special bit variables of a 8051, eg:
2484 sfr at 0x80 P0; /* special function register P0 at location 0x80 */
2486 sbit at 0xd7 CY; /* CY (Carry Flag) */
2492 SDCC allows (via language extensions) pointers to explicitly point to any
2493 of the memory spaces of the 8051.
2494 In addition to the explicit pointers, the compiler also allows a
2498 class of pointers which can be used to point to any of the memory spaces.
2502 Pointer declaration examples:
2511 /* pointer physically in xternal ram pointing to object in internal ram
2514 data unsigned char * xdata p;
2518 /* pointer physically in code rom pointing to data in xdata space */
2520 xdata unsigned char * code p;
2524 /* pointer physically in code space pointing to data in code space */
2526 code unsigned char * code p;
2530 /* the folowing is a generic pointer physically located in xdata space */
2541 Well you get the idea.
2548 For compatibility with the previous version of the compiler, the following
2549 syntax for pointer declaration is still supported but will disappear int
2557 unsigned char _xdata *ucxdp; /* pointer to data in external ram */
2559 unsigned char _data \SpecialChar ~
2560 *ucdp ; /* pointer to data in internal ram */
2562 unsigned char _code \SpecialChar ~
2563 *uccp ; /* pointer to data in R/O code space */
2565 unsigned char _idata *uccp; \SpecialChar ~
2566 /* pointer to upper 128 bytes of ram */
2576 All unqualified pointers are treated as 3-byte (4-byte for the ds390)
2581 These type of pointers can also to be explicitly declared.
2587 unsigned char _generic *ucgp;
2596 The highest order byte of the
2600 pointers contains the data space information.
2601 Assembler support routines are called whenever data is stored or retrieved
2607 These are useful for developing reusable library routines.
2608 Explicitly specifying the pointer type will generate the most efficient
2610 Pointers declared using a mixture of OLD and NEW style could have unpredictable
2614 Parameters & Local Variables
2617 Automatic (local) variables and parameters to functions can either be placed
2618 on the stack or in data-space.
2619 The default action of the compiler is to place these variables in the internal
2620 RAM (for small model) or external RAM (for Large model).
2621 This in fact makes them
2625 so by default functions are non-reentrant.
2628 They can be placed on the stack either by using the
2632 compiler option or by using the
2636 keyword in the function declaration, e.g.:
2645 unsigned char foo(char i) reentrant
2658 Since stack space on 8051 is limited, the
2666 option should be used sparingly.
2667 Note that the reentrant keyword just means that the parameters & local
2668 variables will be allocated to the stack, it
2672 mean that the function is register bank independent.
2676 Local variables can be assigned storage classes and absolute addresses,
2683 unsigned char foo() {
2689 xdata unsigned char i;
2701 data at 0x31 unsiged char j;
2716 In the above example the variable
2720 will be allocated in the external ram,
2724 in bit addressable space and
2733 or when a function is declared as
2737 this can only be done for static variables.
2740 Parameters however are not allowed any storage class, (storage classes for
2741 parameters will be ignored), their allocation is governed by the memory
2742 model in use, and the reentrancy options.
2748 For non-reentrant functions SDCC will try to reduce internal ram space usage
2749 by overlaying parameters and local variables of a function (if possible).
2750 Parameters and local variables of a function will be allocated to an overlayabl
2751 e segment if the function has
2753 no other function calls and the function is non-reentrant and the memory
2757 If an explicit storage class is specified for a local variable, it will
2761 Note that the compiler (not the linkage editor) makes the decision for overlayin
2763 Functions that are called from an interrupt service routine should be preceded
2764 by a #pragma\SpecialChar ~
2765 NOOVERLAY if they are not reentrant.
2768 Also note that the compiler does not do any processing of inline assembler
2769 code, so the compiler might incorrectly assign local variables and parameters
2770 of a function into the overlay segment if the inline assembler code calls
2771 other c-functions that might use the overlay.
2772 In that case the #pragma\SpecialChar ~
2773 NOOVERLAY should be used.
2776 Parameters and Local variables of functions that contain 16 or 32 bit multiplica
2777 tion or division will NOT be overlayed since these are implemented using
2778 external functions, e.g.:
2788 void set_error(unsigned char errcd)
2804 void some_isr () interrupt 2 using 1
2833 In the above example the parameter
2841 would be assigned to the overlayable segment if the #pragma\SpecialChar ~
2843 not present, this could cause unpredictable runtime behavior when called
2845 The #pragma\SpecialChar ~
2846 NOOVERLAY ensures that the parameters and local variables for
2847 the function are NOT overlayed.
2850 Interrupt Service Routines
2853 SDCC allows interrupt service routines to be coded in C, with some extended
2860 void timer_isr (void) interrupt 2 using 1
2873 The number following the
2877 keyword is the interrupt number this routine will service.
2878 The compiler will insert a call to this routine in the interrupt vector
2879 table for the interrupt number specified.
2884 keyword is used to tell the compiler to use the specified register bank
2885 (8051 specific) when generating code for this function.
2886 Note that when some function is called from an interrupt service routine
2887 it should be preceded by a #pragma\SpecialChar ~
2888 NOOVERLAY if it is not reentrant.
2889 A special note here, int (16 bit) and long (32 bit) integer division, multiplic
2890 ation & modulus operations are implemented using external support routines
2891 developed in ANSI-C, if an interrupt service routine needs to do any of
2892 these operations then the support routines (as mentioned in a following
2893 section) will have to be recompiled using the
2897 option and the source file will need to be compiled using the
2904 If you have multiple source files in your project, interrupt service routines
2905 can be present in any of them, but a prototype of the isr MUST be present
2906 or included in the file that contains the function
2913 Interrupt Numbers and the corresponding address & descriptions for the Standard
2914 8051 are listed below.
2915 SDCC will automatically adjust the interrupt vector table to the maximum
2916 interrupt number specified.
2922 \begin_inset Tabular
2923 <lyxtabular version="2" rows="6" columns="3">
2924 <features rotate="false" islongtable="false" endhead="0" endfirsthead="0" endfoot="0" endlastfoot="0">
2925 <column alignment="center" valignment="top" leftline="true" rightline="false" width="" special="">
2926 <column alignment="center" valignment="top" leftline="true" rightline="false" width="" special="">
2927 <column alignment="center" valignment="top" leftline="true" rightline="true" width="" special="">
2928 <row topline="true" bottomline="true" newpage="false">
2929 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2937 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2945 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
2954 <row topline="true" bottomline="false" newpage="false">
2955 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2963 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2971 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
2980 <row topline="true" bottomline="false" newpage="false">
2981 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2989 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
2997 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
3006 <row topline="true" bottomline="false" newpage="false">
3007 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3015 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3023 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
3032 <row topline="true" bottomline="false" newpage="false">
3033 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3041 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3049 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
3058 <row topline="true" bottomline="true" newpage="false">
3059 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3067 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="false" rotate="false" usebox="none" width="" special="">
3075 <cell multicolumn="0" alignment="center" valignment="top" topline="true" bottomline="false" leftline="true" rightline="true" rotate="false" usebox="none" width="" special="">
3092 If the interrupt service routine is defined without
3096 a register bank or with register bank 0 (using 0), the compiler will save
3097 the registers used by itself on the stack upon entry and restore them at
3098 exit, however if such an interrupt service routine calls another function
3099 then the entire register bank will be saved on the stack.
3100 This scheme may be advantageous for small interrupt service routines which
3101 have low register usage.
3104 If the interrupt service routine is defined to be using a specific register
3109 are save and restored, if such an interrupt service routine calls another
3110 function (using another register bank) then the entire register bank of
3111 the called function will be saved on the stack.
3112 This scheme is recommended for larger interrupt service routines.
3115 Calling other functions from an interrupt service routine is not recommended,
3116 avoid it if possible.
3120 Also see the _naked modifier.
3126 A special keyword may be associated with a function declaring it as
3131 SDCC will generate code to disable all interrupts upon entry to a critical
3132 function and enable them back before returning.
3133 Note that nesting critical functions may cause unpredictable results.
3158 The critical attribute maybe used with other attributes like
3166 A special keyword may be associated with a function declaring it as
3175 function modifier attribute prevents the compiler from generating prologue
3176 and epilogue code for that function.
3177 This means that the user is entirely responsible for such things as saving
3178 any registers that may need to be preserved, selecting the proper register
3179 bank, generating the
3183 instruction at the end, etc.
3184 Practically, this means that the contents of the function must be written
3185 in inline assembler.
3186 This is particularly useful for interrupt functions, which can have a large
3187 (and often unnecessary) prologue/epilogue.
3188 For example, compare the code generated by these two functions:
3194 data unsigned char counter;
3196 void simpleInterrupt(void) interrupt 1
3210 void nakedInterrupt(void) interrupt 2 _naked
3243 ; MUST explicitly include ret in _naked function.
3257 For an 8051 target, the generated simpleInterrupt looks like:
3402 whereas nakedInterrupt looks like:
3427 ; MUST explicitly include ret(i) in _naked function.
3433 While there is nothing preventing you from writing C code inside a _naked
3434 function, there are many ways to shoot yourself in the foot doing this,
3435 and is is recommended that you stick to inline assembler.
3438 Functions using private banks
3445 attribute (which tells the compiler to use a register bank other than the
3446 default bank zero) should only be applied to
3450 functions (see note 1 below).
3451 This will in most circumstances make the generated ISR code more efficient
3452 since it will not have to save registers on the stack.
3459 attribute will have no effect on the generated code for a
3463 function (but may occasionally be useful anyway
3464 \begin_float footnote
3467 possible exception: if a function is called ONLY from 'interrupt' functions
3468 using a particular bank, it can be declared with the same 'using' attribute
3469 as the calling 'interrupt' functions.
3470 For instance, if you have several ISRs using bank one, and all of them
3471 call memcpy(), it might make sense to create a specialized version of memcpy()
3472 'using 1', since this would prevent the ISR from having to save bank zero
3473 to the stack on entry and switch to bank zero before calling the function
3479 (pending: I don't think this has been done yet)
3486 function using a non-zero bank will assume that it can trash that register
3487 bank, and will not save it.
3488 Since high-priority interrupts can interrupt low-priority ones on the 8051
3489 and friends, this means that if a high-priority ISR
3493 a particular bank occurs while processing a low-priority ISR
3497 the same bank, terrible and bad things can happen.
3498 To prevent this, no single register bank should be
3502 by both a high priority and a low priority ISR.
3503 This is probably most easily done by having all high priority ISRs use
3504 one bank and all low priority ISRs use another.
3505 If you have an ISR which can change priority at runtime, you're on your
3506 own: I suggest using the default bank zero and taking the small performance
3510 It is most efficient if your ISR calls no other functions.
3511 If your ISR must call other functions, it is most efficient if those functions
3512 use the same bank as the ISR (see note 1 below); the next best is if the
3513 called functions use bank zero.
3514 It is very inefficient to call a function using a different, non-zero bank
3522 Data items can be assigned an absolute address with the
3526 keyword, in addition to a storage class, e.g.:
3532 xdata at 0x8000 unsigned char PORTA_8255 ;
3538 In the above example the PORTA_8255 will be allocated to the location 0x8000
3539 of the external ram.
3540 Note that this feature is provided to give the programmer access to
3544 devices attached to the controller.
3545 The compiler does not actually reserve any space for variables declared
3546 in this way (they are implemented with an equate in the assembler).
3547 Thus it is left to the programmer to make sure there are no overlaps with
3548 other variables that are declared without the absolute address.
3549 The assembler listing file (.lst) and the linker output files (.rst) and
3550 (.map) are a good places to look for such overlaps.
3554 Absolute address can be specified for variables in all storage classes,
3567 The above example will allocate the variable at offset 0x02 in the bit-addressab
3569 There is no real advantage to assigning absolute addresses to variables
3570 in this manner, unless you want strict control over all the variables allocated.
3576 The compiler inserts a call to the C routine
3578 _sdcc__external__startup()
3583 at the start of the CODE area.
3584 This routine is in the runtime library.
3585 By default this routine returns 0, if this routine returns a non-zero value,
3586 the static & global variable initialization will be skipped and the function
3587 main will be invoked Other wise static & global variables will be initialized
3588 before the function main is invoked.
3591 _sdcc__external__startup()
3593 routine to your program to override the default if you need to setup hardware
3594 or perform some other critical operation prior to static & global variable
3598 Inline Assembler Code
3601 SDCC allows the use of in-line assembler with a few restriction as regards
3603 All labels defined within inline assembler code
3611 where nnnn is a number less than 100 (which implies a limit of utmost 100
3612 inline assembler labels
3620 It is strongly recommended that each assembly instruction (including labels)
3621 be placed in a separate line (as the example shows).
3626 command line option is used, the inline assembler code will be passed through
3627 the peephole optimizer.
3628 This might cause some unexpected changes in the inline assembler code.
3629 Please go throught the peephole optimizer rules defined in file
3633 carefully before using this option.
3673 The inline assembler code can contain any valid code understood by the assembler
3674 , this includes any assembler directives and comment lines.
3675 The compiler does not do any validation of the code within the
3685 Inline assembler code cannot reference any C-Labels, however it can reference
3686 labels defined by the inline assembler, e.g.:
3712 ; some assembler code
3732 /* some more c code */
3734 clabel:\SpecialChar ~
3736 /* inline assembler cannot reference this label */
3748 $0003: ;label (can be reference by inline assembler only)
3760 /* some more c code */
3768 In other words inline assembly code can access labels defined in inline
3769 assembly within the scope of the funtion.
3773 The same goes the other way, ie.
3774 labels defines in inline assembly CANNOT be accessed by C statements.
3777 int(16 bit) and long (32 bit) Support
3780 For signed & unsigned int (16 bit) and long (32 bit) variables, division,
3781 multiplication and modulus operations are implemented by support routines.
3782 These support routines are all developed in ANSI-C to facilitate porting
3783 to other MCUs, although some model specific assembler optimations are used.
3784 The following files contain the described routine, all of them can be found
3785 in <installdir>/share/sdcc/lib.
3791 <pending: tabularise this>
3797 _mulsint.c - signed 16 bit multiplication (calls _muluint)
3799 _muluint.c - unsigned 16 bit multiplication
3801 _divsint.c - signed 16 bit division (calls _divuint)
3803 _divuint.c - unsigned 16 bit division
3805 _modsint.c - signed 16 bit modulus (call _moduint)
3807 _moduint.c - unsigned 16 bit modulus
3809 _mulslong.c - signed 32 bit multiplication (calls _mululong)
3811 _mululong.c - unsigned32 bit multiplication
3813 _divslong.c - signed 32 division (calls _divulong)
3815 _divulong.c - unsigned 32 division
3817 _modslong.c - signed 32 bit modulus (calls _modulong)
3819 _modulong.c - unsigned 32 bit modulus
3827 Since they are compiled as
3831 , interrupt service routines should not do any of the above operations.
3832 If this is unavoidable then the above routines will need to be compiled
3837 option, after which the source program will have to be compiled with
3844 Floating Point Support
3847 SDCC supports IEEE (single precision 4bytes) floating point numbers.The floating
3848 point support routines are derived from gcc's floatlib.c and consists of
3849 the following routines:
3855 <pending: tabularise this>
3861 _fsadd.c - add floating point numbers
3863 _fssub.c - subtract floating point numbers
3865 _fsdiv.c - divide floating point numbers
3867 _fsmul.c - multiply floating point numbers
3869 _fs2uchar.c - convert floating point to unsigned char
3871 _fs2char.c - convert floating point to signed char
3873 _fs2uint.c - convert floating point to unsigned int
3875 _fs2int.c - convert floating point to signed int
3877 _fs2ulong.c - convert floating point to unsigned long
3879 _fs2long.c - convert floating point to signed long
3881 _uchar2fs.c - convert unsigned char to floating point
3883 _char2fs.c - convert char to floating point number
3885 _uint2fs.c - convert unsigned int to floating point
3887 _int2fs.c - convert int to floating point numbers
3889 _ulong2fs.c - convert unsigned long to floating point number
3891 _long2fs.c - convert long to floating point number
3899 Note if all these routines are used simultaneously the data space might
3901 For serious floating point usage it is strongly recommended that the large
3908 SDCC allows two memory models for MCS51 code, small and large.
3909 Modules compiled with different memory models should
3913 be combined together or the results would be unpredictable.
3914 The library routines supplied with the compiler are compiled as both small
3916 The compiled library modules are contained in seperate directories as small
3917 and large so that you can link to either set.
3921 When the large model is used all variables declared without a storage class
3922 will be allocated into the external ram, this includes all parameters and
3923 local variables (for non-reentrant functions).
3924 When the small model is used variables without storage class are allocated
3925 in the internal ram.
3928 Judicious usage of the processor specific storage classes and the 'reentrant'
3929 function type will yield much more efficient code, than using the large
3931 Several optimizations are disabled when the program is compiled using the
3932 large model, it is therefore strongly recommdended that the small model
3933 be used unless absolutely required.
3939 The only model supported is Flat 24.
3940 This generates code for the 24 bit contiguous addressing mode of the Dallas
3942 In this mode, up to four meg of external RAM or code space can be directly
3944 See the data sheets at www.dalsemi.com for further information on this part.
3948 In older versions of the compiler, this option was used with the MCS51 code
3954 Now, however, the '390 has it's own code generator, selected by the
3963 Note that the compiler does not generate any code to place the processor
3964 into 24 bitmode (although
3968 in the ds390 libraries will do that for you).
3973 , the boot loader or similar code must ensure that the processor is in 24
3974 bit contiguous addressing mode before calling the SDCC startup code.
3982 option, variables will by default be placed into the XDATA segment.
3987 Segments may be placed anywhere in the 4 meg address space using the usual
3989 Note that if any segments are located above 64K, the -r flag must be passed
3990 to the linker to generate the proper segment relocations, and the Intel
3991 HEX output format must be used.
3992 The -r flag can be passed to the linker by using the option
3996 on the sdcc command line.
3997 However, currently the linker can not handle code segments > 64k.
4000 Defines Created by the Compiler
4003 The compiler creates the following #defines.
4006 SDCC - this Symbol is always defined.
4009 SDCC_mcs51 or SDCC_ds390 or SDCC_z80, etc - depending on the model used
4013 __mcs51 or __ds390 or __z80, etc - depending on the model used (e.g.
4017 SDCC_STACK_AUTO - this symbol is defined when
4024 SDCC_MODEL_SMALL - when
4031 SDCC_MODEL_LARGE - when
4038 SDCC_USE_XSTACK - when
4045 SDCC_STACK_TENBIT - when
4052 SDCC_MODEL_FLAT24 - when
4065 SDCC performs a host of standard optimizations in addition to some MCU specific
4068 \layout Subsubsection
4070 Sub-expression Elimination
4073 The compiler does local and global common subexpression elimination, e.g.:
4088 will be translated to
4104 Some subexpressions are not as obvious as the above example, e.g.:
4118 In this case the address arithmetic a->b[i] will be computed only once;
4119 the equivalent code in C would be.
4135 The compiler will try to keep these temporary variables in registers.
4136 \layout Subsubsection
4138 Dead-Code Elimination
4153 i = 1; \SpecialChar ~
4158 global = 1;\SpecialChar ~
4171 global = 3;\SpecialChar ~
4186 int global; void f ()
4199 \layout Subsubsection
4260 Note: the dead stores created by this copy propagation will be eliminated
4261 by dead-code elimination.
4262 \layout Subsubsection
4267 Two types of loop optimizations are done by SDCC loop invariant lifting
4268 and strength reduction of loop induction variables.
4269 In addition to the strength reduction the optimizer marks the induction
4270 variables and the register allocator tries to keep the induction variables
4271 in registers for the duration of the loop.
4272 Because of this preference of the register allocator, loop induction optimizati
4273 on causes an increase in register pressure, which may cause unwanted spilling
4274 of other temporary variables into the stack / data space.
4275 The compiler will generate a warning message when it is forced to allocate
4276 extra space either on the stack or data space.
4277 If this extra space allocation is undesirable then induction optimization
4278 can be eliminated either for the entire source file (with --noinduction
4279 option) or for a given function only using #pragma\SpecialChar ~
4290 for (i = 0 ; i < 100 ; i ++)
4308 for (i = 0; i < 100; i++)
4318 As mentioned previously some loop invariants are not as apparent, all static
4319 address computations are also moved out of the loop.
4323 Strength Reduction, this optimization substitutes an expression by a cheaper
4330 for (i=0;i < 100; i++)
4350 for (i=0;i< 100;i++) {
4354 ar[itemp1] = itemp2;
4370 The more expensive multiplication is changed to a less expensive addition.
4371 \layout Subsubsection
4376 This optimization is done to reduce the overhead of checking loop boundaries
4377 for every iteration.
4378 Some simple loops can be reversed and implemented using a
4379 \begin_inset Quotes eld
4382 decrement and jump if not zero
4383 \begin_inset Quotes erd
4387 SDCC checks for the following criterion to determine if a loop is reversible
4388 (note: more sophisticated compilers use data-dependency analysis to make
4389 this determination, SDCC uses a more simple minded analysis).
4392 The 'for' loop is of the form
4398 for (<symbol> = <expression> ; <sym> [< | <=] <expression> ; [<sym>++ |
4408 The <for body> does not contain
4409 \begin_inset Quotes eld
4413 \begin_inset Quotes erd
4417 \begin_inset Quotes erd
4423 All goto's are contained within the loop.
4426 No function calls within the loop.
4429 The loop control variable <sym> is not assigned any value within the loop
4432 The loop control variable does NOT participate in any arithmetic operation
4436 There are NO switch statements in the loop.
4437 \layout Subsubsection
4439 Algebraic Simplifications
4442 SDCC does numerous algebraic simplifications, the following is a small sub-set
4443 of these optimizations.
4449 i = j + 0 ; /* changed to */ i = j;
4451 i /= 2; /* changed to */ i >>= 1;
4453 i = j - j ; /* changed to */ i = 0;
4455 i = j / 1 ; /* changed to */ i = j;
4461 Note the subexpressions given above are generally introduced by macro expansions
4462 or as a result of copy/constant propagation.
4463 \layout Subsubsection
4468 SDCC changes switch statements to jump tables when the following conditions
4473 The case labels are in numerical sequence, the labels need not be in order,
4474 and the starting number need not be one or zero.
4480 switch(i) {\SpecialChar ~
4587 Both the above switch statements will be implemented using a jump-table.
4590 The number of case labels is at least three, since it takes two conditional
4591 statements to handle the boundary conditions.
4594 The number of case labels is less than 84, since each label takes 3 bytes
4595 and a jump-table can be utmost 256 bytes long.
4599 Switch statements which have gaps in the numeric sequence or those that
4600 have more that 84 case labels can be split into more than one switch statement
4601 for efficient code generation, e.g.:
4639 If the above switch statement is broken down into two switch statements
4673 case 9: \SpecialChar ~
4683 case 12:\SpecialChar ~
4693 then both the switch statements will be implemented using jump-tables whereas
4694 the unmodified switch statement will not be.
4695 \layout Subsubsection
4697 Bit-shifting Operations.
4700 Bit shifting is one of the most frequently used operation in embedded programmin
4702 SDCC tries to implement bit-shift operations in the most efficient way
4722 generates the following code:
4740 In general SDCC will never setup a loop if the shift count is known.
4780 Note that SDCC stores numbers in little-endian format (i.e.
4781 lowest order first).
4782 \layout Subsubsection
4787 A special case of the bit-shift operation is bit rotation, SDCC recognizes
4788 the following expression to be a left bit-rotation:
4799 i = ((i << 1) | (i >> 7));
4807 will generate the following code:
4823 SDCC uses pattern matching on the parse tree to determine this operation.Variatio
4824 ns of this case will also be recognized as bit-rotation, i.e.:
4830 i = ((i >> 7) | (i << 1)); /* left-bit rotation */
4831 \layout Subsubsection
4836 It is frequently required to obtain the highest order bit of an integral
4837 type (long, int, short or char types).
4838 SDCC recognizes the following expression to yield the highest order bit
4839 and generates optimized code for it, e.g.:
4860 hob = (gint >> 15) & 1;
4873 will generate the following code:
4912 000A E5*01\SpecialChar ~
4940 000C 33\SpecialChar ~
4971 000D E4\SpecialChar ~
5002 000E 13\SpecialChar ~
5033 000F F5*02\SpecialChar ~
5063 Variations of this case however will
5068 It is a standard C expression, so I heartily recommend this be the only
5069 way to get the highest order bit, (it is portable).
5070 Of course it will be recognized even if it is embedded in other expressions,
5077 xyz = gint + ((gint >> 15) & 1);
5083 will still be recognized.
5084 \layout Subsubsection
5089 The compiler uses a rule based, pattern matching and re-writing mechanism
5090 for peep-hole optimization.
5095 a peep-hole optimizer by Christopher W.
5096 Fraser (cwfraser@microsoft.com).
5097 A default set of rules are compiled into the compiler, additional rules
5098 may be added with the
5100 --peep-file <filename>
5103 The rule language is best illustrated with examples.
5131 The above rule will change the following assembly sequence:
5161 Note: All occurrences of a
5165 (pattern variable) must denote the same string.
5166 With the above rule, the assembly sequence:
5184 will remain unmodified.
5188 Other special case optimizations may be added by the user (via
5194 some variants of the 8051 MCU allow only
5203 The following two rules will change all
5225 replace { lcall %1 } by { acall %1 }
5227 replace { ljmp %1 } by { ajmp %1 }
5235 inline-assembler code
5237 is also passed through the peep hole optimizer, thus the peephole optimizer
5238 can also be used as an assembly level macro expander.
5239 The rules themselves are MCU dependent whereas the rule language infra-structur
5240 e is MCU independent.
5241 Peephole optimization rules for other MCU can be easily programmed using
5246 The syntax for a rule is as follows:
5252 rule := replace [ restart ] '{' <assembly sequence> '
5290 <assembly sequence> '
5308 '}' [if <functionName> ] '
5316 <assembly sequence> := assembly instruction (each instruction including
5317 labels must be on a separate line).
5321 The optimizer will apply to the rules one by one from the top in the sequence
5322 of their appearance, it will terminate when all rules are exhausted.
5323 If the 'restart' option is specified, then the optimizer will start matching
5324 the rules again from the top, this option for a rule is expensive (performance)
5325 , it is intended to be used in situations where a transformation will trigger
5326 the same rule again.
5327 An example of this (not a good one, it has side effects) is the following
5354 Note that the replace pattern cannot be a blank, but can be a comment line.
5355 Without the 'restart' option only the inner most 'pop' 'push' pair would
5356 be eliminated, i.e.:
5408 the restart option the rule will be applied again to the resulting code
5409 and then all the pop-push pairs will be eliminated to yield:
5427 A conditional function can be attached to a rule.
5428 Attaching rules are somewhat more involved, let me illustrate this with
5459 The optimizer does a look-up of a function name table defined in function
5464 in the source file SDCCpeeph.c, with the name
5469 If it finds a corresponding entry the function is called.
5470 Note there can be no parameters specified for these functions, in this
5475 is crucial, since the function
5479 expects to find the label in that particular variable (the hash table containin
5480 g the variable bindings is passed as a parameter).
5481 If you want to code more such functions, take a close look at the function
5482 labelInRange and the calling mechanism in source file SDCCpeeph.c.
5483 I know this whole thing is a little kludgey, but maybe some day we will
5484 have some better means.
5485 If you are looking at this file, you will also see the default rules that
5486 are compiled into the compiler, you can add your own rules in the default
5487 set there if you get tired of specifying the --peep-file option.
5493 SDCC supports the following #pragma directives.
5494 This directives are applicable only at a function level.
5497 SAVE - this will save all the current options.
5500 RESTORE - will restore the saved options from the last save.
5501 Note that SAVES & RESTOREs cannot be nested.
5502 SDCC uses the same buffer to save the options each time a SAVE is called.
5505 NOGCSE - will stop global subexpression elimination.
5508 NOINDUCTION - will stop loop induction optimizations.
5511 NOJTBOUND - will not generate code for boundary value checking, when switch
5512 statements are turned into jump-tables.
5515 NOOVERLAY - the compiler will not overlay the parameters and local variables
5519 NOLOOPREVERSE - Will not do loop reversal optimization
5522 EXCLUDE NONE | {acc[,b[,dpl[,dph]]] - The exclude pragma disables generation
5523 of pair of push/pop instruction in ISR function (using interrupt keyword).
5524 The directive should be placed immediately before the ISR function definition
5525 and it affects ALL ISR functions following it.
5526 To enable the normal register saving for ISR functions use #pragma\SpecialChar ~
5527 EXCLUDE\SpecialChar ~
5531 CALLEE-SAVES function1[,function2[,function3...]] - The compiler by default
5532 uses a caller saves convention for register saving across function calls,
5533 however this can cause unneccessary register pushing & popping when calling
5534 small functions from larger functions.
5535 This option can be used to switch the register saving convention for the
5536 function names specified.
5537 The compiler will not save registers when calling these functions, extra
5538 code will be generated at the entry & exit for these functions to save
5539 & restore the registers used by these functions, this can SUBSTANTIALLY
5540 reduce code & improve run time performance of the generated code.
5541 In future the compiler (with interprocedural analysis) will be able to
5542 determine the appropriate scheme to use for each function call.
5543 If --callee-saves command line option is used, the function names specified
5544 in #pragma\SpecialChar ~
5545 CALLEE-SAVES is appended to the list of functions specified inthe
5549 The pragma's are intended to be used to turn-off certain optimizations which
5550 might cause the compiler to generate extra stack / data space to store
5551 compiler generated temporary variables.
5552 This usually happens in large functions.
5553 Pragma directives should be used as shown in the following example, they
5554 are used to control options & optimizations for a given function; pragmas
5555 should be placed before and/or after a function, placing pragma's inside
5556 a function body could have unpredictable results.
5562 #pragma SAVE /* save the current settings */
5564 #pragma NOGCSE /* turnoff global subexpression elimination */
5566 #pragma NOINDUCTION /* turn off induction optimizations */
5588 #pragma RESTORE /* turn the optimizations back on */
5594 The compiler will generate a warning message when extra space is allocated.
5595 It is strongly recommended that the SAVE and RESTORE pragma's be used when
5596 changing options for a function.
5601 <pending: this is messy and incomplete>
5606 The following library routines are provided for your convenience.
5609 stdio.h - Contains the following functions printf & sprintf these routines
5610 are developed by Martijn van Balen <balen@natlab.research.philips.com>.
5614 %[flags][width][b|B|l|L]type
5627 flags: -\SpecialChar ~
5634 left justify output in specified field width
5659 prefix output with +/- sign if output is signed type
5680 prefix output with a blank if it's a signed positive value
5691 width:\SpecialChar ~
5700 specifies minimum number of characters outputted for numbers
5755 - For numbers, spaces are added on the left when needed.
5785 If width starts with a zero character, zeroes and used
5842 - For strings, spaces are are added on the left or right (when
5871 flag '-' is used) when needed.
5921 byte argument (used by d, u, o, x, X)
5943 long argument (used by d, u, o, x, X)
5987 unsigned decimal number
6012 unsigned octal number
6037 unsigned hexadecimal number (0-9, a-f)
6062 unsigned hexadecimal number (0-9, A-F)
6112 string (generic pointer)
6137 generic pointer (I:data/idata, C:code, X:xdata, P:paged)
6162 float (still to be implemented)
6165 Also contains a very simple version of printf (printf_small).
6166 This simplified version of printf supports only the following formats.
6169 format\SpecialChar ~
6174 output\SpecialChar ~
6190 decimal \SpecialChar ~
6205 decimal\SpecialChar ~
6222 decimal\SpecialChar ~
6239 hexadecimal\SpecialChar ~
6252 hexadecimal\SpecialChar ~
6265 hexadecimal\SpecialChar ~
6337 character\SpecialChar ~
6353 character\SpecialChar ~
6361 The routine is very stack intesive, --stack-after-data parameter should
6362 be used when using this routine, the routine also takes about 1K of code
6364 It also expects an external function named putchar(char) to be present
6365 (this can be changed).
6366 When using the %s format the string / pointer should be cast to a generic
6372 \begin_inset Quotes eld
6375 my str %s, my int %d
6378 \begin_inset Quotes erd
6381 ,(char _generic *)mystr,myint);
6384 stdarg.h - contains definition for the following macros to be used for variable
6385 parameter list, note that a function can have a variable parameter list
6386 if and only if it is 'reentrant'
6390 va_list, va_start, va_arg, va_end.
6394 setjmp.h - contains defintion for ANSI setjmp & longjmp routines.
6395 Note in this case setjmp & longjmp can be used between functions executing
6396 within the same register bank, if long jmp is executed from a function
6397 that is using a different register bank from the function issuing the setjmp
6398 function, the results may be unpredictable.
6399 The jump buffer requires 3 bytes of data (the stack pointer & a 16 byte
6400 return address), and can be placed in any address space.
6403 stdlib.h - contains the following functions.
6411 string.h - contains the following functions.
6415 strcpy, strncpy, strcat, strncat, strcmp, strncmp, strchr, strrchr, strspn,
6416 strcspn, strpbrk, strstr, strlen, strtok, memcpy, memcmp, memset.
6420 ctype.h - contains the following routines.
6424 iscntrl, isdigit, isgraph, islower, isupper, isprint, ispunct, isspace,
6425 isxdigit, isalnum, isalpha.
6429 malloc.h - The malloc routines are developed by Dmitry S.
6430 Obukhov (dso@usa.net).
6431 These routines will allocate memory from the external ram.
6432 Here is a description on how to use them (as described by the author).
6446 #define DYNAMIC_MEMORY_SIZE 0x2000
6467 unsigned char xdata dynamic_memory_pool[DYNAMIC_MEMORY_SIZE];
6477 unsigned char xdata * current_buffer;
6538 init_dynamic_memory(dynamic_memory_pool,DYNAMIC_MEMORY_SIZE);
6552 //Now it's possible to use malloc.
6582 current_buffer = malloc(0x100);
6592 serial.h - Serial IO routines are also developed by Dmitry S.
6593 Obukhov (dso@usa.net).
6594 These routines are interrupt driven with a 256 byte circular buffer, they
6595 also expect external ram to be present.
6596 Please see documentation in file SDCCDIR/sdcc51lib/serial.c.
6597 Note the header file
6598 \begin_inset Quotes eld
6602 \begin_inset Quotes erd
6605 MUST be included in the file containing the 'main' function.
6608 ser.h - Alternate serial routine provided by Wolfgang Esslinger <wolfgang@WiredMi
6609 nds.com> these routines are more compact and faster.
6610 Please see documentation in file SDCCDIR/sdcc51lib/ser.c
6613 ser_ir.h - Another alternate set of serial routines provided by Josef Wolf
6614 <jw@raven.inka.de>, these routines do not use the external ram.
6617 reg51.h - contains register definitions for a standard 8051
6620 float.h - contains min, max and other floating point related stuff.
6623 All library routines are compiled as --model-small, they are all non-reentrant,
6624 if you plan to use the large model or want to make these routines reentrant,
6625 then they will have to be recompiled with the appropriate compiler option.
6628 Have not had time to do the more involved routines like printf, will get
6632 Interfacing with Assembly Routines
6633 \layout Subsubsection
6635 Global Registers used for Parameter Passing
6638 The compiler always uses the global registers
6646 to pass the first parameter to a routine.
6647 The second parameter onwards is either allocated on the stack (for reentrant
6648 routines or if --stack-auto is used) or in the internal / external ram
6649 (depending on the memory model).
6651 \layout Subsubsection
6653 Assembler Routine(non-reentrant)
6656 In the following example the function cfunc calls an assembler routine asm_func,
6657 which takes two parameters.
6663 extern int asm_func(unsigned char, unsigned char);
6667 int c_func (unsigned char i, unsigned char j)
6675 return asm_func(i,j);
6689 return c_func(10,9);
6697 The corresponding assembler function is:
6703 .globl _asm_func_PARM_2
6767 add a,_asm_func_PARM_2
6803 Note here that the return values are placed in 'dpl' - One byte return value,
6804 'dpl' LSB & 'dph' MSB for two byte values.
6805 'dpl', 'dph' and 'b' for three byte values (generic pointers) and 'dpl','dph','
6806 b' & 'acc' for four byte values.
6809 The parameter naming convention is _<function_name>_PARM_<n>, where n is
6810 the parameter number starting from 1, and counting from the left.
6811 The first parameter is passed in
6812 \begin_inset Quotes eld
6816 \begin_inset Quotes erd
6819 for One bye parameter,
6820 \begin_inset Quotes eld
6824 \begin_inset Quotes erd
6828 \begin_inset Quotes eld
6832 \begin_inset Quotes erd
6836 \begin_inset Quotes eld
6840 \begin_inset Quotes erd
6843 for four bytes, the varible name for the second parameter will be _<function_na
6848 Assemble the assembler routine with the following command:
6855 asx8051 -losg asmfunc.asm
6862 Then compile and link the assembler routine to the C source file with the
6870 sdcc cfunc.c asmfunc.rel
6871 \layout Subsubsection
6873 Assembler Routine(reentrant)
6876 In this case the second parameter onwards will be passed on the stack, the
6877 parameters are pushed from right to left i.e.
6878 after the call the left most parameter will be on the top of the stack.
6885 extern int asm_func(unsigned char, unsigned char);
6889 int c_func (unsigned char i, unsigned char j) reentrant
6897 return asm_func(i,j);
6911 return c_func(10,9);
6919 The corresponding assembler routine is:
7029 The compiling and linking procedure remains the same, however note the extra
7030 entry & exit linkage required for the assembler code, _bp is the stack
7031 frame pointer and is used to compute the offset into the stack for parameters
7032 and local variables.
7038 The external stack is located at the start of the external ram segment,
7039 and is 256 bytes in size.
7040 When --xstack option is used to compile the program, the parameters and
7041 local variables of all reentrant functions are allocated in this area.
7042 This option is provided for programs with large stack space requirements.
7043 When used with the --stack-auto option, all parameters and local variables
7044 are allocated on the external stack (note support libraries will need to
7045 be recompiled with the same options).
7048 The compiler outputs the higher order address byte of the external ram segment
7049 into PORT P2, therefore when using the External Stack option, this port
7050 MAY NOT be used by the application program.
7056 Deviations from the compliancy.
7059 functions are not always reentrant.
7062 structures cannot be assigned values directly, cannot be passed as function
7063 parameters or assigned to each other and cannot be a return value from
7090 s1 = s2 ; /* is invalid in SDCC although allowed in ANSI */
7101 struct s foo1 (struct s parms) /* is invalid in SDCC although allowed in
7123 return rets;/* is invalid in SDCC although allowed in ANSI */
7128 'long long' (64 bit integers) not supported.
7131 'double' precision floating point not supported.
7134 No support for setjmp and longjmp (for now).
7137 Old K&R style function declarations are NOT allowed.
7143 foo(i,j) /* this old style of function declarations */
7145 int i,j; /* are valid in ANSI but not valid in SDCC */
7159 functions declared as pointers must be dereferenced during the call.
7170 /* has to be called like this */
7172 (*foo)(); /* ansi standard allows calls to be made like 'foo()' */
7175 Cyclomatic Complexity
7178 Cyclomatic complexity of a function is defined as the number of independent
7179 paths the program can take during execution of the function.
7180 This is an important number since it defines the number test cases you
7181 have to generate to validate the function.
7182 The accepted industry standard for complexity number is 10, if the cyclomatic
7183 complexity reported by SDCC exceeds 10 you should think about simplification
7184 of the function logic.
7185 Note that the complexity level is not related to the number of lines of
7187 Large functions can have low complexity, and small functions can have large
7193 SDCC uses the following formula to compute the complexity:
7198 complexity = (number of edges in control flow graph) - (number of nodes
7199 in control flow graph) + 2;
7203 Having said that the industry standard is 10, you should be aware that in
7204 some cases it be may unavoidable to have a complexity level of less than
7206 For example if you have switch statement with more than 10 case labels,
7207 each case label adds one to the complexity level.
7208 The complexity level is by no means an absolute measure of the algorithmic
7209 complexity of the function, it does however provide a good starting point
7210 for which functions you might look at for further optimization.
7216 Here are a few guidelines that will help the compiler generate more efficient
7217 code, some of the tips are specific to this compiler others are generally
7218 good programming practice.
7221 Use the smallest data type to represent your data-value.
7222 If it is known in advance that the value is going to be less than 256 then
7223 use a 'char' instead of a 'short' or 'int'.
7226 Use unsigned when it is known in advance that the value is not going to
7228 This helps especially if you are doing division or multiplication.
7231 NEVER jump into a LOOP.
7234 Declare the variables to be local whenever possible, especially loop control
7235 variables (induction).
7238 Since the compiler does not do implicit integral promotion, the programmer
7239 should do an explicit cast when integral promotion is required.
7242 Reducing the size of division, multiplication & modulus operations can reduce
7243 code size substantially.
7244 Take the following code for example.
7250 foobar(unsigned int p1, unsigned char ch)
7254 unsigned char ch1 = p1 % ch ;
7265 For the modulus operation the variable ch will be promoted to unsigned int
7266 first then the modulus operation will be performed (this will lead to a
7267 call to support routine _muduint()), and the result will be casted to an
7269 If the code is changed to
7275 foobar(unsigned int p1, unsigned char ch)
7279 unsigned char ch1 = (unsigned char)p1 % ch ;
7290 It would substantially reduce the code generated (future versions of the
7291 compiler will be smart enough to detect such optimization oppurtunities).
7294 Notes on MCS51 memory layout
7297 The 8051 family of micro controller have a minimum of 128 bytes of internal
7298 memory which is structured as follows
7302 - Bytes 00-1F - 32 bytes to hold up to 4 banks of the registers R7 to R7
7305 - Bytes 20-2F - 16 bytes to hold 128 bit variables and
7307 - Bytes 30-7F - 60 bytes for general purpose use.
7311 Normally the SDCC compiler will only utilise the first bank of registers,
7312 but it is possible to specify that other banks of registers should be used
7313 in interrupt routines.
7314 By default, the compiler will place the stack after the last bank of used
7316 if the first 2 banks of registers are used, it will position the base of
7317 the internal stack at address 16 (0X10).
7318 This implies that as the stack grows, it will use up the remaining register
7319 banks, and the 16 bytes used by the 128 bit variables, and 60 bytes for
7320 general purpose use.
7323 By default, the compiler uses the 60 general purpose bytes to hold "near
7325 The compiler/optimiser may also declare some Local Variables in this area
7330 If any of the 128 bit variables are used, or near data is being used then
7331 care needs to be taken to ensure that the stack does not grow so much that
7332 it starts to over write either your bit variables or "near data".
7333 There is no runtime checking to prevent this from happening.
7336 The amount of stack being used is affected by the use of the "internal stack"
7337 to save registers before a subroutine call is made (--stack-auto will declare
7338 parameters and local variables on the stack) and the number of nested subroutin
7342 If you detect that the stack is over writing you data, then the following
7344 --xstack will cause an external stack to be used for saving registers and
7345 (if --stack-auto is being used) storing parameters and local variables.
7346 However this will produce more code which will be slower to execute.
7350 --stack-loc will allow you specify the start of the stack, i.e.
7351 you could start it after any data in the general purpose area.
7352 However this may waste the memory not used by the register banks and if
7353 the size of the "near data" increases, it may creep into the bottom of
7357 --stack-after-data, similar to the --stack-loc, but it automatically places
7358 the stack after the end of the "near data".
7359 Again this could waste any spare register space.
7362 --data-loc allows you to specify the start address of the near data.
7363 This could be used to move the "near data" further away from the stack
7364 giving it more room to grow.
7365 This will only work if no bit variables are being used and the stack can
7366 grow to use the bit variable space.
7374 If you find that the stack is over writing your bit variables or "near data"
7375 then the approach which best utilised the internal memory is to position
7376 the "near data" after the last bank of used registers or, if you use bit
7377 variables, after the last bit variable by using the --data-loc, e.g.
7378 if two register banks are being used and no bit variables, --data-loc 16,
7379 and use the --stack-after-data option.
7382 If bit variables are being used, another method would be to try and squeeze
7383 the data area in the unused register banks if it will fit, and start the
7384 stack after the last bit variable.
7387 Retargetting for other MCUs.
7390 The issues for retargetting the compiler are far too numerous to be covered
7392 What follows is a brief description of each of the seven phases of the
7393 compiler and its MCU dependency.
7396 Parsing the source and building the annotated parse tree.
7397 This phase is largely MCU independent (except for the language extensions).
7398 Syntax & semantic checks are also done in this phase, along with some initial
7399 optimizations like back patching labels and the pattern matching optimizations
7400 like bit-rotation etc.
7403 The second phase involves generating an intermediate code which can be easy
7404 manipulated during the later phases.
7405 This phase is entirely MCU independent.
7406 The intermediate code generation assumes the target machine has unlimited
7407 number of registers, and designates them with the name iTemp.
7408 The compiler can be made to dump a human readable form of the code generated
7409 by using the --dumpraw option.
7412 This phase does the bulk of the standard optimizations and is also MCU independe
7414 This phase can be broken down into several sub-phases:
7418 Break down intermediate code (iCode) into basic blocks.
7420 Do control flow & data flow analysis on the basic blocks.
7422 Do local common subexpression elimination, then global subexpression elimination
7424 Dead code elimination
7428 If loop optimizations caused any changes then do 'global subexpression eliminati
7429 on' and 'dead code elimination' again.
7432 This phase determines the live-ranges; by live range I mean those iTemp
7433 variables defined by the compiler that still survive after all the optimization
7435 Live range analysis is essential for register allocation, since these computati
7436 on determines which of these iTemps will be assigned to registers, and for
7440 Phase five is register allocation.
7441 There are two parts to this process.
7445 The first part I call 'register packing' (for lack of a better term).
7446 In this case several MCU specific expression folding is done to reduce
7451 The second part is more MCU independent and deals with allocating registers
7452 to the remaining live ranges.
7453 A lot of MCU specific code does creep into this phase because of the limited
7454 number of index registers available in the 8051.
7457 The Code generation phase is (unhappily), entirely MCU dependent and very
7458 little (if any at all) of this code can be reused for other MCU.
7459 However the scheme for allocating a homogenized assembler operand for each
7460 iCode operand may be reused.
7463 As mentioned in the optimization section the peep-hole optimizer is rule
7464 based system, which can reprogrammed for other MCUs.
7467 SDCDB - Source Level Debugger
7470 SDCC is distributed with a source level debugger.
7471 The debugger uses a command line interface, the command repertoire of the
7472 debugger has been kept as close to gdb (the GNU debugger) as possible.
7473 The configuration and build process is part of the standard compiler installati
7474 on, which also builds and installs the debugger in the target directory
7475 specified during configuration.
7476 The debugger allows you debug BOTH at the C source and at the ASM source
7480 Compiling for Debugging
7485 debug option must be specified for all files for which debug information
7487 The complier generates a .cdb file for each of these files.
7488 The linker updates the .cdb file with the address information.
7489 This .cdb is used by the debugger.
7492 How the Debugger Works
7495 When the --debug option is specified the compiler generates extra symbol
7496 information some of which are put into the the assembler source and some
7497 are put into the .cdb file, the linker updates the .cdb file with the address
7498 information for the symbols.
7499 The debugger reads the symbolic information generated by the compiler &
7500 the address information generated by the linker.
7501 It uses the SIMULATOR (Daniel's S51) to execute the program, the program
7502 execution is controlled by the debugger.
7503 When a command is issued for the debugger, it translates it into appropriate
7504 commands for the simulator.
7507 Starting the Debugger
7510 The debugger can be started using the following command line.
7511 (Assume the file you are debugging has the file name foo).
7525 The debugger will look for the following files.
7528 foo.c - the source file.
7531 foo.cdb - the debugger symbol information file.
7534 foo.ihx - the intel hex format object file.
7537 Command Line Options.
7540 --directory=<source file directory> this option can used to specify the
7541 directory search list.
7542 The debugger will look into the directory list specified for source, cdb
7544 The items in the directory list must be separated by ':', e.g.
7545 if the source files can be in the directories /home/src1 and /home/src2,
7546 the --directory option should be --directory=/home/src1:/home/src2.
7547 Note there can be no spaces in the option.
7551 -cd <directory> - change to the <directory>.
7554 -fullname - used by GUI front ends.
7557 -cpu <cpu-type> - this argument is passed to the simulator please see the
7558 simulator docs for details.
7561 -X <Clock frequency > this options is passed to the simulator please see
7562 the simulator docs for details.
7565 -s <serial port file> passed to simulator see the simulator docs for details.
7568 -S <serial in,out> passed to simulator see the simulator docs for details.
7574 As mention earlier the command interface for the debugger has been deliberately
7575 kept as close the GNU debugger gdb, as possible.
7576 This will help the integration with existing graphical user interfaces
7577 (like ddd, xxgdb or xemacs) existing for the GNU debugger.
7578 \layout Subsubsection
7580 break [line | file:line | function | file:function]
7583 Set breakpoint at specified line or function:
7592 sdcdb>break foo.c:100
7596 sdcdb>break foo.c:funcfoo
7597 \layout Subsubsection
7599 clear [line | file:line | function | file:function ]
7602 Clear breakpoint at specified line or function:
7611 sdcdb>clear foo.c:100
7615 sdcdb>clear foo.c:funcfoo
7616 \layout Subsubsection
7621 Continue program being debugged, after breakpoint.
7622 \layout Subsubsection
7627 Execute till the end of the current function.
7628 \layout Subsubsection
7633 Delete breakpoint number 'n'.
7634 If used without any option clear ALL user defined break points.
7635 \layout Subsubsection
7637 info [break | stack | frame | registers ]
7640 info break - list all breakpoints
7643 info stack - show the function call stack.
7646 info frame - show information about the current execution frame.
7649 info registers - show content of all registers.
7650 \layout Subsubsection
7655 Step program until it reaches a different source line.
7656 \layout Subsubsection
7661 Step program, proceeding through subroutine calls.
7662 \layout Subsubsection
7667 Start debugged program.
7668 \layout Subsubsection
7673 Print type information of the variable.
7674 \layout Subsubsection
7679 print value of variable.
7680 \layout Subsubsection
7685 load the given file name.
7686 Note this is an alternate method of loading file for debugging.
7687 \layout Subsubsection
7692 print information about current frame.
7693 \layout Subsubsection
7698 Toggle between C source & assembly source.
7699 \layout Subsubsection
7704 Send the string following '!' to the simulator, the simulator response is
7706 Note the debugger does not interpret the command being sent to the simulator,
7707 so if a command like 'go' is sent the debugger can loose its execution
7708 context and may display incorrect values.
7709 \layout Subsubsection
7716 My name is Bobby Brown"
7719 Interfacing with XEmacs.
7722 Two files (in emacs lisp) are provided for the interfacing with XEmacs,
7723 sdcdb.el and sdcdbsrc.el.
7724 These two files can be found in the $(prefix)/bin directory after the installat
7726 These files need to be loaded into XEmacs for the interface to work.
7727 This can be done at XEmacs startup time by inserting the following into
7728 your '.xemacs' file (which can be found in your HOME directory):
7734 (load-file sdcdbsrc.el)
7740 .xemacs is a lisp file so the () around the command is REQUIRED.
7741 The files can also be loaded dynamically while XEmacs is running, set the
7742 environment variable 'EMACSLOADPATH' to the installation bin directory
7743 (<installdir>/bin), then enter the following command ESC-x load-file sdcdbsrc.
7744 To start the interface enter the following command:
7758 You will prompted to enter the file name to be debugged.
7763 The command line options that are passed to the simulator directly are bound
7764 to default values in the file sdcdbsrc.el.
7765 The variables are listed below, these values maybe changed as required.
7768 sdcdbsrc-cpu-type '51
7771 sdcdbsrc-frequency '11059200
7777 The following is a list of key mapping for the debugger interface.
7785 ;; Current Listing ::
7802 binding\SpecialChar ~
7841 -------\SpecialChar ~
7881 sdcdb-next-from-src\SpecialChar ~
7907 sdcdb-back-from-src\SpecialChar ~
7933 sdcdb-cont-from-src\SpecialChar ~
7943 SDCDB continue command
7959 sdcdb-step-from-src\SpecialChar ~
7985 sdcdb-whatis-c-sexp\SpecialChar ~
7995 SDCDB ptypecommand for data at
8059 sdcdbsrc-delete\SpecialChar ~
8073 SDCDB Delete all breakpoints if no arg
8121 given or delete arg (C-u arg x)
8137 sdcdbsrc-frame\SpecialChar ~
8152 SDCDB Display current frame if no arg,
8201 given or display frame arg
8266 sdcdbsrc-goto-sdcdb\SpecialChar ~
8276 Goto the SDCDB output buffer
8292 sdcdb-print-c-sexp\SpecialChar ~
8303 SDCDB print command for data at
8367 sdcdbsrc-goto-sdcdb\SpecialChar ~
8377 Goto the SDCDB output buffer
8393 sdcdbsrc-mode\SpecialChar ~
8409 Toggles Sdcdbsrc mode (turns it off)
8413 ;; C-c C-f\SpecialChar ~
8421 sdcdb-finish-from-src\SpecialChar ~
8429 SDCDB finish command
8433 ;; C-x SPC\SpecialChar ~
8441 sdcdb-break\SpecialChar ~
8459 Set break for line with point
8461 ;; ESC t\SpecialChar ~
8471 sdcdbsrc-mode\SpecialChar ~
8487 Toggle Sdcdbsrc mode
8489 ;; ESC m\SpecialChar ~
8499 sdcdbsrc-srcmode\SpecialChar ~
8523 The Z80 and gbz80 port
8526 SDCC can target both the Zilog Z80 and the Nintendo Gameboy's Z80-like gbz80.
8527 The port is incomplete - long support is incomplete (mul, div and mod are
8528 unimplimented), and both float and bitfield support is missing.
8529 Apart from that the code generated is correct.
8532 As always, the code is the authoritave reference - see z80/ralloc.c and z80/gen.c.
8533 The stack frame is similar to that generated by the IAR Z80 compiler.
8534 IX is used as the base pointer, HL is used as a temporary register, and
8535 BC and DE are available for holding varibles.
8536 IY is currently unusued.
8537 Return values are stored in HL.
8538 One bad side effect of using IX as the base pointer is that a functions
8539 stack frame is limited to 127 bytes - this will be fixed in a later version.
8545 SDCC has grown to be a large project.
8546 The compiler alone (without the preprocessor, assembler and linker) is
8547 about 40,000 lines of code (blank stripped).
8548 The open source nature of this project is a key to its continued growth
8550 You gain the benefit and support of many active software developers and
8552 Is SDCC perfect? No, that's why we need your help.
8553 The developers take pride in fixing reported bugs.
8554 You can help by reporting the bugs and helping other SDCC users.
8555 There are lots of ways to contribute, and we encourage you to take part
8556 in making SDCC a great software package.
8562 Send an email to the mailing list at 'user-sdcc@sdcc.sourceforge.net' or 'devel-sd
8563 cc@sdcc.sourceforge.net'.
8564 Bugs will be fixed ASAP.
8565 When reporting a bug, it is very useful to include a small test program
8566 which reproduces the problem.
8567 If you can isolate the problem by looking at the generated assembly code,
8568 this can be very helpful.
8569 Compiling your program with the --dumpall option can sometimes be useful
8570 in locating optimization problems.
8576 Sandeep Dutta (sandeep.dutta@usa.net) - SDCC, the compiler, MCS51 code generator,
8579 Alan Baldwin (baldwin@shop-pdp.kent.edu) - Initial version of ASXXXX & ASLINK.
8582 John Hartman (jhartman@compuserve.com) - Porting ASXXX & ASLINK for 8051
8585 Obukhov (dso@usa.net) - malloc & serial i/o routines.
8588 Daniel Drotos (drdani@mazsola.iit.uni-miskolc.hu) - for his Freeware simulator
8590 Malini Dutta(malini_dutta@hotmail.com) - my wife for her patience and support.
8592 Unknown - for the GNU C - preprocessor.
8594 Michael Hope - The Z80 and Z80GB port, 186 development
8596 Kevin Vigor - The DS390 port.
8598 Johan Knol - Lots of fixes and enhancements, DS390/TINI libs.
8600 Scott Datallo - The PIC port.
8606 Thanks to all the other volunteer developers who have helped with coding,
8607 testing, web-page creation, distribution sets, etc.
8608 You know who you are :-)
8615 This document was initially written by Sandeep Dutta
8618 All product names mentioned herein may be trademarks of their respective
8624 \begin_inset LatexCommand \printindex{}