c tools manual

106
a ADSP-2100 Family C Tools Manual

Upload: vbook

Post on 11-Apr-2015

346 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: C Tools manual

3Contents

2 – 1

a

ADSP-2100 Family

C Tools Manual

Page 2: C Tools manual

3 Contents

2 – 2

ADSP-2100 FamilyC Tools Manual

© 1994 Analog Devices, Inc.ALL RIGHTS RESERVED

PRODUCT AND DOCUMENTATION NOTICE: Analog Devices reserves the right to change thisproduct and its documentation without prior notice.

Information furnished by Analog Devices is believed to be accurate and reliable.However, no responsibility is assumed by Analog Devices for its use, nor for any infringement ofpatents, or other rights of third parties which may result from its use. No license is granted by implicationor otherwise under the patent rights of Analog Devices.

Permission is granted to copy and distribute modified versions of this manual under the conditions forverbatim copying, provided also that the sections entitled “GNU General Public License” and “Boycott” areincluded exactly as in the original, and provided that the entire resulting derived work is distributed under theterms of a permission notice identical to this one.

Permission is granted to copy and distribute translations of this manual into another language, under theabove conditions for modified versions, except that the sections entitled “GNU General Public License” and“Boycott”, and this permission notice, may be included in translations approved by the Free SoftwareFoundation instead of in the original English.

PRINTED IN U.S.A.

Printing HistorySECOND EDITION 11/94

For marketing information or Applications Engineering assistance, contact your localAnalog Devices sales office or authorized distributor.If you have suggestions for how the ADSP-2100 Family development tools ordocumentation can better serve your needs, or you need Applications Engineeringassistance from Analog Devices, please contact:

Analog Devices, Inc.DSP Applications Engineering

Page 3: C Tools manual

3Contents

2 – 3

One Technology WayNorwood, MA 02062-9106Tel: (617) 461-3672Fax: (617) 461-3010e-mail: [email protected]

Or log in to the DSP Bulletin Board System:Telephone number (617) 461-4258300, 1200, 2400, 9600 baud, no parity, 8 bits data, 1 stop bit

For additional marketing information, call (617) 461-3881 in Norwood MA, USA.

LiteratureADSP-2100 FAMILY MANUALS

ADSP-2100 Family User’s Manual (Prentice Hall)Complete description of processor architectures and system interfaces.

ADSP-2100 Family Assembler Tools & Simulator ManualADSP-2100 Family C Tools ManualADSP-2100 Family C Runtime Library ManualProgrammer’s references.

ADSP-2100 Family EZ Tools ManualUser’s manuals for in-circuit emulators and demonstration boards.

APPLICATIONS INFORMATION

Digital Signal Processing Applications Using the ADSP-2100 Family,Volume 1 (Prentice Hall)Topics include arithmetic, filters, FFTs, linear predictive coding, modemalgorithms, graphics, pulse-code modulation, multirate filters, DTMF,multiprocessing, host interface and sonar.

Digital Signal Processing Applications Using the ADSP-2100 Family,Volume 2 (Prentice Hall)

Page 4: C Tools manual

3 Contents

2 – 4

Topics include modems, linear predictive coding, GSM codec, sub-bandADPCM, speech recognition, discrete cosine transform, digital tonedetection, digital control system design, IIR biquad filters, software uartand hardware interfacing.

SPECIFICATION INFORMATION

ADSP-2100/ADSP2100A Data SheetADSP-21xx Data SheetADSP-21msp50A/55A/56A Data SheetADSP-21msp58/59 Preliminary Data SheetADSP-2171/72/73 Data SheetADSP-2181 Preliminary Data Sheet

Page 5: C Tools manual

3Contents

2 – 5

2

2 – 1

Contents

v

CHAPTER 1 INTRODUCTION

1.1 OVERVIEW .................................................................................................... 1–11.2 ORGANIZATION OF THIS MANUAL ............................................................. 1–21.3 MANUAL NOTATIONAL CONVENTIONS ..................................................... 1–21.4 RELEASE SPECIFIC INFORMATION ........................................................... 1–31.5 REFERENCE MATERIALS ............................................................................ 1–31.6 LICENSE INFORMATION .............................................................................. 1–4

CHAPTER 2 C COMPILER

2.1 OVERVIEW .................................................................................................... 2–12.2 STARTING THE C COMPILER ...................................................................... 2–22.3 G21 COMMAND LINE SWITCHES ................................................................ 2–42.4 G21 C LANGUAGE EXTENSIONS .............................................................. 2–152.4.1 Dual Memory Support Keywords (pm dm)........................................... 2–172.4.1.1 Memory Keywords & Assignments / Type Conversions ............. 2–192.4.1.2 Memory Keywords & Function Declarations / Pointers ............... 2–202.4.1.3 Memory Keywords & Function Arguments .................................. 2–212.4.1.4 Memory Keywords & Macros ...................................................... 2–212.4.2 Type Reference Support Keyword (typeof) ......................................... 2–222.4.3 Inline Function Support Keyword (inline) ............................................. 2–232.4.4 Inline Assembly Language Support Keyword (asm) ............................ 2–242.4.4.1 Assembly Construct Template .................................................... 2–252.4.4.2 Assembly Construct Operand Description .................................. 2–272.4.4.3 Assembly Constructs With Multiple Instructions ......................... 2–292.4.4.4 Assembly Construct Reordering & Optimization ......................... 2–292.4.4.5 Assembly Constructs With Input & Output Operands ................. 2–302.4.4.6 Assembly Constructs & Macros .................................................. 2–31

Page 6: C Tools manual

3 Contents

2 – 6

2.4.4.7 Assembly Constructs & C/Assembly Symbol Association .......... 2–322.4.5 Support For Compound Statements Within Expressions .................... 2–332.4.6 Non-Constant Initializer Support .......................................................... 2–342.4.7 Indexed Initializer Support ................................................................... 2–342.4.8 Aggregate Assignment Support ........................................................... 2–362.5 USING THE C PREPROCESSOR ............................................................... 2–372.5.1 Starting The C Preprocessor ............................................................... 2–372.5.2 C Preprocessor Command Line Switches ........................................... 2–392.5.3 C Preprocessor Commands ................................................................ 2–392.5.4 C Preprocessor Macro Support ........................................................... 2–452.5.4.1 Predefined Macros ...................................................................... 2–452.5.4.2 Header Files ................................................................................ 2–472.5.4.3 Writing Macros ............................................................................ 2–482.5.4.4 Compound Statements As Macros ............................................. 2–48

CHAPTER 3 ASSEMBLY LANGUAGE INTERFACING

3.1 OVERVIEW .................................................................................................... 3–13.2 C RUNTIME ENVIRONMENT ........................................................................ 3–23.2.1 G21 Reserved Registers ....................................................................... 3–33.2.2 User Reserved Registers ....................................................................... 3–33.2.3 Scratch Registers .................................................................................. 3–43.2.4 C Runtime Stack Registers .................................................................... 3–43.2.5 C Runtime Stack .................................................................................... 3–53.2.6 Arguments & Return Transfer ................................................................ 3–63.2.7 Function Call Return Address ................................................................ 3–63.2.8 Data Storage Formats ........................................................................... 3–83.3 C RUNTIME HEADER.................................................................................... 3–83.4 C / ASSEMBLY INTERFACE SUPPORT MACROS .................................... 3–103.5 C / ASSEMBLY INTERFACE CONVENTIONS ............................................ 3–143.6 C / ASSEMBLY INTERFACE PROGRAMMING EXAMPLES ...................... 3–153.6.1 Inline Assembly Language (asm) Interfacing Example ........................ 3–163.6.2 External Assembly Subroutine Interfacing Example ............................ 3–163.6.3 Simple Assembly Routines Example ................................................... 3–213.6.4 Assembly Routines With Parameters Example ................................... 3–223.6.5 Assembly Routines With Parameters & Return Values Example ........ 3–233.6.6 Non-Leaf Assembly Routines Example ............................................... 3–24

vi

Page 7: C Tools manual

3Contents

2 – 7vii

CHAPTER 4 C SOURCE DEBUGGER

4.1 OVERVIEW .................................................................................................... 4–14.2 GETTING STARTED — CBUG USER INTERFACE ..................................... 4–24.2.1 Starting CBUG ....................................................................................... 4–24.2.2 The CBUG Menu & Pushbuttons ........................................................... 4–24.2.3 Execution.. ............................................................................................. 4–44.2.3.1 Step ............................................................................................... 4–54.2.3.2 Next ............................................................................................... 4–64.2.3.3 Step ‘n’ times ................................................................................ 4–64.2.3.4 Next ‘n’ times ................................................................................ 4–74.2.3.5 Continue ........................................................................................ 4–74.2.3.6 Go Until ......................................................................................... 4–74.2.3.7 Finish ............................................................................................ 4–84.2.3.8 Restart .......................................................................................... 4–84.2.4 Breaks.. .................................................................................................. 4–94.2.4.1 Break ............................................................................................. 4–94.2.4.2 Delete ............................................................................................ 4–94.2.4.3 List .............................................................................................. 4–104.2.5 Data.. ................................................................................................... 4–104.2.5.1 Print ............................................................................................. 4–104.2.5.2 Assign ......................................................................................... 4–104.2.5.3 Display ........................................................................................ 4–114.2.6 Symbols.. ............................................................................................. 4–114.2.6.1 Globals ........................................................................................ 4–114.2.6.2 Locals .......................................................................................... 4–124.2.6.3 Functions .................................................................................... 4–124.3 PROGRAM PREPARATION ........................................................................ 4–124.3.1 C Program Requirements .................................................................... 4–124.3.2 Translation Process Requirements ...................................................... 4–134.4 SETUP & C DEBUGGING............................................................................ 4–134.4.1 C Stepping vs. Assembly Single-Stepping .......................................... 4–134.4.2 Normal Execution Stops ...................................................................... 4–134.4.3 Abnormal Execution Stops .................................................................. 4–144.4.4 C Breakpoints vs. Assembly Breakpoints ............................................ 4–14

APPENDIX A FSF GENERAL PUBLIC LICENSE

INDEX

Page 8: C Tools manual

3 Contents

2 – 8viii

FIGURES

Figure 2.1 Translation Process Overview ................................................................. 2–1

Figure 3.1 Assembly Language Interfacing Overview............................................... 3–1Figure 3.2 Floating-Point Number Storage Format ................................................... 3–9

Figure 4.1 C Source Level Debugger (CBUG) Menu Tree ....................................... 4–4

LISTINGS

Listing 2.1 Dual Memory Support Keyword Variable Syntax Examples .................. 2–18Listing 2.2 Dual Memory Support Keyword typedef & struct Syntax Examples ...... 2–19Listing 2.3 Legal Dual Memory Space Variable Assignment Example.................... 2–19Listing 2.4 Illegal Dual Memory Space Type Cast Example .................................... 2–20Listing 2.5 Dual Memory Support Keyword Function Declaration ........................... 2–20Listing 2.6 Illegal Dual Memory Support Keywords & Calls .................................... 2–21Listing 2.7 Dual Memory Support Keywords & Macros ........................................... 2–22Listing 2.8 typeof() Argument Written With An Expression Example ...................... 2–22Listing 2.9 typeof() Argument Written With A Type Example .................................. 2–22Listing 2.10 typeof() Argument Written With A Pointer Examples ............................. 2–23Listing 2.11 typeof() Argument Written With Macros Example .................................. 2–23Listing 2.12 Inline Function Definition Example ......................................................... 2–23Listing 2.13 Compound Expression Example ............................................................ 2–33Listing 2.14 Compound Expression With Macros Example ....................................... 2–34Listing 2.15 Initializer With Runtime Varying Elements Example .............................. 2–34Listing 2.16 Standard C Array Initializer Example ..................................................... 2–35Listing 2.17 G21 C Array Initializer With Labeled Elements Example ....................... 2–35Listing 2.18 Standard C Array Initializer Example ..................................................... 2–35Listing 2.19 G21 C Array Initializer With Labeled Elements Example ....................... 2–35Listing 2.20 G21 C Array Initializer With enum Type Indices Example ..................... 2–35Listing 2.21 Standard C struct Initializer Example ..................................................... 2–35Listing 2.22 G21 C struct Initializer With Labeled Elements Example ....................... 2–36Listing 2.23 Standard C struct Example .................................................................... 2–36Listing 2.24 G21 C Constructor struct Example ........................................................ 2–36Listing 2.25 G21 C Constructor Array Example ........................................................ 2–36Listing 2.26 # Preprocessor Directive Example Input ................................................ 2–44Listing 2.27 # Preprocessor Directive Example Output ............................................. 2–44Listing 2.28 ## Preprocessor Directive Example Input .............................................. 2–45Listing 2.29 ## Preprocessor Directive Example Output ........................................... 2–45

Page 9: C Tools manual

3Contents

2 – 9viv

Listing 3.1 Assembly Language Subroutine Return Address .................................... 3–7Listing 3.2 The ADSP-2101 Runtime Header File – 2101_hdr.dsp ........................... 3–8Listing 3.3 asm_sprt.h – C / Assembly Interface Support Macros ................. 3–12, 3–13Listing 3.4 Inline Assembly Language ( asm() ) Interfacing Example ..................... 3–16Listing 3.5 Main C Module ....................................................................................... 3–17Listing 3.6 Equivalent C Code For Assembly Language Module sum_ .................. 3–17Listing 3.7 Assembly Language Module sum_ ........................................................ 3–18Listing 3.8 Compiled Version Of Main C Module (main.dsp) ................................... 3–21Listing 3.9 Simple Assembly Routines Example – delay_ ............................. 3–21, 3–22Listing 3.10 Assembly Routines With Parameters Example – add5_ ............. 3–22, 3–23Listing 3.11 Assembly Routines With Parameters & Return Values Example .......... 3–23Listing 3.12 Non-Leaf Assembly Routines Example – rms_ ........................... 3–24, 3–25Listing 3.13 Non-Leaf Assembly Routines Example – calladd5_ .............................. 3–25Listing 3.14 Non-Leaf Assembly Routines Example – foo_ ...................................... 3–26

TABLES

Table 2.1 Alphabetical Listing Of G21 Command Line Switches ............................. 2–3Table 2.2 File Extensions & G21 Operations ........................................................... 2–5Table 2.3 G21 Default File Name Extensions .......................................................... 2–5Table 2.4 Search/Place Directories & Environment Variables ................................. 2–6Table 2.5 Examples Of G21 Command Line Switch Positive & Negative Forms .... 2–6Table 2.6 Alphabetical Listing Of G21 C Language Extension Keywords ............. 2–17Table 2.7 Operand Constraints & Constraint Modifiers For asm() Constructs ....... 2–28Table 2.8 Alphabetical Listing Of C Preprocessor Command Line Switches ........ 2–38Table 2.9 Alphabetical Listing Of C Preprocessor Commands .............................. 2–40Table 2.10 Alphabetical Listing Of G21 Predefined Macros .................................... 2–45

Table 3.1 G21 Reserved Registers .......................................................................... 3–3Table 3.2 User Reserved Registers ......................................................................... 3–3Table 3.3 Scratch Registers ..................................................................................... 3–4Table 3.4 Pointer Registers ..................................................................................... 3–4Table 3.5 Parameter & Return Value Transfer Registers ........................................ 3–6Table 3.6 Data Storage Formats .............................................................................. 3–8Table 3.7 C / Assembly Interface Support Macros (From asm_sprt.h) .................. 3–10Table 3.8 Naming Conventions For C / Assembly Symbols .................................. 3–14

Page 10: C Tools manual

3 Contents

2 – 10x

Page 11: C Tools manual

1

1 – 1

Introduction

1.1 OVERVIEWThe ADSP-2100 Family C Tools are tools for developing C languageprograms that run on ADSP-2100 Family Digital Signal Processors (DSP).The tools include:

• G21 C Compiler and C Preprocessor• ADSP-2100 Family C Runtime Library• CBUG™ — C Source Level Debugging Utility

These tools let C programmers develop C programs for the ADSP-2100Family. C programs can be written, compiled and executed withoutextensive knowledge of the ADSP-2100 Family architecture.

The runtime library functions, coded in ADSP-2100 Family assemblylanguage, may be called as functions from your C language program. Thefunctions perform floating-point math, digital signal processing, andstandard C operations.

The C language tools are used with the other ADSP-2100 FamilyDevelopment Software tools. These development tools include the SystemBuilder, Assembler, Linker, and PROM Splitter. The System Buildercreates an architecture description file based on your system’s hardwareconfiguration, while the Assembler, Linker, and PROM Splitter are usedto create executable machine language programs.

The C compiler produces ADSP-2100 Family assembly language code andautomatically runs the Assembler. The Assembler produces object codefiles that must be linked (together with any C Runtime library functionsused) to create an executable program. The PROM Splitter is used toproduce PROM loadable files.

Page 12: C Tools manual

1 Introduction

1 – 2

1.2 ORGANIZATION OF THIS MANUALThis manual provides information on the C compiler and related tools.You will find information distributed as follows:

Chapter 1, IntroductionChapter 1 provides an overview of the manual and references.

Chapter 2, C CompilerChapter 2 provides information on C Compiler and Preprocessoroperations. In this chapter, you will find information on:

• G21 Command Line Switches• G21 C Language Extensions• C Preprocessor Directives

Chapter 3, C/Assembly Language InterfacingChapter 3 provides information on the C Runtime Environment andassembly language interfacing. In this chapter, you will find informationon:

• C/Assembly Language Interface Specification• C/Assembly Language Interface Programming Examples

Chapter 4, C Source Level Debugging UtilityChapter 4 provides a user’s guide for the CBUG™ C Source LevelDebugging Utility. This utility is run from within the ADSP-2100 FamilySimulator.

1.3 MANUAL NOTATIONAL CONVENTIONSThe following notation conventions apply to this manual:

• Source code listings, elements of the C language, variable names andfile names are printed in the courier font.

• A lowercase word highlighted in italics, such as jumplabel, represents auser-defined symbol such as a program label, data variable, orfilename.

• Square brackets, [ ], enclose optional items.

Page 13: C Tools manual

1Introduction

1 – 3

• The term ADSP-2100 refers generically to one or all of the ADSP-2100Family processors.

• G21 conforms to the ANSI standard (X3J11) for the C programminglanguage. Any reference to “standard C” in the documentation is areference to that standard.

1.4 RELEASE SPECIFIC INFORMATIONEach release of the C compiler is shipped with a release note detailing thespecifics of that release. Included is a list of restrictions, workarounds,installation information, and documentation errata. You must return theregistration form included with your compiler to receive informationabout updates.

1.5 REFERENCE MATERIALSAs you develop your application, you may need to refer to other sourcesfor information on programming theory and practice, microprocessorarchitecture, and digital signal processing techniques. This section listssome useful references.

For information on the architecture and system interface of the ADSP-2100Family processors, see:

• ADSP-2100 Family User’s Manual

For information on the ADSP-2100 Family assembly languagedevelopment tools, see:

• ADSP-2100 Family Assembler Tools & Simulator Manual

For information on usage, syntax and semantics of the C language, see:

• Kernighan and Ritchie. The C Programming Language. Second edition.Prentice Hall, 1988.

• Harbison and Steele. C: A Reference Manual. Prentice Hall, 1987.• Plauger and Brodie. Standard C. Microsoft Press, 1989.

For information on digital signal processing theory and application, see:

• Higgins. Digital Signal Processing In VLSI. Prentice Hall, 1990.• Mar, ed. Digital Signal Processing Applications Using the ADSP-2100

Family. Prentice Hall, 1990.

Page 14: C Tools manual

1 Introduction

1 – 4

For a copy of the ANSI standard (X3J11) for the C programming language,contact ANSI:

ANSI1430 BroadwayNew York, NY 10018(212) 642-4900

For information on the GCC compiler from the Free Software Foundation,see the GCC original documentation in machine-readable form on theADSP-2100 Family C Tools release diskettes.

1.6 LICENSE INFORMATIONThe Free Software Foundation General Public License is applicable to the Ccompiler and preprocessor software this manual describes. Thisagreement gives you certain rights, but no warranty. Analog Devices’standard warranty applies to registered owners of ADSP-2100 Family CTools Packages. For the complete text of the agreement, see Appendix A,Free Software Foundation General Public License.

Page 15: C Tools manual

2

2 – 1

C Compiler

2.1 OVERVIEWThe ADSP-2100 Family C Compiler (G21) is a port of the Free SoftwareFoundation C compiler (GCC). G21 controls the operation of othersoftware development tools during the preprocessing, compiling,assembling, and linking process (see note below). When you run G21, thetranslation process can involve the C Preprocessor, C Compiler,Assembler, and/or Linker. Figure 2.1 shows an overview of thetranslation process. For more information on compilation related files, seeTable 2.2.

Note: From this point on, this document refers to the preprocessing,compiling, assembling, and/or linking process as the translation process.

Figure 2.1 Translation Process Overview

Each stage of the translation process can perform the following tasks:

• Produce output that the next stage uses as input• Pass files requiring no processing to the next stage• Combinations of the above

C Compiler

C Preprocessor

Input Files

Assembler

Output Files

Linkerg21

Page 16: C Tools manual

2 C Compiler

2 – 2

2.2 STARTING THE C COMPILERG21 has many start up options. This section shows the command line andall the options. A template for the G21 command line follows:

• sourcefile - This is the name of the file (or files) to bepreprocessed, compiled, assembled, and/or linked. A file name caninclude the drive, directory, file name and file extension. G21 uses thefile extension to determine what operations to perform. Table 2.2 liststhe allowed extensions and matching compiler operations.

• switch and parameter - G21 has many optional switches. Theseselect the operations and modes for the compiler and other tools. Table2.1 lists all the compiler switches, parameters, and syntax (optionalones are shown enclosed in [ ]). For complete descriptions of eachcompiler switch and parameters, see the next section, “Command LineSwitches.”

The G21 program name can be uppercase or lowercase, except in UNIXsystems where it must be lowercase. The following command line, forexample:

g21 source.c -a 21xx.ach -g -Wall -o program.exe

runs G21 with:

g21 sourcefile [ sourcefile …] - switch [ parameter ] [- switch [ parameter ]…]

source.c Selects a C language source file for your program-a 21xx.ach Selects an architecture file describing your DSP system-g Selects debugging information be output for CBUG-Wall Selects a list of compiler warnings-o program.exe Selects a name for the compiled, linked output

Page 17: C Tools manual

2C Compiler

2 – 3

sourcefile [-MD][-a filename ] [-MMD][-ansi] [-nostdinc][-c] [-nostdlib][-D macro [ =definition ]] [-o filename ][-E] [-pedantic]Used only with [-E] are: [-pedantic-errors][-C], [-dD], [-dM], [-dN], [-runhdr filename ][-M], [-MM], [-P] [-save-temps][-fcond-mismatch] [-S][-finline-functions] [-traditional][-fkeep-inline-functions] [-traditional-cpp][-fno-asm] [-U macro ][-fno-builtin] [-v][-fsigned-bitfields] [-w][-fsigned-char] [-W][-fsyntax-only] [-Wall][-funsigned-bitfields] [-Wchar-subscripts][-funsigned-char] [-Wcomment][-fwritable-strings] [-Werror][-g] [-Wformat][-imacros filename ] [-Wimplicit][-I-] [-Wparentheses][-I directory ] [-Wreturn-type][-L directory ] [-Wswitch][-l library-name ] [-Wtrigraphs][-map [ filename ]] [-Wuninitialized][-mno-doloops] [-Wunused][-mreserved= register-list ]

Table 2.1 Alphabetical Listing Of G21 Command Line Switches

Note: G21 switches in Table 2.1 may be used in any order on thecommand line. Items shown in [ ] are optional. Items shown in italics areuser dependant and are described with each switch in the next section,“G21 Command Line Switches.”

Page 18: C Tools manual

2 C Compiler

2 – 4

2.3 G21 COMMAND LINE SWITCHESThis section describes (in alphabetical order) the G21 command lineswitches.

Many G21 switches take a file name as an optional parameter. If you donot provide an output file name, G21 (in most cases) names the file foryou. Table 2.2 lists the type of files, names, and extensions G21 appends tooutput files. Table 2.3 lists exceptions to the naming rules.

File searches vary per command line switch and file type. The compilersupports relative and absolute directory names and an environmentvariable ( ADI_DSP ) to define file search paths. For more information onfile searches, see the command line switch that controls the specific search.For more information on environment variables, see the ADSP-2100Family Development Software Tools Release Note.

When you provide an input or output file name as an optional parameter,use the following guidelines:

• Use a file name (include the file extension) with either anunambiguous relative path or absolute path. A file name, with anabsolute path, includes the drive, directory, file name and fileextension. G21 uses the file extension convention listed in Table 2.2 todetermine the input file type. If you set a file name for output, you donot have to include a file extension, except as noted in Table 2.3. Thecompiler appends a file extension to files you name.

• Verify that the compiler is using the correct file. If you do not providethe complete file path as part of the parameter, G21 (in most cases)searches for input (or places output) in the current directory. Table 2.4lists the exceptions to the current directory file search/placementconvention.

Page 19: C Tools manual

2C Compiler

2 – 5

Input File Translation Operation Output FileExtension Extension.c C source to be preprocessed .i.h Macro or header file to be preprocessed .i.i C source to be compiled .s.s Assembler source to be preprocessed .is.asm Assembler source to be preprocessed .is.dsp Assembler source to be preprocessed .is.is Assembler source to be assembled .obj.obj Object file to be linked .exe————— —————.ach Architecture file for DSP system definition.a Library file for function definitions

DSP system memory map file output .mapDSP system symbol map file output .sym

Table 2.2 File Extensions & G21 Operations

Note: The compiler treats all files with unrecognized extensions as objectfiles.

G21 File Default Input file extension /Switch Type Default Output file extensionsourcefile See Table 2.2 Assumes .obj extension if none given-a Architecture Assumes .ach extension to reference name-o Executable Appends .exe extension to reference name-o -E C Source Appends no extension-o -S Assembler Appends no extension-o -c Object Appends .int , .cde , and .obj to name

Table 2.3 G21 Default File Name Extensions

Page 20: C Tools manual

2 C Compiler

2 – 6

File Type Directory EnvironmentVariable

Architecture $ADI_DSP/21xx/lib ADI_DSPRuntime Header $ADI_DSP/21xx/lib ADI_DSPTemporary (user defined) TMP

Table 2.4 Search/Place Directories & Environment Variables

Most compiler switches that begin with -W or -f have positive andnegative forms. Table 2.5 lists examples of these. This section documentsthe positive form of switches that support both formats.

Positive Form Negative Form-fsigned-bitfields -fno-signed-bitfields-Wimplicit -Wno-implicit

Table 2.5 Examples Of G21 Command Line Switch Positive & Negative Forms

sourcefileThe source file parameter (or parameters) on the command line selects thename of the file (or files) to be preprocessed, compiled, assembled, and/orlinked. A file name can include the drive, directory, file name and fileextension. G21 uses the file extension to determine what operations toperform. Table 2.2 lists the allowed extensions and matching compileroperations.

-a filenameThe -a (architecture) switch directs G21 to use the specified architecturedescription file as a description of your DSP hardware system. Use theSystem Builder utility to generate this file. For more information onarchitecture files, see the ADSP-2100 Family Assembler Tools & SimulatorManual.

-ansiThe -ansi (ANSI standard C compilation) switch directs the compilerto behave as a strict ANSI standard compiler. This behavior changeinvolves many features of the compiler. Some key features of the compilerthat are influenced by this switch are: the disabling of the asm , inline ,and typeof keywords, the predefinition of the macro__STRICT_ANSI__ , and treating abort , exit , and _exit asnon-built-in functions. Note that the alternate keywords __asm__ ,__inline__ , and __typeof__ continue to work despite -ansi .

Page 21: C Tools manual

2C Compiler

2 – 7

-cThe -c (compile only) switch directs G21 to compile and/or assemblethe source files, but stop before linking. The output is an object file foreach source file.

-D macro [ =definition ]The -D (define macro) switch directs the compiler to define a macro. Ifyou do not include the optional definition string, the compiler defines themacro as the string ‘1’. Note that G21 processes all -D switches on thecommand line before any -U (undefine macro) switches.

-EThe -E (end after preprocessing) switch directs G21 to stop after the CPreprocessor runs (without compiling). The output (preprocessed sourcecode) prints to standard out. G21 supports a group of command lineswitches that are C Preprocessor directives and may only be run incombination with the -E switch. Descriptions of these switches ( -C ,-dD , -dM , -dN , -M , -MM , -P ) follow.

• -CThe -C (comments) switch directs the C Preprocessor to retaincomments in the output file.

• -dDThe -dD (document defined macros) switch directs the CPreprocessor to output both a list of #define commands for all userdefined macros and the results of preprocessing.

• -dMThe -dM (document macros) switch directs the C Preprocessor tooutput just a list of #define commands for all the macros definedduring the execution of the preprocessor, including predefined macros.

• -dNThe -dN (document defined macro names) switch directs the CPreprocessor to output both a list of #define name entries for alluser defined macros (no arguments or contents) and the results ofpreprocessing.

• -MThe -M (make only) switch directs the C Preprocessor to output just arule suitable for the make utility describing the dependencies of themain program file. The format of the make rule output by thepreprocessor is: object-file : include-file ….

Page 22: C Tools manual

2 C Compiler

2 – 8

• -MMThe -MM (make macros only) switch directs the C Preprocessor tooutput just a rule suitable for the make utility describing thedependencies of the main program file. The rule only mentions filesincluded with #include “ file ” — (not for #include < file >). The format of the make rule output by the preprocessor is: object-file :include-file ….

• -PThe -P (pound prefix) switch directs the C Preprocessor to omit the#-lines with line number information in the output from thepreprocessor.

-fcond-mismatchThe -fcond-mismatch (allow conditional expression mismatch) switchdirects the compiler to allow conditional expressions with mismatchedtypes in the second and third arguments. The value of such an expressionis void .

-finline-functionsThe -finline-functions (force function inlining) switch directs thecompiler to integrate all simple functions into their callers. The compilerheuristically decides which functions are simple enough to be worthintegrating in this way. If all calls to a given function are integrated, andthe function is declared static , then the function is normally notoutput as assembler code in its own right.

-fkeep-inline-functionsThe -fkeep-inline-functions (force keeping of inlined functions)switch directs the compiler to output a separate runtime callable versionof the function, even if all calls to a given function are integrated and thefunction is declared static .

-fno-asmThe -fno-asm (no assembler keywords) switch directs the compiler tonot recognize asm , inline , or typeof as keywords. This switch doesnot affect __asm__ , __inline__ , and __typeof__ .

-fno-builtinThe -fno-builtin (no builtin functions) switch directs the compiler toonly recognize builtin functions that begin with two underscores ( __ ).Note that this switch affects many functions including the following: abs , fabs , labs , memcpy , memcmp , strcmp , strcpy , strlen ,and sqrt .

Page 23: C Tools manual

2C Compiler

2 – 9

-fsigned-bitfieldsThe -fsigned-bitfields (make bitfields signed) switch directs thecompiler to make bitfields signed, when the declaration does not useeither signed or unsigned . (negative form is-fno-signed-bitfields )

-fsigned-charThe -fsigned-char (make char signed) switch directs the compiler tomake the default type for char signed.

-fsyntax-onlyThe -fsyntax-only (just check syntax) switch directs the compiler tocheck the source code for syntax, but not write any output.

-funsigned-bitfieldsThe -funsigned-bitfields (make bitfields unsigned) switch directsthe compiler to make bitfields unsigned when the declaration does not useeither signed or unsigned . (negative form is-fno-unsigned-bitfields )

-funsigned-charThe -funsigned-char (make char unsigned) switch directs thecompiler to make the default type for char unsigned.

-fwritable-stringsThe -fwritable-strings (write strings) switch directs the compilerto store string constants in the writable data segment without makingthem unique.

-gThe -g (generate debugging information) switch directs the compiler tooutput debugging information. Note that this switch causes the compilerto define the macro __DEBUG__ . For more information on debugging,see Chapter 4, C Source Debugger.

-imacros filenameThe -imacros (introduce macros file) switch directs the C Preprocessorto process filename, discard the output, and make the macros (defined inthe file) available for use in the main input. Note that the preprocessorprocesses -D (define macro) and -U (undefine macro) command lineswitches before any -imacros switches. Also, the preprocessorprocesses -imacros switches in the order they appear on the commandline.

Page 24: C Tools manual

2 C Compiler

2 – 10

-I directoryThe -I (include search directory) switch directs the C Preprocessor toappend the directory to the search path for include files.

-I-The -I- (include “ file “ search directory) switch directs the CPreprocessor to search directories (appended to the search path previouslyby the -I switch) only for cases of #include “ file “ — (not for#include < file > ). The -I- switch does not affect -I switchesoccurring after it on the G21 command line. Note that the -I- switchprevents the C Preprocessor from searching for files in the currentdirectory.

-L directoryThe -L (library search directory) switch directs the linker to append thedirectory to the search path for library files.

-l library-nameThe -l (link library) switch directs the linker to search the library forfunctions when linking. The library-name is the portion of the file namebetween the lib prefix and .a extension. The G21 command lineswitch -lc directs the linker to search in the library named c forfunctions. This library resides in a file named libc.a . Note that youshould list all object files on the command line before using the -lswitch; this ensures that functions the object files refer to will be loadedfrom the library.

-mapThe -map (generate a memory map) switch directs the linker to output amemory map of all symbols. The map file name corresponds to theexecutable file name; if the executable file name is test.exe , the mapfile name is test.map .

-mno-doloopsThe -mno-doloops (no do loops) switch directs the compiler not togenerate do loop structures in the assembled code. Use this feature whenyour code contains do loops with a loop value greater than 16384.

-mreserved= register-listThe -mreserved (mark register(s) reserved) switch directs the compilernot to use the specified registers anywhere. This guarantees that a knownset of register are available for inline assembly code or linked assemblymodules. Separate each register name with a comma on the compiler

Page 25: C Tools manual

2C Compiler

2 – 11

command line. You can reserve the i2 and i3 registers. When youreserve either register, the corresponding l register ( l2 or l3 ) is alsoreserved.

-MDThe -MD (make document) switch directs the C Preprocessor to output arule suitable for the make utility describing the dependencies of themain program file in addition to completing compilation. The CPreprocessor names the output files the same as input, but changes theextension from .c to .d . The format of the make rule output by thepreprocessor is: object-file : include-file ….

-MMDThe -MMD (make macro document) switch directs the C Preprocessor tooutput a rule suitable for the make utility describing the dependencies ofthe main program file in addition to completing compilation. Dependencyinformation does not include system header files. The C Preprocessornames the output files the same as input, but changes the extension from.c to .d . The format of the make rule output by the preprocessor is:object-file : include-file ….

-nostdincThe -nostdinc (no standard directory search for include) switchdirects the C Preprocessor to search for header files in only the currentdirectory and directories specified with -I switch.

-nostdlibThe -nostdlib (no standard library) switch directs the linker to searchonly libraries specified with -l switch.

-o filenameThe -o (output) switch directs G21 to use filename for the name ofthe final output file.

-pedanticThe -pedantic (issue ANSI standard C compilation warnings) switchcauses the compiler to issue all the warnings consistent with strict ANSIstandard C (rejecting all programs that use forbidden extensions). Notethat the -pedantic switch does not cause the compiler to issue errors incases of alternate keywords beginning and ending with “ __ ” orexpressions that follow the __extension__ .

Page 26: C Tools manual

2 C Compiler

2 – 12

-pedantic-errorsThe -pedantic-errors (issue ANSI standard C compilation errors)switch causes the compiler to issue errors instead of warnings for casesdescribed in the -pedantic switch.

-runhdr filenameThe -runhdr (runtime header) switch directs the linker to use theruntime header you specify. If you do not use the -runhdr switch, thelinker uses the 2105_hdr.obj runtime header by default. G21 comeswith the following runtime header files: 2100_hdr.obj ,2101_hdr.obj , 2105_hdr.obj , 2111_hdr.obj , 2150_hdr.obj ,2171_hdr.obj .

-save-tempsThe -save-temps (save intermediate temporary files) switch directsG21 not to discard intermediate files. G21 places the intermediate output( *.i , *.is , *.s ) files in the current directory.

-SThe -S (stop after compilation) switch directs G21 to stop compilationbefore running the assembler. The compiler outputs an assembler file witha .s extension.

-traditionalThe -traditional (traditional C compilation) switch directs thecompiler to apply the following rules (consistent with traditional Ccompilers) to compilation:

• All extern declarations (including implicit declarations offunctions) take effect globally.

• The keywords typeof , inline , signed , const , andvolatile are not recognized.

• Pointer/integer comparisons are always allowed.• Integer types unsigned short and unsigned char promote to

unsigned int .• Out of range floating point literals are not flagged as an error.• String “constants” are not necessarily constant; they are stored in

writable space and identical looking constants are allocated separately.• All automatic variables not declared register are preserved by

longjmp .• Add the -traditional-cpp switch to the G21 command line.

Page 27: C Tools manual

2C Compiler

2 – 13

-traditional-cppThe -traditional-cpp (traditional C Preprocessing) switch directsthe preprocessor to apply the following rules (consistent with traditionalC Preprocessors) to compilation:

• Direct the preprocessor to delete comments (rather than replace themwith a space); this allows traditional token concatenation.

• Direct the preprocessor to recognize macro arguments within stringconstants in a macro definition.

• Direct the preprocessor to not defined the predefined macro__STDC__ . Note that the -traditional-cpp switch does notaffect the predefined macro __GNUC__ . Also, the-traditional-cpp switch does not affect GNU extensions,extensions indicated by __GNUC__ .

-U macroThe -U (undefine macro) switch lets you undefine macros. Note that thecompiler processes all -D (define macro) switches on the command linebefore any -U switches.

-vThe -v (verbose) switch directs G21 to print (to standard output) thecommands it issues to execute each stage. Also, G21 prints the versionnumber of the preprocessor and compiler.

-wThe -w (warnings off) switch directs the compiler to inhibit all warningmessages.

-WThe -W (warnings extra) switch directs the compiler to issue extrawarning messages for the following events:

• Whenever a non-volatile automatic variable might be changed by a callto longjmp .

• Whenever the compiler sees only the calls to setjmp . It cannot knowwhere longjmp will be called; a signal handler could call it at anypoint in the code. Note that this warning may be erroneous, becauselongjmp cannot be called at the place that would cause a problem.

• Whenever a function can return either with or without a value. Notethat falling off the end of the function body is considered returningwithout a value.

Page 28: C Tools manual

2 C Compiler

2 – 14

• Whenever an expression-statement contains no side effects.• Whenever an unsigned value is compared against zero with > or <= .

-WallThe -Wall (all recommended warnings) switch directs the compiler toissue warning messages that correspond to a list of individual warningswitches. The switches -Wall equates to are: -Wchar-subscripts ,-Wcomment , -Wformat , -Wimplicit , -Wparentheses ,-Wreturn-type , -Wswitch , -Wtrigraphs , -Wuninitialized ,-Wunused .

-Wchar-subscriptsThe -Wchar-subscripts (warnings for type char subscripts)switch directs the compiler to issue warning messages if an arraysubscript has type char .

-WcommentThe -Wcomment (warnings for comment string) switch directs thecompiler to issue warning messages if the comment start sequence /*appears in a comment.

-WerrorThe -Werror (warnings as errors) switch directs the compiler to makeall warnings into errors.

-WformatThe -Wformat (warnings for format/type mismatch) switch directs thecompiler to issue warning messages if arguments for printf , scanf ,and other functions have types that are not appropriate for the specifiedformat string.

-WimplicitThe -Wimplicit (warnings for implicit declarations) switch directs thecompiler to issue warning messages if a function or parameter is implicitlydeclared.

-WparenthesesThe -Wparentheses (warnings for omitted parentheses) switch directsthe compiler to issue warning messages if parentheses are omitted incertain contexts.

Page 29: C Tools manual

2C Compiler

2 – 15

-Wreturn-typeThe -Wreturn-type (warnings for int return types) switch directsthe compiler to issue warning messages if a function is defined with areturn type that defaults to int. Also, warn if a function whose return typeis not void has a return statement with no return value.

-WswitchThe -Wswitch (warnings for switch index/case mismatch) switchdirects the compiler to issue warning messages if a switch statement withan index of enumeral type lacks a case for any of the named codes of thatenumeration. Also, warn if any case labels are outside the enumerationrange. Note that the presence of a default label inhibits this warning.

-WtrigraphsThe -Wtrigraphs (warnings for ANSI trigraphs) switch directs thecompiler to issue warning messages if it encounters any ANSI trigraphs.

-WuninitializedThe -Wuninitialized (warnings for uninitialized variables) switchdirects the compiler to issue warning messages if an automatic variable isused without first being initialized.

-WunusedThe -Wunused (warnings for unused variables) switch directs thecompiler to issue warning messages if a local variable is unused asidefrom its declaration, a never defined function is declared static, or astatement computes a result that is explicitly not used.

2.4 G21 C LANGUAGE EXTENSIONSG21 supports a set of extensions to the C language. This section providesan overview of the extensions, capsule descriptions of each, and directsyou to text with further information on each extension.

Table 2.6 lists the G21 C language extension keywords. The extensionsprovide:

• Support for separate program and data memoryThe dm (data memory) keyword directs G21 to specify the location ofa static (or global) variable or to qualify a pointer declaration ( * ) asbeing in data memory. The pm (program memory) keyword directsG21 to specify the location of a static (or global) variable or to qualify apointer declaration ( * ) as being in program memory. For moreinformation on these keywords, see section 2.4.1, “Dual MemorySupport Keywords ( pm dm ).”

Page 30: C Tools manual

2 C Compiler

2 – 16

• Support for typeof declarationsThe typeof keyword lets you refer to the type of an expression. Formore information on this keyword, see section 2.4.2, “Type ReferenceSupport Keyword ( typeof() ).”

• Support for inline functionsThe inline (inline the following function) keyword directs G21 tointegrate the function code into the code of the callers. For moreinformation on this keyword, see section 2.4.3, “Inline FunctionSupport Keyword ( inline ).”

• Support for asm() inlining of assembly languageThe asm() keyword lets you place ADSP-2100 Family assemblylanguage commands directly in your C program. For more informationon the keyword, see section 2.4.4, “Inline Assembly Language SupportKeyword ( asm() ).”

• Support for compound statements within expressionsG21 C lets you place a compound statement inside an expression,enclosed in parentheses. This permits you to declare variables withinan expression. For more information on this feature, see section 2.4.5,“Support For Compound Statements Within An Expression.”

• Support for non-constant initializersG21 C provides support for initializers beyond that provided instandard C. The elements of an aggregate initializer for an automaticvariable are not required to be constant expressions in G21 C. For moreinformation on this feature, see section 2.4.6, “Non-Constant InitializerSupport.”

• Support for indexed initializersG21 C provides supports for initializers beyond that provided instandard C. The non-constant initializer support mentioned above alsoapplies to array element initializers. With an index, you may indicatethe element to initialize. For more information on this feature, seesection 2.4.7, “Indexed Initializer Support.”

• Support for aggregate assignmentsAn aggregate assignment expression looks like a cast containing aninitializer. For more information on this feature, see section 2.4.8,“Aggregate Assignment Support.”

Page 31: C Tools manual

2C Compiler

2 – 17

dm expressionpm expressioninline function-nametypeof expressionasm(“ assembly_commands ”)

Table 2.6 Alphabetical Listing Of G21 C Language Extension Keywords

2.4.1 Dual Memory Support Keywords ( pm dm )This section covers G21 language extension keywords to C that supportthe dual-memory space, modified Harvard architecture of the ADSP-2100Family processors. There are two keywords used to designate memoryspace: dm and pm . They can be used to specify the location of a static (orglobal) variable or to qualify a pointer declaration ( * ).

The following rules apply to dual memory support keywords:

• A memory space keyword ( dm or pm ) refers to the expression to itsright.

• You can specify one memory space for each * .

• G21 uses Data Memory as the default memory space for all variables.Automatic variables reside on the stack—always in data memory.

• G21 assumes all undeclared spaces for data to be data memory spaces.

• G21 uses Program Memory as the memory space for functions always.Function pointers always point to program memory.

• Automatic variables cannot be assigned memory spaces, all automaticvariables reside on the stack, which is always in data memory. Notethat the pm keyword cannot be used inside a function unlessaccompanied by the static qualifier.

• Literal character strings always reside in data memory.

Page 32: C Tools manual

2 C Compiler

2 – 18

Listing 2.1 shows examples of dual memory keyword syntax.

int pm abc[100]; /* declares an array abc *//* with 100 elements in program memory */

int dm def[100]; /* declares an array def *//* with 100 elements in data memory */

int ghi[100]; /* declares an array ghi *//* with 100 elements in data memory */

int pm * pm pp; /* declares pp to be a *//* pointer which resides in program memory and *//* points to a program memory integer */

int dm * dm dd; /* declares dd to be a *//* pointer which resides in data memory and *//* points to a data memory integer */

int *dd; /* declares dd to be a *//* pointer which resides in data memory and *//* points to a data memory integer */

int pm * dm dp; /* declares dp to be a *//* pointer which resides in data memory and *//* points to a program memory integer */

int pm * dp; /* declares dp to be a *//* pointer which resides in data memory and *//* points to a program memory integer */

int dm * pm pd; /* declares pd to be a *//* pointer which resides in program memory and *//* points to a data memory integer */

int * pm pd; /* declares pd to be a *//* pointer which resides in program memory and *//* points to a data memory integer */

float pm * dm * pm fp; /* the first pm means *//* that **fp is in program memory, the following *//* dm puts *fp in data memory, and fp itself is */in program memory */

Listing 2.1 Dual Memory Support Keyword Variable Syntax Examples

Page 33: C Tools manual

2C Compiler

2 – 19

Memory space specification keywords are similar to storage classes. Theycannot qualify type names and structure tags, but you can use them inpointer declarations. Listing 2.2 shows examples of memory spacespecification keywords in typedef and struct statements.

typedef float pm * PFLOATP;/* PFLOATP defines a type which is a pointer to a *//* float which resides in pm. */

struct s {int x; int y; int z; };static pm struct s mystruct={10,9,8};/* Note that the pm specification is not used in *//* the structure definition. The pm specification *//* is used when defining the variable mystruct */

Listing 2.2 Dual Memory Support Keyword typedef & struct Syntax Examples

2.4.1.1 Memory Keywords & Assignments / Type ConversionsMemory space specifications limit the kinds of assignments your programcan make:

• You may make assignments between variables allocated in differentmemory spaces.

• Pointers to Program Memory must always point to Program Memory.Pointers to Data Memory must always point to Data Memory.You maynot mix addresses from different memory spaces within oneexpression. Do not attempt to explicitly cast one type of pointer toanother.

Listing 2.3 shows a code segment with variables in different memoryspaces being assigned. Listing 2.4 shows a code segment with illegalmixing of memory space assignments.

int pm x;int dm y;x = y; /* Legal code */

Listing 2.3 Legal Dual Memory Space Variable Assignment Example

Page 34: C Tools manual

2 C Compiler

2 – 20

int pm *x;int dm *y;int dm a;x = y; /* Compiler will flag error */x = &a; /* Compiler will flag error */

Listing 2.4 Illegal Dual Memory Space Type Cast Example

2.4.1.2 Memory Keywords & Function Declarations / PointersFunctions always reside in program memory. Pointers to functions alwayspoint to program memory. Listing 2.5 shows some sample functiondeclarations with pointers.

int * y(); /* function y resides in *//* pm and returns a *//* pointer to an integer *//* which resides in dm */

int pm * y(); /* function y resides in *//* pm and returns a *//* pointer to an integer *//* which resides in pm */

int dm * y(); /* function y resides in *//* pm and returns a *//* pointer to an integer *//* which resides in dm */

int * pm * y(); /* function y resides in *//* pm and returns a *//* pointer which resides *//* in pm that points to *//* an integer which *//* resides in dm */

Listing 2.5 Dual Memory Support Keyword Function Declaration (With Pointers) Syntax Examples

Page 35: C Tools manual

2C Compiler

2 – 21

2.4.1.3 Memory Keywords & Function ArgumentsG21 checks calls to prototyped functions for memory space specificationsconsistent with the function prototype. Listing 2.6 shows sample code thatG21 will flag as inconsistent use of memory spaces between a functionprototype and a call to the function.

extern int foo(int pm*);/* declare function foo() which expects a *//* pointer residing in dm to an int residing *//* in pm as its argument and returns an int */

int x; /* define int x in dm */

foo(&x); /* call function foo() *//* using pm pointer (location of x) as the *//* argument. G21 FLAGS AS AN ERROR, THIS IS AN *//* INCONSISTENCY BETWEEN THE FUNCTION’S *//* DECLARED MEMORY SPACE ARGUMENT AND FUNCTION *//* CALL MEMORY SPACE ARGUMENT */

Listing 2.6 Illegal Dual Memory Support Keywords & Calls To Prototyped Functions

2.4.1.4 Memory Keywords & MacrosUsing macros when making memory space specification for variables orpointers can make your code easier to maintain. If you must change thedefinition of a variable or pointer (moving it to another memory space),declarations that depend on the definition may need to be changed toensure consistency between different declarations of the same variable orpointer.

To make changes of this kind easier, you can use C preprocessor macros todefine common memory spaces that must be coordinated. Listing 2.7shows two code segments that are equivalent after preprocessing. Thesegment on the right lets you redefine the memory space specifications byredefining the macro SPACE1 and/or SPACE2.

Page 36: C Tools manual

2 C Compiler

2 – 22

#define SPACE1 pm#define SPACE2 dm

char pm * foo (char dm *) char SPACE1 * foo (char SPACE2 *)char pm *x; char SPACE1 *x;char dm y; char SPACE2 y;

x = foo(&y); x = foo(&y);

Listing 2.7 Dual Memory Support Keywords & Macros

2.4.2 Type Reference Support Keyword ( typeof )The G21 typeof() construct lets you refer to the type of an expression.The syntax for using this keyword follows the same pattern as sizeof(). The typeof() construct acts semantically like a type name definedwith typedef . The argument to typeof() can be an expression or atype. Note that typeof() supports Program Memory objects.

You can use a typeof() construct anywhere a typedef name couldbe used. Examples of places where typeof() may be used are: in adeclaration, in a cast, or inside of sizeof() or typeof() .

Listing 2.8 shows typeof() with an argument that is an expression.Note that in the expression, the x is assumed to be an array of functions;the type described is that of the return value of the first of the functions.

typeof (x[0](1))

Listing 2.8 typeof() Argument Written With An Expression Example

Listing 2.9 shows a typeof() with an argument that is a type. The typedescribed is that of pointers to int . Listing 2.10 shows typeof()examples with pointers in their arguments.

typeof (int *)

Listing 2.9 typeof() Argument Written With A Type Example

Page 37: C Tools manual

2C Compiler

2 – 23

typeof (*x) y; /* This declares y with the *//* type of what x points to.*/

typeof (*x) y[4]; /* This declares y as an *//* array of such values. */

typeof (typeof (char *)[4]) y;/* This declares y as an array of pointers to *//* characters. It is equivalent to the following *//* traditional C declaration: char *y[4]; */

Listing 2.10 typeof() Argument Written With A Pointer Examples

Listing 2.11 uses macros to rewrite the third example in Listing 2.10. Thedeclaration is the type of arrays of four pointers to char.

#define pointer(T) typeof(T *)#define array(T, N) typeof(T [N])

array (pointer (char), 4) y; /* this is the *//* type of arrays of four pointers to char */

Listing 2.11 typeof() Argument Written With Macros Example

2.4.3 Inline Function Support Keyword ( inline )The G21 inline keyword directs G21 to integrate the code for thefunction you declare as inline into the code of its callers. This makesexecution faster by eliminating the function-call overhead. If any of theactual argument values are constant, their known values may permitsimplifications at compile time so that not all of the inline function’s codeneeds to be included. Listing 2.12 shows an example function definitionthat uses the inline keyword.

inline int inc (int *a){ (*a)++;}

Listing 2.12 Inline Function Definition Example

Page 38: C Tools manual

2 C Compiler

2 – 24

When a function is both inline and static , if all calls to the functionare integrated into the caller, and the function’s address is never used,then the function’s own assembler code is never referenced. In this case,G21 does not actually output assembler code for the function, unless youspecify the option -fkeep-inline-functions . Some calls cannot beintegrated for various reasons (in particular, calls that precede thefunction’s definition cannot be integrated, and neither can recursive callswithin the definition). If there is a non-integrated call, then the function iscompiled to assembler code as usual. The function must also be compiledas usual if the program refers to its address, because that can’t be inlined.

When an inline function is not static , then the compiler must assumethat there may be calls from other source files; since a global symbol canbe defined only once in any program, the function must not be defined inthe other source files, so the calls therein cannot be integrated. Therefore, anon-static inline function is always compiled on its own in the usualfashion.

If you specify both inline and extern in the function definition,then the definition is used only for inlining. In no case is the functioncompiled on its own, not even if you refer to its address explicitly. Such anaddress becomes an external reference, as if you had only declared thefunction, and had not defined it.

This combination of inline and extern has almost the effect of amacro. The way to use it is to put a function definition in a header filewith these keywords, and put another copy of the definition (lackinginline and extern ) in a library file. The definition in the header filewill cause most calls to the function to be inlined. If any uses of thefunction remain, they will refer to the single copy in the library.

Note: For information on the G21 command line switches-finline-functions and -fkeep-inline-functions and howthey affect function inlining, see previous section “G21 Command LineSwitches.”

2.4.4 Inline Assembly Language Support Keyword ( asm )The G21 asm() construct lets you code ADSP-2100 Family assemblylanguage instructions within a C function. The asm() construct is usefulfor expressing assembly language statements that cannot be expressedeasily or efficiently with C constructs.

Page 39: C Tools manual

2C Compiler

2 – 25

With asm() you can either code complete assembly languageinstructions or you can specify the operands of the instruction using Cexpressions. When specifying operands with a C expression, you do notneed to know which registers or memory locations contain C variables.

An asm() construct, without operands, takes the form show below:

asm(“si=0;”);

The complete assembly language instruction enclosed in quotes is theargument to asm() .

Using asm() constructs with operands require some additional syntax.The following sections cover this syntax:

• Assembly Construct Template• Assembly Construct Operand Description• Assembly Constructs With Multiple Instructions• Assembly Construct Reordering & Optimization• Assembly Constructs With Input & Output Operands• Assembly Construct & Macros• Assembly Constructs & C/Assembly Symbol Association

2.4.4.1 Assembly Construct TemplateUsing asm() constructs, you can specify the operands of the assemblyinstruction using C expressions. You do not need to know which registersor memory locations contain C variables. Use the following syntax foryour asm() constructs:

asm(“ template ” : “ constraint ” ( out ops ) : “ constraint ” ( in ops ) : “ clobber ”);

templateThis is the assembly instructions with %number indicating the placementof input and output operands. The numbering of operands starts at 0 andnumbers the operands in order of appearance from left to right. Separatemultiple instruction templates with a semicolon. For more information onmultiple instruction templates see section 2.4.4.3, “Assembly ConstructsWith Multiple Instructions.”

Page 40: C Tools manual

2 C Compiler

2 – 26

constraintThis is part of the asm() syntax lets you direct G21 to use certainregisters for the input and output operands. For more information onoperand constraints, see section 2.4.4.2, “Assembly Construct OperandDescription.”

out opsThis is the set of C variable names that correspond to output operands forthe assembly instructions.

in opsThis is the set of C variable names that correspond to input operands forthe assembly instructions.

clobberThis is part of the asm() syntax lets you inform G21 that the listedregisters are overwritten by the assembly instructions. Use lower case forclobbered register names and separate each with a comma.

The following rules apply to assembly construct template syntax:

• Only the first argument to asm() , the assembly language template, ismandatory. All other arguments are optional.

• Each operand is described by an operand constraint string followed by aC expression in parentheses.

• Use a colon to separate the template from the first output operand, thelast output operand from the first input operand, and the last inputoperand from the clobbered registers. If there are no output operands,and there are input operands, then there must be two consecutivecolons separating the assembly template from the input operands.

• Use a comma to separate operands and registers within arguments.

• The number of operands in arguments must match the number ofoperands in your template.

• The number of permissible operands is ten ( %0 , %1 , %2 , %3 , %4 ,%5 , %6 , %7 , %8 , and %9 ).

Page 41: C Tools manual

2C Compiler

2 – 27

• The compiler cannot check whether the operands have data types thatare reasonable for the instruction being executed. It does not parse theassembler instruction template and does not know what it means, orwhether it is a valid assembler input.

The following example shows how to apply the asm() constructtemplate to the ADSP-2100 Family assembly language abs instruction:

{int x, result;

asm (“%0=abs %1;” : “=a” (result) : “e” (x));

/* result = abs x; */}

In this example:

• The template is “%0=abs %1;” . The %0 is replaced with operandzero (result) , the first operand. The %1 is replaced with operandone (x) .

• The output operand is the C variable: result . The letter a is theoperand constraint for the variable. This constrains the output to an AXregister. The = in =a indicates that the operand is an output.

• The input operand is the C variable: x . The letter e is the operandconstraint for the variable. This constrains x to any data register.

2.4.4.2 Assembly Construct Operand DescriptionThe second and third arguments to the asm() construct describe theoperands in the assembly language template. There are several pieces ofinformation that need to be conveyed for G21 to know how to assignregisters to operands. You convey this information with an operandconstraint. The operand constraint string contains a letter correspondingto each class of allowable register. Table 2.7 describes the correspondencebetween constraint letters and register classes.

To assign registers to the operands, G21 must be told which operands inan assembly language instruction are inputs, which are outputs, andwhich outputs may not overlap inputs. The compiler is told this in threeways, the first two are required.

Page 42: C Tools manual

2 C Compiler

2 – 28

• The output operand list appears as the first argument after theassembly language template. The list is separated from the assemblylanguage template with a colon. The input operands are separatedfrom the output operands with a colon and always follow the outputoperands.

• The operand constraints describe which registers are set because of anassembly language instruction. The = in = constraint indicatesthat the operand is an output; all output operand constraints must use= .

• Unless an output operand has the &= constraint modifier, G21 mayallocate it in the same register as an unrelated input operand. This isbecause G21 assumes that the inputs are consumed before the outputsare produced. This assumption may be false if the assembler codeactually consists of more than one instruction. In such a case, use&= for each output operand that may not overlap an input.

e Data registers: AX0 , AX1 , AY0 , AY1 , MX0 , MX1 ,MY0 , MY1 , MR0 , MR1 , SI , SR0 , SR1

a AX registers: AX0 , AX1 , AR , MR0 , MR1 , SR0 , SR1A AY0 and AY1 registersb MX registers: MX0 , MX1 , AR , MR0 , MR1B MY0 and MY1 registersc AR registerC MR0 registerd SI registers: SI , AR , MR0 , MR1 , SR0 , SR1D SR1 registerf SE registerw DAG1 i registersx DAG1 m registersy DAG2 i registersz DAG2 m registers=constraint Indicates constraint is applied to an output operand=&constraint Indicates constraint is applied to an output operand that

may not overlap an input

Table 2.7 Operand Constraints & Constraint Modifiers For asm() Constructs

Note: The use of any letter not listed above results in unspecifiedbehavior. The compiler does not check the validity of the code by usingthe constraint letter.

Page 43: C Tools manual

2C Compiler

2 – 29

2.4.4.3 Assembly Constructs With Multiple InstructionsThere can be many assembly instructions in one template. The inputoperands are guaranteed not to use any of the clobbered registers, so youcan read and write the clobbered registers as often as you like. If theasm() string is longer than one line, you may continue it on the next lineby placing a backslash (\) at the end of the line. The following listing is anexample of multiple instructions in a template:

/* (pseudo code) ax1 = from; ay1 = to; result = from + to;*/

asm (“ax1=%1; \ay1=%2; \%0=ax1+ay1;”: “=a” (result) /* output operand */: “e” (from), “e” (to) /* input operands */: “ax1”, “ay1”); /* clobbered registers */

2.4.4.4 Assembly Construct Reordering & OptimizationIf an asm() construct has output operands, (for optimization purposes)G21 assumes the instruction lacks side effects except to change the outputoperands. This does not mean that instructions with a side effect cannot beused, but you must be careful. The compiler may eliminate them if theoutput operands are not used, or move them out of loops, or replace twowith one if they constitute a common sub-expression. Also, if yourinstruction does have a side effect on a variable that otherwise appears notto change, the old value of the variable may be reused later if it happens tobe found in a register.

You can prevent an asm() instruction from being deleted, movedsignificantly, or combined, by writing the keyword volatile after theasm . For example:

#define set_priority(x) \asm volatile (“set_priority %0;”: /* no outputs */ : “e” (x))

Note: An asm volatile () construct can be moved in ways thatappear insignificant to the compiler, such as across jump instructions. Youcannot expect a sequence of asm volatile () constructs to remainperfectly consecutive. If you want consecutive output, use a single asm()construct. Another way to avoid reordering is to use the output of anasm() construct in a C instruction.

Page 44: C Tools manual

2 C Compiler

2 – 30

2.4.4.5 Assembly Constructs With Input & Output OperandsThe output operands must be write only; G21 assumes that the values inthese operands do not need to be preserved.

When the assembler instruction has an operand that is both read from andwritten to, you must logically split its function into two separateoperands: one input operand and one write-only output operand. Theconnection between them is expressed by constraints that say they need tobe in the same location when the instruction executes. You can use thesame C expression for both operands, or different expressions. Forexample, in the following statement, the modify instruction with baras its read only source operand and foo as its read write destination:

/* (pseudo code) modify (foo,bar); */

asm (“modify (%0,%2);” : “=w” (foo) : “0” (foo), “x” (bar));

The constraint “0” for operand 1 says that it must occupy the samelocation as operand 0. A digit in an operand constraint is allowed only inan input operand, and it must refer to an output operand.

Only a digit in the constraint can guarantee that one operand is in thesame place as another. Just because foo is the value of both operandsdoes not guarantee that they are in the same place in the generatedassembler code. The following does not work:

/* NOT recommended */asm (“modify (%0,%2);” : “=w” (foo) : “w” (foo), “x” (bar));

Various optimizations or reloading could cause operands 0 and 1 to be indifferent registers. For example, the compiler might find a copy of thevalue of foo in one register and use it for operand 1, but generate theoutput operand 0 in a different register.

Be aware that asm() does not support input operands that are both readfrom and written to. The example below shows a dangerous use of suchan operand. In this example, my_variable is modified during theasm() operation. The compiler only knows that the output,result_asm , has changed. Subsequent use of my_variable after theasm() instruction may yield incorrect results since those values mayhave been modified during the asm() instruction and not restored.

Page 45: C Tools manual

2C Compiler

2 – 31

int result_asm;int *my_variable;

/* NOT recommended *//* (pseudo code) result_asm=dm(*my_variable,3); *//* asm() operation changes value of my_variable */

asm(“%0=dm(%1,3);” : “=e” (result_asm) : “w” (my_variable));

2.4.4.6 Assembly Constructs & MacrosThere are two ways to combine asm() constructs and macros. You canuse macros within asm() constructs and you can define macros thatcontain asm() constructs.

macros within asm() constructsIf you want to use macros inside asm() statements, you must specify aninclude file that defines the macros. The following example illustrates themethod for including the def2101.h file and using a macro. Thedef2101.h file is in the $ADI_DSP/21xx/include directory andcontains bit definitions for ADSP-2101 system registers:

asm(“#include <def2101.h>”);

main(){

asm(“ar=dm(Tcount_Reg); ena timer;” );}

macros that contain asm() constructsA way to use asm() constructs is to encapsulate them in macros thatlook like functions. For example,

#define abs_macro(result,x) \asm(“%0=abs %1;” : “=a” (result) : “a” (x))

/* (pseudo code) result = abs x; */

main (){

int result_var;int x_var=10;abs_macro(result_var, 10);/* or */abs_macro(result_var, x_var);

}

Page 46: C Tools manual

2 C Compiler

2 – 32

This defines a macro, abs_macro() , which uses the asm() constructsto perform an assembly-language abs operation on variable x_var ,putting the result in result_var .

2.4.4.7 Assembly Constructs & C/Assembly Symbol AssociationThe asm() construct in G21 C lets you assign C variable names toassembly language symbols and to specific registers. For information onnaming conventions for these variables and symbols, see Chapter 3,Assembly Language Interfacing.

You can assign an assembly language symbol to a static or global variableusing asm() . Wherever the variable is defined or declared, place anasm(“name”) after the definition or declaration. The assembly languagesymbol must be placed within double quotes, surrounded by parentheses,after the asm keyword. For example,

int foo asm(“bar”);

Note: This specifies that the name used for the variable foo in theassembler code is bar instead of the conventional name foo_ . Thisfeature lets you define names for the linker that do not end with anunderscore. You must make sure that the assembler names you choose donot conflict with any other assembler symbols.

You can assign a particular register variable using asm() . Assigning aregister to a variable by placing the register name within quotes as theargument to asm() . The following example assigns the register AY0 tothe variable x :

register int x asm(“AY0”);

You can define a local register variable with a specified register as well. Inthe following example, i5 is the name of the register that must be used.Note that this is the same syntax used for defining global registervariables, but for a local variable it appears within a function.

register int *foo asm (“i5”);

Defining such a register variable does not reserve the register. It remainsavailable for other uses in places where flow control determines thevariable’s value is not live.

Page 47: C Tools manual

2C Compiler

2 – 33

These rules apply to using asm() constructs for assignments:

• Global register variable declarations must precede function definitions.

• Choose a register that is normally saved and restored by function calls,so that library routines do not overwrite it.

• Defining a global register variable in a certain register reserves thatregister entirely for this use, within the current file. The register is notallocated for any other purpose in the functions in the current file. Theregister is not saved and restored by these functions.

• It is not safe to access the global register variables from signalhandlers, or from more than one thread of control. The runtime libraryroutines may temporarily use the register.

• It is not safe for one function that uses a global register variable to callanother such function by way of a third function that was compiledwithout knowledge of this variable (that is, in a different source file inwhich the variable was not declared).

• Excessive use of this feature may leave the compiler too few availableregisters to compile certain functions.

2.4.5 Support For Compound Statements Within ExpressionsG21 C lets you place a compound statement inside an expression, enclosedin parentheses. This permits you to declare variables within an expression.Note that the value of a compound expression is the value of the laststatement in the expression.

Listing 2.13 shows an example of compound expression usage.

({ int y = foo (); /* This is expression for */ int z; /* the absolute value of */ if (y > 0) z = y; /* function foo () */ else z = - y; z;}) /* z; is the last statement */

/* in the expression and is *//* the return value */

Listing 2.13 Compound Expression Example

Page 48: C Tools manual

2 C Compiler

2 – 34

Compound expressions aid in coding macro definitions that evaluate eachoperand exactly once. Listing 2.14 shows two code segments that definemacros for finding the maximum of two variables. The standard C macro(definition on the left) computes either a or b twice, with bad results ifthe operand has side effects. The G21 C macro (definition on the right)does not have this problem. Note that writing the G21 C macro definitiondepends on knowing the type of operand (in this case a and b areint ). Also, note that this example could be written for the general casewith a typeof() construct.

#define max(a,b) \ #define maxint(a,b) \((a) > (b) ? (a) : (b)) ({ int _a = (a), _b = (b); \

_a > _b ? _a : _b; })

Listing 2.14 Compound Expression With Macros Example

2.4.6 Non-Constant Initializer SupportG21 C provides support for initializers beyond that provided in standardC. The elements of an aggregate initializer for an automatic variable arenot required to be constant expressions in G21 C.

Listing 2.15 shows an initializer with runtime varying elements:

foo (float f, float g){ float beat_freqs[2] = { f-g, f+g };}

Listing 2.15 Initializer With Runtime Varying Elements Example

2.4.7 Indexed Initializer SupportStandard C requires the elements of an initializer to appear in a fixedorder, the same as the order of the elements in the array or structure beinginitialized.

G21 C supports labeling elements for array initializers. This feature letsyou specify array or structure elements in any order by specifying thearray indices or structure field names to which they apply. To specify anarray index, write the [ index ] before the element value.

The index values must be constant expressions, even if the array being

Page 49: C Tools manual

2C Compiler

2 – 35

initialized is automatic. Listings 2.16 and 2.17 show equivalent arrayinitializers, the first in standard C and next using G21 C.

int a[6] = { 0, 0, 15, 0, 29, 0 };

Listing 2.16 Standard C Array Initializer Example (Equivalent To Listing 2.17)

int a[6] = { [4] 29, [2] 15 };

Listing 2.17 G21 C Array Initializer With Labeled Elements Example

You can combine this technique of naming elements with standard Cinitialization of successive elements. Each initializer element that does nothave a label applies to the next consecutive element of the array orstructure. Listings 2.18 and 2.19 are equivalent. Labeling the elements ofan array initializer is especially useful when the indices are characters orbelong to an enum type, see Listing 2.20 for an example.

int a[6] = { 0, v1, v2, 0, v4, 0 };

Listing 2.18 Standard C Array Initializer Example (Equivalent To Listing 2.19)

int a[6] = { [1] v1, v2, [4] v4 };

Listing 2.19 G21 C Array Initializer With Labeled Elements Example

int whitespace[256] ={ [‘ ‘] 1, [‘\t’] 1, [‘\h’] 1, [‘\f’] 1, [‘\n’] 1, [‘\r’] 1};

Listing 2.20 G21 C Array Initializer With enum Type Indices Example

In a structure initializer, specify the name of a field to initialize withfieldname : before the element value. Listings 2.21 and 2.22 areequivalent.

struct point { int x, y; };

struct point p = { xvalue, yvalue };

Listing 2.21 Standard C struct Initializer Example (Equivalent To Listing 2.22)

struct point { int x, y; };

Page 50: C Tools manual

2 C Compiler

2 – 36

struct point p = { y: yvalue, x: xvalue };

Listing 2.22 G21 C struct Initializer With Labeled Elements Example

2.4.8 Aggregate Assignment SupportExtended initializer support in G21 C includes support for aggregateassignment expressions. An aggregate assignment looks like a castcontaining an initializer. Its value is an object of the type specified in thecast, containing the elements specified in the initializer.

The most common usage for an aggregate assignment is in specifying atype struct. Listing 2.23 shows a standard C struct definition. Listing 2.24shows equivalent code that has been simplified using an aggregateassignment.

struct foo {int a; char b[2];} structure;

{ struct foo temp = { x + y, ‘a’, 0 }; structure = temp; }

Listing 2.23 Standard C struct Example

struct foo {int a; char b[2];} structure;

structure = ((struct foo) {x + y, ‘a’, 0});

Listing 2.24 G21 C Constructor struct Example

Another usage for an aggregate assignment is in specifying an array.Listing 2.25 shows an example where all the elements of the aggregateassignment are made up of simple constant expressions and the aggregateassignment is coerced to a pointer to its first element.

char **foo = (char *[]) { “x”, “y”, “z” };

Listing 2.25 G21 C Constructor Array Example

2.5 USING THE C PREPROCESSORThe C preprocessor (CPP) is a macro processor. You use CPP to maketransformations and text substitutions in you source code. The C

Page 51: C Tools manual

2C Compiler

2 – 37

preprocessor provides:

• Header file inclusion• Macro expansion• Conditional compilation

You control preprocessor transformations with preprocessor commands(lines starting with # ), but there are three transformations thepreprocessor makes without any commands:

• Replaces comments with single spaces• Deletes backslash-newline sequences, no matter where. This lets you

break a long line for cosmetic purposes without changing its meaning.• Replaces predefined macro names with their expansions

Note: The following are exceptions to the above transformations:

• The preprocessor does not recognize comments or macros within thefilename delimiters of the a #include command

• The preprocessor does not recognize comments or predefined macroswithin a character or string constant.

2.5.1 Starting The C PreprocessorG21 usually runs the preprocessor. Most preprocessor features areaccessible from the G21 command line. Use the information in this sectiononly when you must run the preprocessor alone.

Note: For the location of the preprocessor executable file, see theADSP-2100 Family Development Software Tools Release Note

The G21 C Preprocessor has many start up options. This section shows thecommand line and all the options. A template for the C Preprocessorcommand line follows:

• sourcefile - This is the name of the file (or files) to be preprocessed. Afile name can include the drive, directory, file name and file extension.

cpp sourcefile [ sourcefile …] - switch [ parameter ] [- switch [ parameter ]…]

Page 52: C Tools manual

2 C Compiler

2 – 38

• switch and parameter - The C Preprocessor has many optional switches.These select the operations that the preprocessor will complete. Table2.8 lists all the preprocessor switches, parameters, and syntax (optionalones are shown enclosed in [ ]). For complete descriptions of eachpreprocessor switch and parameters, see the next section, “CPreprocessor Command Line Switches.”

The preprocessor, CPP , program name can be uppercase or lowercase,except in UNIX systems where it must be lowercase. The followingcommand line, for example:

cpp source.c -Wall -H

runs G21 with:

source.c Selects a C language source file for yourprogram

-Wall Selects a list of compiler warnings-H Selects output of all header files used

sourcefile[-$][-C][-dD][-dM][-D macro [ =definition ]][-dN][-H][-I-][-I directory ][-imacros filename ][-nostdinc][-P][-pedantic-errors][-pedantic][-U macro ][-Wall][-Wcomment][-Wtraditional][-Wtrigraphs]

Table 2.8 Alphabetical Listing Of C Preprocessor Command Line Switches

Page 53: C Tools manual

2C Compiler

2 – 39

Note: C Preprocessor switches in Table 2.8 may be used in any order onthe command line. Items shown in [ ] are optional. Items shown in italicsare user dependant and are described with each switch in the next section,“C Preprocessor Command Line Switches.”

2.5.2 C Preprocessor Command Line SwitchesAll (but two) of the C Preprocessor command line switches can be passedto CPP from the G21 command line. For descriptions of the the listedcommand line switches, see the previous section, “G21 Command LineSwitches”:

sourcefile , -C , -dD , -dM , -D macro [ =definition ] , -dN , -I-, -I directory , -imacros filename , -nostdinc , -P ,-pedantic-errors , -pedantic , -U macro , -Wall , -Wcomment ,-Wtraditional , -Wtrigraphs

The switches which can only be used on the CPP command line are:

-HThe -H (header) switch directs the C Preprocessor to output the name ofeach header file used and the results of preprocessing.

-$The -$ (no $ characters) switch directs the C Preprocessor to forbid theuse of $ in identifiers.

2.5.3 C Preprocessor CommandsAll preprocessor commands (except # and ## ) must be the firstnon-white space characters on their line. The # and ## preprocessorcommands provide string conversion and concatenation of strings.Further information on these features is available with the commanddescriptions later in this section.

Table 2.9 lists the G21 C Preprocessor command set. A preprocessorcommand:

• May not be more than one line in length• May be split with a backslash newline• May contain comments containing backslash newline• May not come from a macro expansion

Page 54: C Tools manual

2 C Compiler

2 – 40

#define macro definition#define macro ( arguments ) definition#elif expression#else#endif#error message#if expression#ifdef macro#ifndef macro#include < filename >#include “ filename ”#include macro#undef macro#warning message###

Table 2.9 Alphabetical Listing Of C Preprocessor Commands

Note: C Preprocessor commands in Table 2.9 may be used in any Csource file. Items shown in italics are user dependant and are describedwith each command in this section.

#define macro definitionThis command directs the preprocessor to define the macro as thedefinition. The definition must be a single line and it may not end in themiddle of a multi-line string constant or character constant. The followingline defines a macro named BUFFER_SIZE that the preprocessor willreplace with the text 1020 :

#define BUFFER_SIZE 1020

#define macro ( arguments ) definitionThis command directs the preprocessor to define the macro as thedefinition using the arguments. The definition must be a single line and itmay not end in the middle of a multi-line string constant or characterconstant. The arguments are identifiers, separated by commas. There mustbe no space between the macro name and the left parenthesis. Thefollowing line defines a macro named MIN that selects the minimum oftwo numeric arguments:

#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))

Page 55: C Tools manual

2C Compiler

2 – 41

#elif expressionThis command (else if) goes in the middle of a #if … #endif pairsubdividing it. The #elif includes an expression to test and does notrequire a matching #endif of its own. The following two code segments(shown side by side) are equivalent.

#if X == 1 #if X == 1… …#else /* X != 1 */ #elif X == 2#if X == 2 …… …#else /* X != 2 */ #else /* X != 2 and X != 1*/… …#endif /* X != 2 */ …#endif /* X != 1 */ #endif /* X != 2 and X != 1*/

#elseThis command goes in the middle of a #if … #endif pair. The #elseadds alternative text to a conditional. The preprocessor uses the alternatetext if the original expression is false. In the following pseudo-code:

• If expression is non-zero, the text-if-true is active and#else acts as a failing conditional; the preprocessor ignores thetext-if-false

• If the #if conditional fails, the preprocessor treats text-if-falseas active

#if expressiontext-if-true#else /* Not expression */text-if-false#endif /* Not expression */

#endifThis command terminates a #if … #endif pair. The #ifs and#endifs must balance.

Page 56: C Tools manual

2 C Compiler

2 – 42

#error messageThis command directs the preprocessor to report a fatal error. The rest ofthe line that follows #error is used as the error message. The followingcode segment shows an example error message:

#ifndef __ADSP2105__#error Expecting ADSP-2105. Check architecture file!#endif

#if expressionThis command begins a #if … #endif pair. The text inside of aconditional can include preprocessor commands. Commands inside theconditional are obeyed only if that branch of the conditional succeeds. Thetext can also contain other conditional groups. The expression is a Cexpression of integer type, subject to stringent restrictions. It may contain:

• Integer constants• Character constants• Arithmetic operators: addition, subtraction, multiplication, division,

bitwise operations, shifts, comparisons, and && and || .• Macro calls, expanded before computation of the expression’s value• Non-macro identifiers, treated as zero. Note that sizeof operators

and enum-type values are not allowed. These, like all othernon-macro identifiers, are treated as zero.

#ifdef macroThis command (if defined) begins a #ifdef … #endif pair and directsthe preprocessor to test for definition of a macro. A macro is considered tobe defined if it has a value and that value is not zero. The following twocode segments (shown side by side) are equivalent.

#if defined ( macro ) #ifdef macro

#ifndef macroThis command (if not defined) begins a #ifndef … #endif pair anddirects the preprocessor to test for non-definition of a macro. A macro isconsidered to be undefined if it has no defined value or has a definedvalue of zero. The following two code segments (shown side by side) areequivalent.

#if ! defined ( macro ) #ifndef macro

Page 57: C Tools manual

2C Compiler

2 – 43

#include < filename >This command directs the preprocessor to include the system header filespecified by filename. The preprocessor first searches for the file in thedirectories you specify, then in the standard list of system directories. TheG21 command line switches -I , -I- , and -nostdinc influence thedirectory search. Note that this form of include may not have the /* or> characters in the filename:

#include “ filename ”This command directs the preprocessor to include the user header filespecified by file name. The preprocessor first searches for the file in thecurrent directory, then in directories you specify, and last in the standardlist of system directories. The G21 command line switches -I , -I- , and-nostdinc influence the directory search. Note that this form of includemay not have the “ character in the filename:

#include macroThis command directs the preprocessor to expand the macro. Thepreprocessor processes the expanded text (which must match either<filename> or “filename” ).

#undef macroThis command directs the preprocessor to undefine the macro. Thefollowing line undefines a macro named BUFFER_SIZE :

#undef BUFFER_SIZE

#warning messageThis command directs the preprocessor to issue a warning and continueprocessing. The rest of the line that follows #warning is used as thewarning message. The following code segment shows an examplewarning message:

#ifndef __ADSP2105__#warning Expecting ADSP-2105. Check architecture file!#endif

Page 58: C Tools manual

2 C Compiler

2 – 44

#The # command directs the preprocessor to convert a macro argumentinto a string constant. The preprocessor can convert an argument to astring when macro arguments are substituted into the macro definition.The character # before the argument name specifies conversion of theargument to a string when it is substituted at that point in the definition.Note that the preprocessor handles white space in string conversion textaccording to the following rules: it ignores leading and trailing whitespace and converts any white space in the middle of the text to a singlespace in the resulting string. The example code segment defines a macrothat takes an argument and converts the argument to a string whensubstituting in the body of the definition. Listing 2.26 shows the code youinput to the preprocessor and Listing 2.27 shows the preprocessor output.

#define WARN_IF(EXP) \{ if (EXP) \ fprintf (stderr, “Warning: “ #EXP “\n”); \}

WARN_IF(current < minimum);

Listing 2.26 # Preprocessor Directive Example Input

{ if (current < minimum) fprintf (stderr, “Warning: “ “current < minimum” “\n”);};

Listing 2.27 # Preprocessor Directive Example Output

##The ## command directs the preprocessor to concatenate two strings.When you define a macro, you request concatenation with the specialoperator ## in the macro body. The result is to concatenate the syntactictokens on either side of the ## . The example code segment defines amacro that takes the name of a command as an argument, converts theargument to a string, and concatenates the string with _command tomake the function name. Listing 2.28 shows the code you input to thepreprocessor and Listing 2.29 shows the preprocessor output.

Page 59: C Tools manual

2C Compiler

2 – 45

#define COMMAND(NAME) { #NAME, NAME ## _command }struct command commands[] = { COMMAND(quit), COMMAND(help), };

Listing 2.28 ## Preprocessor Directive Example Input

struct command commands[] = { { “quit”, quit_command } , { “help”, help_command } , };

Listing 2.29 ## Preprocessor Directive Example Output

2.5.4 C Preprocessor Macro SupportThe G21 C Preprocessor supports predefined macros and user definedmacros. This section describes the predefined macros, header (macro)files, and macro writing techniques.

2.5.4.1 Predefined MacrosTable 2.10 lists the set of predefined macros that G21 provides. You canuse these macros without defining them. This section describes eachpredefined macro.

__ADSP21XX____ADSP2100____ADSP2101____ADSP2105____ADSP2111____ADSP2150____ADSP2171____BASE_FILE____DATE____DEBUG____FILE____GNUC____LINE____INCLUDE_LEVEL____STDC____STRICT_ANSI____TIME____VERSION__

Table 2.10 Alphabetical Listing Of G21 Predefined Macros

Page 60: C Tools manual

2 C Compiler

2 – 46

__ADSP21XX__G21 defines this macro always. The definition of this macro implies thatyou are using the ADSP-2100 Family Fixed Point C compiler. (G21extension).

__ADSP2100____ADSP2101____ADSP2105____ADSP2111____ADSP2150____ADSP2171__The preprocessor expands a macro from this set of macros, correspondingto the runtime header you select with the -runhdr G21 command lineswitch. The macro expands to the decimal integer constant 1. If you do notselect a runtime header, the preprocessor defines the __ADSP2105__macro. (G21 extension).

__BASE_FILE__The preprocessor expands this macro to the main input file name as astring constant. The string matches the name of the main program sourcefile specified on the G21 command line. (G21 extension).

__DATE__The preprocessor expands this macro into the date that the preprocessor isbeing run as a string constant. The date string constant takes the formMmm dd yyyy . (ANSI standard).

__DEBUG__G21 defines this macro when you use the -g switch on the G21command line. The definition of this macro implies that G21 will generatecode to run with CBUG. (G21 extension).

__FILE__The preprocessor expands this macro into the current input file name as astring constant. The string matches the name of the file specified on theG21 command line or in a preprocessor #include command. (ANSIstandard).

__GNUC__G21 defines this macro always. The definition of this macro implies thatyour code may use G21 C language extensions. (G21 extension).

Page 61: C Tools manual

2C Compiler

2 – 47

__LINE__The preprocessor expands this macro into the current input line numberas a decimal integer constant. (ANSI standard).

__INCLUDE_LEVEL__The preprocessor expands this macro into the current depth of include filenesting as a decimal integer constant. The preprocessor increments thevalue of this macro with every #include command and decrementswith every end of file. (ANSI standard).

__STDC__The preprocessor expands this macro to the decimal integer constant 1.The definition of this macro implies that this code is ANSI Standard C.The -traditional G21 command line switch undefines this macro.(ANSI standard).

__STRICT_ANSI__G21 defines this macro when you use the -ansi switch on the G21command line. The definition of this macro implies that G21 will performas an ANSI standard compiler. (G21 extension).

__TIME__The preprocessor expands this macro into the time that the preprocessor isbeing run as a string constant. The date string constant takes the formhh:mm:ss . (ANSI standard).

__VERSION__The preprocessor expands this macro to the version number of G21 as astring constant. The version number string constant takes the form #.## .(G21 extension).

2.5.4.2 Header FilesA header file contains C declarations and macro definitions. Use the#include C preprocessor command to establish access to header files foryour program. Header files have a .h extension on the filename.

There are two main uses for header files:

• System header files declare the interfaces to the parts of the operatingsystem. Include them in your program for the definitions anddeclarations you need to access system calls and libraries.

Page 62: C Tools manual

2 C Compiler

2 – 48

• User header files contain declarations for interfaces between the sourcefiles of your program.

2.5.4.3 Writing MacrosA macro is a name standing for a block of text that the preprocessorsubstitutes. Use the #define C preprocessor command to set the macrodefinition. When the macro definition has arguments, the block of text thepreprocessor substitutes can vary with each new set of arguments.

2.5.4.4 Compound Statements As MacrosWhen writing macros, it is useful to define a macro that expands into acompound statement. You can treat macro expansions as a function,making your source code easier to read and maintain. The following twocode segments define the macro SKIP_SPACES :

#define SKIP_SPACES (p, limit) \ #define SKIP_SPACES (p, limit)\{ register char *lim = (limit); \ do { register char *lim =(limit); \ while (p != lim) { \ while (p != lim) {\ if (*p++ != ‘ ‘) { \ if (*p++ != ‘ ‘) {\ p—; break; }}} p—; break; }}}\

while (0)

Enclosing the definition on the left within the do {…} while (0) pairtransforms the preprocessor output from a compound statement to asingle statement. This lets you treat the expanded macro as a function,shown on the right below (note that the do - while loop macro allowsa semicolon at the end):

if (*p != 0) if (*p != 0) SKIP_SPACES (p, lim) SKIP_SPACES (p, lim);else … else …

Page 63: C Tools manual

3

3 – 1

Assembly LanguageInterfacing

3.1 OVERVIEWThe G21 C Compiler supports two methods for interfacing C andAssembly language programs. G21 C is compatible with inline assemblycode (assembly instructions embedded within your C program using theasm() construct) and linked external assembly modules. This chaptercovers G21 compatibility requirements for your assembly code.

Figure 3.1 shows an overview of the C Runtime Environment. Assemblyroutines interfacing with C programs must be compatible with the CRuntime Environment. The C Runtime Environment is a set of rules thatthe G21 C Compiler uses to operate on ADSP-2100 Family processors. Theenvironment defines:

• Register use• Stack operation• Interface requirements

Figure 3.1 Assembly Language Interfacing Overview

Optional

C Runtime Environment

Assembly Interface Macros

C Program

Assembly Subroutine

Page 64: C Tools manual

3 Assembly LanguageInterfacing

3 – 2

Note: Figure 3.1 shows that C programs and Assembly Subroutines runwithin the C Runtime Environment. Your C programs can interface withAssembly Subroutine with or without Assembly Interface Macros.

This chapter also covers two types of support software that come withyour G21 C Compiler; these are the Runtime Header and AssemblyInterface Macros files. A Runtime Header is a system header file that setsprocessor specific features to be compatible with the C RuntimeEnvironment. Several Runtime Headers come with your developmentsoftware to support the ADSP-2100 Family of processors. AssemblyInterface Macros are macros that provide C to Assembly module interfaceservices.

3.2 C RUNTIME ENVIRONMENTThis section defines the C Runtime Environment with which your inlineassembly code and/or assembly modules must comply. The C RuntimeEnvironment only runs in MAC integer mode. The definition of the CRuntime Environment includes:

• G21 Reserved Registers• User Reserved Registers• Scratch Registers• Pointer Registers• C Runtime Stack• Type Double And Float Storage• Memory Segments• Arguments And Return Transfer• Function Call Return Address

Note: You should assemble modules that interface with a C program withrelease 3.0 (or higher) of the Assembler. Use the following assemblercommand line switches:

-cThis assembler command line switch causes the assembler to treat theinput file as case sensitive.

-sThis assembler command line switch causes the assembler not to checksemantics on multi-function instructions.

Page 65: C Tools manual

3Assembly LanguageInterfacing

3 – 3

3.2.1 G21 Reserved RegistersThe G21 C Runtime Environment reserves a set of DAG registers for itsown use. Table 3.1 lists these registers and the values the C RuntimeEnvironment expects to be in them. Do not modify these registers, exceptas noted in Table 3.1.

Register Value Modification RulesL0 0 Modify for temporary use, restore when doneL1 0 Modify for temporary use, restore when doneL4 0 Do Not ModifyL5 0 Modify for temporary use, restore when doneL6 0 Modify for temporary use, restore when doneL7 0 Modify for temporary use, restore when doneM1 1 Do Not ModifyM2 0 Modify for temporary use, restore when doneM6 0 Modify for temporary use, restore when done

Table 3.1 G21 Reserved Registers

Note: The interrupt dispatcher sets L0 , L1 , L5 , L6 , L7 , M2 , and M6to zero before calling an Interrupt Service Routine (ISR).

3.2.2 User Reserved RegistersThe -mreserved= register-list G21 command line parameter letsyou reserve registers for your inline assembly code or assembly languagemodules. Table 3.2 lists these registers. Note that you should reservecorresponding l and i registers; reserving an l register withoutreserving the corresponding i register can result in execution problems.Note that the C Runtime Library does not use these registers.

Register Value Modification Rules — Do not modify unlessreserved with -mreserved

I2 User Defined Modify for temporary use, restore when doneI3 User Defined Modify for temporary use, restore when doneL2 User Defined Modify for temporary use, restore when doneL3 User Defined Modify for temporary use, restore when done

Table 3.2 User Reserved Registers

Page 66: C Tools manual

3 Assembly LanguageInterfacing

3 – 4

3.2.3 Scratch RegistersThe G21 C Runtime Environment reserves a set of registers for use, whosecontents do not need to saved and restored. Table 3.3 lists these registers.

Register Value Modification RulesAF User Defined NoneAR User Defined NoneAY1 User Defined NoneI1 User Defined NoneI6 User Defined NoneM3 User Defined NoneM5 User Defined NoneMF User Defined NoneMR0 User Defined NoneMR1 User Defined NoneMR2 User Defined NoneMY1 User Defined NonePX User Defined NoneSB User Defined NoneSE User Defined NoneSI User Defined NoneSR0 User Defined NoneSR1 User Defined None

Table 3.3 Scratch Registers

3.2.4 C Runtime Stack RegistersThe G21 C Runtime Environment reserves a set of registers for controllingthe C Runtime Stack. These registers may be modified for stackmanagement, but must be saved and restored. Table 3.4 lists theseregisters.

Register Value Modification Rules

I4 stack pointer Modify for stack management, restorewhen done

M4 frame pointer Modify for stack management, restorewhen done

Table 3.4 Pointer Registers

Page 67: C Tools manual

3Assembly LanguageInterfacing

3 – 5

3.2.5 C Runtime StackThe G21 C Runtime Environment uses the C Runtime Stack for storage ofautomatic variables and the return address of the calling function. Thestack is managed by a frame pointer and a stack pointer.

A stack frame is a section of the stack used to hold information about thecurrent context of the C program. Information in the frame includes localvariables and/or parameters for the next function. The current stack frameis the stack space between the frame pointer and the stack pointer.

The frame pointer serves as a base for accessing memory in the stackframe. Routines reference locals, temporaries, and parameters by theiroffset from the frame pointer.

When the compiler creates a new stack frame (on function entry), it usesthe following steps:

• The parameters are passed. Those not placed in registers are pushedonto the C Runtime Stack, with the Stack Pointer adjusting.

• The Frame Pointer is saved.• The Frame Pointer is set to the Stack Pointer.• The Stack Pointer is advanced to a point beyond local and temporary

storage.

When the compiler discards the stack frame (on function exit), it uses thefollowing steps:

• The Stack Pointer is set to the Frame Pointer (which is the previousframe’s Stack Pointer).

• The Frame Pointer is restored to its value for the previous frame.• The Stack Pointer is reduced by the amount advanced when

parameters were pushed on function entry.

Your assembly language module is responsible for two C Runtime Stackoperations:

• Your module must correctly read the parameters passed on the stackon entry.

• Your module must leave the stack pointer in the I4 register and theframe pointer in the M4 register on exit.

Note: The next two sections “Arguments & Return Transfer” and“Function Call Return Address” provide details on these modulerequirements.

Page 68: C Tools manual

3 Assembly LanguageInterfacing

3 – 6

3.2.6 Arguments & Return TransferThe G21 C Runtime Environment uses a set of registers and the C RuntimeStack to transfer function parameters to assembly routines. The RuntimeEnvironment uses the C Runtime Stack to pass the following parameters:

• Pass third single word parameter (and all following parameters) offunctions prototyped without vararg

• Pass first multi-word parameter (and all following parameters) on thestack

• Pass the last named parameter (and all following parameters) forfunctions prototyped with varargs on the stack

Table 3.5 lists rules that G21 uses for passing parameters in registers tofunctions and the rules that your assembly code must use for returns.

Register Parameter Type Passed Or ReturnedAR Pass first single word parameterAY1 Pass second single word parameter———— ————AR Return int, char, short, and one-word structure

parametersSR Return float, double, long, and two-word structure

parameters. Place MSW in SR1 and LSW in SR0

Table 3.5 Parameter & Return Value Transfer Registers

3.2.7 Function Call Return AddressThe G21 C Runtime Environment requires that your assembly languagemodule store the return address while the module is active and jump tothe return address on completion. Your function should include thefollowing:

• During the function prologue, transfer the return address from the PCstack to the C Runtime Stack using the MR1 register.

• Conclude the function epilogue by removing the return address fromthe C Runtime Stack and doing an indirect jump to that address

Page 69: C Tools manual

3Assembly LanguageInterfacing

3 – 7

Listing 3.1 shows how the G21 C compiler translates a C function call toassembly language. The C Runtime Library calls___lib_save_large_frame and ___lib_restore_large_framestore the function return address on entry and provide the return addresson exit. Your assembly language modules should use a similar system forstoring and using the return address.

C Function Call

fxn1 (/* params */){

/* C code */}

Assembly Language Code

fxn1_: mr1=toppcstack; /* function prologue */ mr0=-1; /* function prologue */ call ___lib_save_large_frame; /* function prologue */ . . /* assembly code */ . mr0=-1; /* function epilogue */ jump ___lib_restore_large_frame; /* function epilogue */

Listing 3.1 Assembly Language Subroutine Return Address

Note: Interrupts use the PC stack for return address storage. Sinceinterrupts can be nested, be aware that in some situations more than onelocation of the PC stack may be in use.

Page 70: C Tools manual

3 Assembly LanguageInterfacing

3 – 8

3.2.8 Data Storage FormatsThe G21 C Runtime Environment uses the rules shown in Table 3.6 whenwriting data to memory.

Data Storage Formatdouble orfloat

struct Writes first value stored closer to address 0x0000, or proceeds toward address 0x3FFF with the rest.array

Table 3.6 Data Storage Formats

3.3 C RUNTIME HEADERThe Runtime Header is a system header file that sets processor specificfeatures to be compatible with the C Runtime Environment. Listing 3.2shows an ADSP-2101 Runtime Header.

.MODULE/ABS=0 ADSP2101_Runtime_Header;

.ENTRY ___lib_prog_term;

.EXTERNAL ___lib_setup_everything;

.EXTERNAL main_;

.EXTERNAL ___lib_int2_ctrl, ___lib_sp0x_ctrl,___lib_sp0r_ctrl;.EXTERNAL ___lib_int1_ctrl, ___lib_int0_ctrl,___lib_tmri_ctrl;__Reset_vector: CALL ___lib_setup_everything;

CALL main_; {Begin C program}___lib_prog_term: JUMP ___lib_prog_term;

NOP;__Interrupt2: JUMP ___lib_int2_ctrl;NOP;NOP;NOP;__Sport0_trans: JUMP ___lib_sp0x_ctrl;NOP;NOP;NOP;__Sport0_recv: JUMP ___lib_sp0r_ctrl;NOP;NOP;NOP;__Interrupt1: JUMP ___lib_int1_ctrl;NOP;NOP;NOP;__Interrupt0: JUMP ___lib_int0_ctrl;NOP;NOP;NOP;__Timer_interrupt: JUMP ___lib_tmri_ctrl;NOP;NOP;NOP;.ENDMOD;

Listing 3.2 The ADSP-2101 Runtime Header File — 2101_hdr.dsp

Writes MSW closer to address 0x0000, LSW closer toaddress 0x3FFF; IEEE single precision format. SeeFigure 3.2 for details.

Page 71: C Tools manual

3Assembly LanguageInterfacing

3 – 9

BITS 0 – 6, MOST SIGNIFICANT PART OF THE MANTISSA

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

0000000000000000

BITS 7 – 14, 8-BIT EXPONENT (BIASED BY +127)

BIT 15, SIGN BIT

BITS 0 – 15,LEAST SIGNIFICANT PART OF THE MANTISSA

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

0000000000000000 (LOWER WORD)

(UPPER WORD)

THIS EQUATES TO:

WHERE:

SIGN COMES FROM THE SIGN BIT

MANTISSA REPRESENTS FRACTIONAL PART OF THE MANTISSA (23 BITS), THE 1. IS ASSUMED IN THIS FORMAT

EXPONENT REPRESENTS THE EXPONENT (8 BITS)

-1 (SIGN) x 1.(MANTISSA) x 2 (EXPONENT - 127)

Figure 3.2 Floating-Point Number Storage Format

The Runtime Header shown in Listing 3.2 sets up the following hardwarefeatures:

• Sets up the interrupt table• Sets the DSP’s multiplier to integer multiply mode• Initializes the C Runtime Environment

Page 72: C Tools manual

3 Assembly LanguageInterfacing

3 – 10

3.4 C / ASSEMBLY INTERFACE SUPPORT MACROSThis section lists, describes, and shows syntax for the C / Assemblyinterface support macros in the asm_sprt.h system header file. Usethese macros for interfacing assembly language modules with C functions.

Note: Though the syntax for each macro will not change, the listing ofasm_sprt.h in this section may not be the most recent version. To seethe current version, check the asm_sprt.h file that came with yoursoftware package.

Table 3.7 lists the macros and shows the syntax for each. Following thetable is a brief description of each macro. Listing 3.3 shows the completeasm_sprt.h file.

function_entry;exit;leaf_entry;leaf_exit;readsfirst( register );register =readsnext;putsfirst= register ;putsnext= register ;getsfirst( register );register =getsnext;alter( number );save_reg;restore_reg;

Table 3.7 C / Assembly Interface Support Macros (From asm_sprt.h)

Note: The putsfirst , putsnext , getsfirst , and getsnextmacros can not be used directly with a DAG register. If you want to getthe contents of a DAG register with one of these macros, you must useindirect means. The following code segment demonstrates how to usethese macros with DAG registers:

ar=i6;putsfirst(ar);

function_entry;The preprocessor expands this macro into a series of assembly languagecommands that store the previous frame pointer and return address to theC Runtime Stack. This macro must be the first line in any non-leafassembly module.

Page 73: C Tools manual

3Assembly LanguageInterfacing

3 – 11

exit;The preprocessor expands this macro into a series of assembly languagecommands that restore the previous frame pointer and return addressfrom the C Runtime Stack; then jumps to the return address. This macromust be the last line in any non-leaf assembly module.

leaf_entry;The preprocessor expands this macro into a series of assembly languagecommands that store the previous frame pointer to the C Runtime Stack.This macro must be the first line of a leaf assembly module.

leaf_exit;The preprocessor expands this macro into a series of assembly languagecommands that restore the previous frame pointer from the C RuntimeStack; then jumps to the return address. This macro must be the last line inany leaf assembly module.

readsfirst( register );The preprocessor expands this macro into a series of assembly languagecommands that read the value off the top of the stack, writes the value toregister, and sets up for a read of the next stack entry with thereadsnext macro.

register =readsnext;The preprocessor expands this macro into a series of assembly languagecommands that continue the read process setup by the readsfirstmacro, by reading the next value off the top of the stack and writing it toregister.

putsfirst= register ;The preprocessor expands this macro into a series of assembly languagecommands that write the contents of register to the top of the stack andsets up for a write of the next stack entry with the putsnext macro.

putsnext= register ;The preprocessor expands this macro into a series of assembly languagecommands that continue the write process setup by the putsfirstmacro, by writing the next register to the top of the stack.

getsfirst( register );The preprocessor expands this macro into a series of assembly languagecommands that read the value off the top of the stack, writes the value toregister, and sets up for a read of the next stack entry with the getsnextmacro.

Page 74: C Tools manual

3 Assembly LanguageInterfacing

3 – 12

register =getsnext;The preprocessor expands this macro into a series of assembly languagecommands that continue the read process setup by the getsfirst macro, byreading the next value off the top of the stack and writing it to register.

alter(number);The preprocessor expands this macro into a series of assembly languagecommands that modify the stack pointer by the immediate value number.

save_reg;The preprocessor expands this macro into a series of assembly languagecommands that push the following registers onto the C Runtime Stack:AY0 , AX0 , AX1 , MY0 , MX0 , MX1 , I0 , M0 , I5 , I7 , and M7 .

restore_reg;The preprocessor expands this macro into a series of assembly languagecommands that pop the following registers off of the C Runtime Stack:AY0 , AX0 , AX1 , MY0 , MX0 , MX1 , I0 , M0 , I5 , I7 , and M7 .

#ifndef __ASM_SPRT_DEFINED#define __ASM_SPRT_DEFINED

#define function_entry \SI=M4;M4=I4;MR1=TOPPCSTACK;M5=-1;\DM(I4,M5)=SI;DM(I4,M5)=MR1

#define leaf_entry \SI=M4;M4=I4;M5=-1;DM(I4,M5)=SI

#define leaf_exit \I6=M4;SI=DM(I6,M6);I4=M4;M4=SI;RTS

#define exit \I6=M4;M5=-1;SI=DM(I6,M5);MR1=DM(I6,M6);\I4=M4;M4=SI;I6=MR1;JUMP (I6)

#define readsfirst(a) \M5=1;I6=1;MODIFY(I6,M4);a=DM(I6,M5)

#define readsnext \DM(I6,M5)

Page 75: C Tools manual

3Assembly LanguageInterfacing

3 – 13

#define putsfirst \M5=-1;DM(I4,M5)

#define putsnext \DM(I4,M5)

#define getsfirst(a) \M5=1;I6=1;MODIFY(I6,M4);a=DM(I6,M5)

#define getsnext \DM(I6,M5)

#define alter(x) \M5=x;MODIFY(I4,M5)

#define save_reg \DM(I4,M5)=AY0;DM(I4,M5)=AX0;DM(I4,M5)=AX1;\DM(I4,M5)=MY0;DM(I4,M5)=MX0;DM(I4,M5)=MX1;\SR0=I0;DM(I4,M5)=SR0;\SR0=M0;DM(I4,M5)=SR0;\SR0=I5;DM(I4,M5)=SR0;\SR0=I7;DM(I4,M5)=SR0;\SR0=M7;DM(I4,M5)=SR0

#define restore_reg \I6=I4;M5=1;MODIFY(I6,M5);\SR0=DM(I6,M5); M7=SR0;\SR0=DM(I6,M5); I7=SR0;\SR0=DM(I6,M5); I5=SR0;\SR0=DM(I6,M5); M0=SR0;\SR0=DM(I6,M5); I0=SR0;\MX1=DM(I6,M5); MX0=DM(I6,M5); MY0=DM(I6,M5);\AX1=DM(I6,M5); AX0=DM(I6,M5); AY0=DM(I6,M5);\M5=11;MODIFY(I4,M5)

#endif

Listing 3.3 asm_sprt.h — C / Assembly Interface Support Macros

Page 76: C Tools manual

3 Assembly LanguageInterfacing

3 – 14

3.5 C / ASSEMBLY INTERFACE CONVENTIONSTo link symbols between your C program and assembly module, use thefollowing conventions to name the symbols in your assembly languagemodules:

• Place a trailing underscore on all C language names and variables usedin your assembly language module

• Make C language names and variables used in you assembly languagemodule global in the C program and .external in the assemblylanguage module

• Make assembly language names and variables used in you C programexternal in the C program and .global in the assembly languagemodule

• Use the C language function name for you assembly language moduleas the .MODULE _module_name_ with leading and trailingunderscores

• Use the C language function name for you assembly language modulestartup label in the form module_name_: with a trailing underscore

Table 3.8 shows the C / Assembly interface naming conventions.

In The C Program In The Assembly Subroutinec_var /*declared global*/ .extern c_var_;c_func() .extern c_func_;extern int asm_var .global asm_var_extern asm_func() .MODULE/RAM _asm_func_;

.global asm_func_;asm_func_:

Table 3.8 Naming Conventions For C / Assembly Symbols

Page 77: C Tools manual

3Assembly LanguageInterfacing

3 – 15

3.6 C / ASSEMBLY INTERFACE PROGRAMMING EXAMPLESThis section shows examples of types of C / Assembly interfacing in orderof increasing complexity. The types of examples in this section are:

• Inline Assembly Language ( asm() ) Interfacing• External Assembly Subroutine Interfacing• Simple Assembly Routines• Assembly Routines With Parameters• Assembly Routines With Parameters And Return Values• Non-Leaf Assembly Routines

Note: Leaf assembly routines are routines that return without making anycalls. Non-Leaf assembly routines call other routines before returning tothe caller.

Note that you can use G21 to compile your C program and assemble yourassembly language modules. This ensures that the assembly of yourmodules will comply with the C Runtime Environment. The followingG21 command line, for example:

g21 my_prog.c my_sub1.dsp -a 21xx.ach -runhdr 2101_hdr.obj-mreserved=i2,l2,i3,l3 -Wall -g -save-temps

runs G21 with:

my_prog.cSelects a C language source file for your program.

my_sub1.dspSelects an assembly language module to be assembled and linked withyour program.

-a 21xx.achSelects an architecture file describing your DSP system.

-runhdr 2101_hdr.objSelects a runtime header to initialize the C Runtime Environment on yourDSP system.

-mreserved=i2,l2,i3,l3Selects a set of registers to be reserved for your assembly subroutine’s use.

Page 78: C Tools manual

3 Assembly LanguageInterfacing

3 – 16

-WallSelects a list of compiler warnings

-g -save-tempsSelects debugging information be output for CBUG

3.6.1 Inline Assembly Language (asm) Interfacing ExampleThe example in Listing 3.4 shows how to write a simple routine in ADSP-2100 family assembly code that properly interfaces to the C environment.It uses the asm() construct to pass inline assembly code to the compiler.

int i,j,k;main(){

k=add(i,j);}

add(int x, int y) /* function add() passes *//* param x in ar register */

{ /* and param y in ay1 register */ asm(“ar=ar+ay1;”); /* instruction adds param 1 */ } /* and 2, places result in ar. */

/* ar is return register */

Listing 3.4 Inline Assembly Language ( asm() ) Interfacing Example

3.6.2 External Assembly Subroutine Interfacing ExampleThis example includes two code modules designed to be linked togetherto create a single executable program for the ADSP-2101. The C functionmain() calls an assembly language routine named sum that returns thesum of its two arguments. The example illustrates how to pass argumentsto and from a subroutine and how to return a value.

The function main() is in Listing 3.5. The sum routine is passed twoarguments from main(): the first, a , an integer on the runtime stackand the second, &b , is pointer to an integer. The routine returns the sumof a and &b , while &b is added to a constant and passed back tomain() through the pointer.

Page 79: C Tools manual

3Assembly LanguageInterfacing

3 – 17

main(){ int a; int b; int c;

a=10; b=20;

c= sum(a, &b);}

Listing 3.5 External Assembly Subroutine Interfacing Example — Main C Module

Listing 3.7 shows the assembly code listing for the sum routine. Listing3.6 shows the equivalent C code for sum, to help you understand what theroutine does.

int sum(int x, int *y){

int j=10;int k;

k= x + *y;*y= *y + j;return(k);

}

Listing 3.6 External Assembly Subroutine Interfacing Example — Equivalent C Code For Assembly Language Module sum_

Page 80: C Tools manual

3 Assembly LanguageInterfacing

3 – 18

!Analog Devices ADSP-21xx.MODULE/RAM _sum_dsp_;.external ___lib_save_large_frame;.external ___lib_restore_large_frame;!gcc_compiled

.entry sum_;

sum_: mr1=toppcstack; mr0=-1; call ___lib_save_large_frame; i2=ay1; /* 2nd param ‘*y’ */ mr0=ar; /* 1st param x */ ax1=dm(i2,m2); ay0=ax1; ay1=10; ar=mr0+ay0; /* x + *y */ ar=ax1+ay1, my1=ar; /* *y + j */ ax1=ar; ar=my1; /* return in ar */ dm(i2,m2)=ax1; /* ‘*y’ adjusted */ mr0=-1; jump ___lib_restore_large_frame;.ENDMOD;

Listing 3.7 External Assembly Subroutine Interfacing Example — Assembly Language Module sum_

Note that the routine entry point label sum_ has an underscoreappended. Any assembly language routines that you write to interface tocompiled C code must have an underscore appended to the routine’sname because the compiler automatically does this to any C functionnames. The linker requires the underscore to properly link the assemblylanguage routines with compiled C modules.

The I4 register is the stack pointer: it always points to the next availablelocation on the stack. The M4 register contains the current frame pointervalue. Whenever a new function is called, it must push the previous framepointer and allocate a new frame buffer on the stack. Stack space mustalso be allocated for any local stack variables used in the routine. The codesegment shown below performs these operations. The number of stackvariables created is N–1; the variables are not initialized.

Page 81: C Tools manual

3Assembly LanguageInterfacing

3 – 19

si=m4; /* PSEUDO CODE SEGMENT */m4=i4; /* load new frame buffer */m5=-N; /* allocate space for N-1 */

/* local var and frame ptr */dm(i4,m5)=si; /* store old frame pointer */

The function protocol that G21 follows does this automatically for theuser. The mr1=toppcstack puts in mr1 the current program counter.mr0=-1 , is used to push values on the stack and save the compilerregisters as well as some DAG registers. Then the call is made to___lib_save_large_frame . This routine saves the frame pointer onthe stack, pushes a number of registers on to the stack, and returns readyto perform your function.

Local stack variables have a negative offset from the frame pointer. Thefollowing code segment stores the data register dreg in the K-th local stackvariable:

m7=-1; /* PSEUDO CODE SEGMENT */i6=-k; /* 1 ≤ k ≤ K */modify(i6,m4);dm(i6,m7)=dreg;

The next step is to retrieve the arguments passed by the calling function.Arguments have a positive offset from the current frame pointer; they areput on the runtime stack at the end of the previous frame. The callingfunction pushes the arguments onto the stack in reverse order. If Narguments are pushed, the last argument (PN) is pushed first and the firstargument (P1) is pushed last. The code segment below can be used tofetch argument Pn from the stack.

m5=1; /* PSEUDO CODE SEGMENT*/i6=n; /* 1 ≤ n ≤ N*/modify(i6,m4);dreg=dm(i6,m5);

Since M5= +1 , the index register I6 will point to argument Pn+1 afterthe third instruction executes. Note that arguments passed with theruntime stack are copies of existing values. The copies are removed by the

Page 82: C Tools manual

3 Assembly LanguageInterfacing

3 – 20

calling function immediately after the subroutine completes execution.

In sum_ , the first argument (a) was passed in AR . Since the secondargument ( &b ) is a pointer, it is copied into the index register I2 and theactual dereferenced value is stored in AX1 .

After the subroutine has completed its computation (or other function), thereturn value must be stored in AR ; the value returned by sum_ is thesum of its arguments. The other registers used by the routine must berestored from the stack.

The final step is to restore the stack to its previous state by popping theprevious frame pointer into M4 and setting the stack pointer ( I4 ) to thecorrect value. This may be done by the following code:

m5=1; /* PSEUDO CODE SEGMENT */i4=m4; /* set I4 to start of current frame*/si=dm(i4,m5); /* pop old frame ptr off stack */m4=si;

The final instruction of sum_ is a ___lib_restore_large_frame ,which handles the frame restoring code written above and returns controlto the calling function. When developing and testing code, you should set abreakpoint at the instruction following the call to the function and verifythat the stack was correctly restored.

Page 83: C Tools manual

3Assembly LanguageInterfacing

3 – 21

Listing 3.8 shows the compiled version of main.c (filename main.dsp), which consists of ADSP-2100 Family assembly language code.

! Analog Devices ADSP-21xx.MODULE/RAM _main_;.external ___lib_save_large_frame;.external ___lib_restore_large_frame;!gcc_compiled.external sum_;.entry main_;main_: mr1=toppcstack; mr0=-2; call ___lib_save_large_frame; i2=m4; m0=-2; modify (i2,m0); dm(i2,m2)=20; ar=10; /* “a” */ ay1=i2; /* “&b” */ call sum_; mr0=-2; jump ___lib_restore_large_frame;.ENDMOD;

Listing 3.8 External Assembly Subroutine Interfacing Example — Compiled Version Of Main C Module (main.dsp)

3.6.3 Simple Assembly Routines ExampleThe simplest set of assembly routines are those with no arguments and noreturn values. However, an assembly routine like that might wait for anexternal event, or delay a number of cycles available in a global variable.In such assembly routines, pay close attention to register usage. Theassembly routine must save and later restore any compiler registers thatare modified. Since a simple delay does not need many registers, you canuse scratch registers that do not need to be saved.

/* void delay ( void );An assembly language subroutine to delay N cycleswhere N is the value of the global variable del_cycle*/

#include <asm_sprt.h>;

(listing continues on next page)

Page 84: C Tools manual

3 Assembly LanguageInterfacing

3 – 22

.MODULE/RAM _delay_;

.external del_cycle_;

.global delay_;delay_:

function_entry; /* This must appear as the first line *//* in every assembly language routine */

ar=dm(del_cycle_); /* We use ar because it is a scratch *//* register and doesn’t need to be *//* preserved */

cntr= ar;do d_loop until ce;

d_loop: nop;exit; /* The exit macro is the last line */

/* executed in any assembly language *//* subroutine. The exit macro returns *//* control to the calling program */

.ENDMOD;

Listing 3.9 Simple Assembly Routines Example — delay_

Note that all symbols accessed from C contain a trailing underscore. Sincethe assembly routine name ( delay_ ) and the global variable( del_cycle_ ) are both available to C programs, they contain a trailingunderscore in the assembly code listing.

3.6.4 Assembly Routines With Parameters ExampleAnother, more complicated set of routines are those with parameters. Thefollowing example adds five inputs integers passed as parameters to thefunction and returns the sum of the parameters.

/* void add5 (int a, int b, int c, int d, int e);An assembly language subroutine that adds 5 numbers*/

#include <asm_sprt.h>

.MODULE/RAM _sum_of_5_;

.global add5_;

add5_: function_entry; /* The two parameters are passed */

/* in ar and ay1 respectively */ ar=ar+ay1; /* Add the 1st and 2nd parameter */

Page 85: C Tools manual

3Assembly LanguageInterfacing

3 – 23

/* the 3rd/4rth/5th parameters can *//* be accessed by readsfirst() and *//* subsequently readsnext */

readsfirst(ay1); /* Put the third parameter in ay1 */ ar=ar+ay1; /* Add the third parameter */ ay1=readsnext; /* Put the fourth parameter in ay1 */ ar=ar+ay1; /* Add the fourth parameter */ ay1=readsnext; /* Put the fifth parameter in ay1 */ ar=ar+ay1; /* Add the fifth parameter */ exit; /* Function return value in ar */

.ENDMOD;

Listing 3.10 Assembly Routines With Parameters Example — add5_

3.6.5 Assembly Routines With Parameters & Return Values Example

Another class of assembly routines are those that have parameters andreturn values. A simple example of such an assembly routine would be toadd two numbers and return their sum. Return values are stored in thear register.

/* int add2 (int a, int b);An assembly language subroutine that adds two numbersand returns sum*/

#include <asm_sprt.h>

.MODULE/RAM _add2_;

.global add2_;

add2_: function_entry; /* The first two parameters passed */

/* in ar and ay1 respectively *//* return values are always returned *//* the ar register */

ar=ar+ay1; /* Add the first and second parameter *//* then store in ar */

exit; /* Function return value in ar */.ENDMOD;

Page 86: C Tools manual

3 Assembly LanguageInterfacing

3 – 24

Listing 3.11 Assembly Routines With Parameters & Return Values Example — add2_

3.6.6 Non-Leaf Assembly Routines ExampleA more complicated example, one that calls another routine, would be tocompute the root mean square of two integer numbers ( z=(x^2+y^2)^(1/2) ).While it is simple to calculate a square-root in ADSP-2100 Family assemblylanguage, this example uses the square root function provided in the CRuntime Library. It illustrates how to call C functions from assemblylanguage.

/* float rms (int x, int y);An assembly language subroutine that returnsthe root mean square of parameters*/! Analog Devices ADSP-21xx.MODULE/RAM _ff_;.external ___lib_save_large_frame;.external ___lib_restore_large_frame;!gcc_compiled.external sqrtf_;.external __floatsisf_;.external __fixsfsi_;.entry rms_;rms_: mr1=toppcstack; mr0=-4; call ___lib_save_large_frame; i6=-4; mx1=ar; modify(i6,m4); my1=mx1; mr=mx1*my1 (ss),dm(i6,m6)=ay1; /* x^2 */ my1=dm(i6,m6); ax1=mr0; mr0=dm(i6,m6); mr=mr0*my1 (ss); /* y^2 */ ay1=mr0; m7=1; ar=ax1+ay1; /* (x^2) + (y^2) */ call __floatsisf_; /* change int to float */ i6=-3; /* for sqrt_ routine */ modify(i6,m4); dm(i6,m7)=sr1; m7=-1; m5=-1; dm(i6,m6)=sr0; mr0=dm(i6,m7);

Page 87: C Tools manual

3Assembly LanguageInterfacing

3 – 25

dm(i4,m5)=mr0; /* push LSW onto stack */ mr0=dm(i6,m6); dm(i4,m5)=mr0; /* push MSW onto stack */ call sqrtf_; /* Answer comes back */

/* from sqrt in sr1/sr0 *//* as it should for a *//* float There is no *//* need to re-put them *//* there for returning.*/

mr0=-4; jump ___lib_restore_large_frame;.ENDMOD;

Listing 3.12 Non-Leaf Assembly Routines Example — rms_

If a called function takes more than two single word parameters, theremaining parameters must be pushed on the stack and popped off thestack after the function call. The following function could call the add5routine (Listing 3.12) described above :

/* int calladd5 ( void ) ;An assembly language subroutine that calls another routinewithmore than 2 parameters. Here we add the numbers 1,2,3,4,5.*/

#include <asm_sprt.h>

.MODULE/RAM _calladd5_;

.external add5_;

.global calladd5_;

calladd5_: function_entry; ay1=2; /* the second parameter is sent in ay1 */ ar=3; /* the third parameter is held in ar */ putsfirst=ar; /* put third parameter onto stack */ ar=4; /* the fourth parameter is held in ar */ putsnext=ar; /* put fourth parameter in stack */ ar=5; /* the fifth parameter is is held in ar */ putsnext=ar; /* put fifth parameter in stack */ ar=1; /* the first parameter is sent in ar */ call add5_; alter(3); /* remove the two arg’s from the stack */ exit; /* function return value in ar */

.ENDMOD;

Page 88: C Tools manual

3 Assembly LanguageInterfacing

3 – 26

Listing 3.13 Non-Leaf Assembly Routines Example — calladd5_

Some functions need to make use of compiler registers. A variable must bestored in a compiler register whenever:

1. Its lifetime spans a function call or2. There are no more scratch registers available.

The following is an example of an assembly routine that performs anoperation on the elements of a C array:

/* void foo ( int function(int ), int *array, int length);An assembly language routine that operates on a C array */

#include <asm_sprt.h>

.MODULE/RAM _foo_;

.global foo_;

foo_: function_entry; readsfirst(si); /* read third argument, the number

of data points in the array */ my1=i3; putsnext=my1; /* We also need to save i3, */

/* for the same reason */ i6=ar; /* Read the first argument, */

/* the address of the function tocall */ i3=ay1; /* Read the second argument, */

/* the C array containing the *//* data to be processed */

cntr=si;do foo_loop until ce; /* Loop through data points */ ar=dm(i3,m2); /* Get data point from array, */

/* store in ar for parameter */ /* for function call */ call(i6); /* Call the function */

foo_loop: dm(i3,m1)=ar; /* store the return value back in */

/* the array */ my1=getsnext; /* restore the value of i3 */ i3 = my1; exit;.ENDMOD;

Listing 3.14 Non-Leaf Assembly Routines Example — foo_

Page 89: C Tools manual

A

A – 1

FSF General Public License

GNU GENERAL PUBLIC LICENSEVersion 2, June 1991

Copyright 1989, 1991 Free Software Foundation, Inc.675 Mass Ave, Cambridge, MA 02139, USA

Everyone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away yourfreedom to share and change it. By contrast, the GNU General PublicLicense is intended to guarantee your freedom to share and change freesoftware—to make sure the software is free for all its users. ThisGeneral Public License applies to most of the Free SoftwareFoundation’s software and to any other program whose authors committo using it. (Some other Free Software Foundation software is covered bythe GNU Library General Public License instead.) You can apply it toyour programs, too.

When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthis service if you wish), that you receive source code or can get itif you want it, that you can change the software or use pieces of itin new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbidanyone to deny you these rights or to ask you to surrender the rights.These restrictions translate to certain responsibilities for you if youdistribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whethergratis or for a fee, you must give the recipients all the rights thatyou have. You must make sure that they, too, receive or can get thesource code. And you must show them these terms so they know theirrights.

Page 90: C Tools manual

A FSF General Public License

A – 2

We protect your rights with two steps: (1) copyright the software, and(2) offer you this license which gives you legal permission to copy,distribute and/or modify the software.

Also, for each author’s protection and ours, we want to make certainthat everyone understands that there is no warranty for this freesoftware. If the software is modified by someone else and passed on, wewant its recipients to know that what they have is not the original, sothat any problems introduced by others will not reflect on the originalauthors’ reputations.

Finally, any free program is threatened constantly by softwarepatents. We wish to avoid the danger that redistributors of a freeprogram will individually obtain patent licenses, in effect making theprogram proprietary. To prevent this, we have made it clear that anypatent must be licensed for everyone’s free use or not licensed at all.

The precise terms and conditions for copying, distribution andmodification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION ANDMODIFICATION

1. This License applies to any program or other work which containsa notice placed by the copyright holder saying it may be distributedunder the terms of this General Public License. The “Program”, below,refers to any such program or work, and a “work based on the Program”means either the Program or any derivative work under copyright law:that is to say, a work containing the Program or a portion of it,either verbatim or with modifications and/or translated into anotherlanguage. (Hereinafter, translation is included without limitation inthe term “modification”.) Each licensee is addressed as “you.”

Activities other than copying, distribution and modification are notcovered by this License; they are outside its scope. The act ofrunning the Program is not restricted, and the output from the Programis covered only if its contents constitute a work based on theProgram (independent of having been made by running the Program).Whether that is true depends on what the Program does.

Page 91: C Tools manual

FSF General Public License

A – 3

A

2. You may copy and distribute verbatim copies of the Program’ssource code as you receive it, in any medium, provided that youconspicuously and appropriately publish on each copy an appropriatecopyright notice and disclaimer of warranty; keep intact all thenotices that refer to this License and to the absence of any warranty;and give any other recipients of the Program a copy of this Licensealong with the Program.

You may charge a fee for the physical act of transferring a copy, andyou may at your option offer warranty protection in exchange for a fee.

3. You may modify your copy or copies of the Program or any portionof it, thus forming a work based on the Program, and copy anddistribute such modifications or work under the terms of Section 1above, provided that you also meet all of these conditions:

a. You must cause the modified files to carry prominent noticesstating that you changed the files and the date of any change.

b. You must cause any work that you distribute or publish, that inwhole or in part contains or is derived from the Program or anypart thereof, to be licensed as a whole at no charge to all thirdparties under the terms of this License.

c. If the modified program normally reads commands interactivelywhen run, you must cause it, when started running for suchinteractive use in the most ordinary way, to print or display anannouncement including an appropriate copyright notice and anotice that there is no warranty (or else, saying that you providea warranty) and that users may redistribute the program underthese conditions, and telling the user how to view a copy of thisLicense. (Exception: if the Program itself is interactive butdoes not normally print such an announcement, your work basedon the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. Ifidentifiable sections of that work are not derived from the Program,and can be reasonably considered independent and separate works inthemselves, then this License, and its terms, do not apply to thosesections when you distribute them as separate works. But when youdistribute the same sections as part of a whole which is a work basedon the Program, the distribution of the whole must be on the terms ofthis License, whose permissions for other licensees extend to theentire whole, and thus to each and every part regardless of who wrote it.

Page 92: C Tools manual

A FSF General Public License

A – 4

Thus, it is not the intent of this section to claim rights or contestyour rights to work written entirely by you; rather, the intent is toexercise the right to control the distribution of derivative orcollective works based on the Program.

In addition, mere aggregation of another work not based on the Programwith the Program (or with a work based on the Program) on a volume ofa storage or distribution medium does not bring the other work underthe scope of this License.

4. You may copy and distribute the Program (or a work based on it,under Section 2) in object code or executable form under the terms ofSections 1 and 2 above provided that you also do one of the following:

a. Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms ofSections 1 and 2 above on a medium customarily used for softwareinterchange; or,

b. Accompany it with a written offer, valid for at least threeyears, to give any third party, for a charge no more than yourcost of physically performing source distribution, a completemachine-readable copy of the corresponding source code, to bedistributed under the terms of Sections 1 and 2 above on a mediumcustomarily used for software interchange; or,

c. Accompany it with the information you received as to the offerto distribute corresponding source code. (This alternative isallowed only for noncommercial distribution and only if youreceived the program in object code or executable form with suchan offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work formaking modifications to it. For an executable work, complete sourcecode means all the source code for all modules it contains, plus anyassociated interface definition files, plus the scripts used tocontrol compilation and installation of the executable. However, as aspecial exception, the source code distributed need not includeanything that is normally distributed (in either source or binaryform) with the major components (compiler, kernel, and so on) of theoperating system on which the executable runs, unless that componentitself accompanies the executable.

Page 93: C Tools manual

FSF General Public License

A – 5

A

If distribution of executable or object code is made by offeringaccess to copy from a designated place, then offering equivalentaccess to copy the source code from the same place counts asdistribution of the source code, even though third parties are notcompelled to copy the source along with the object code.

5. You may not copy, modify, sublicense, or distribute the Programexcept as expressly provided under this License. Any attemptotherwise to copy, modify, sublicense or distribute the Program isvoid, and will automatically terminate your rights under this License.However, parties who have received copies, or rights, from you underthis License will not have their licenses terminated so long as suchparties remain in full compliance.

6. You are not required to accept this License, since you have notsigned it. However, nothing else grants you permission to modify ordistribute the Program or its derivative works. These actions areprohibited by law if you do not accept this License. Therefore, bymodifying or distributing the Program (or any work based on theProgram), you indicate your acceptance of this License to do so, andall its terms and conditions for copying, distributing or modifyingthe Program or works based on it.

7. Each time you redistribute the Program (or any work based on theProgram), the recipient automatically receives a license from theoriginal licensor to copy, distribute or modify the Program subject tothese terms and conditions. You may not impose any furtherrestrictions on the recipients’ exercise of the rights granted herein.You are not responsible for enforcing compliance by third parties tothis License.

8. If, as a consequence of a court judgment or allegation of patentinfringement or for any other reason (not limited to patent issues),conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannotdistribute so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence youmay not distribute the Program at all. For example, if a patentlicense would not permit royalty-free redistribution of the Program byall those who receive copies directly or indirectly through you, thenthe only way you could satisfy both it and this License would be torefrain entirely from distribution of the Program.

Page 94: C Tools manual

A FSF General Public License

A – 6

If any portion of this section is held invalid or unenforceable underany particular circumstance, the balance of the section is intended toapply and the section as a whole is intended to apply in othercircumstances.

It is not the purpose of this section to induce you to infringe anypatents or other property right claims or to contest validity of anysuch claims; this section has the sole purpose of protecting theintegrity of the free software distribution system, which isimplemented by public license practices. Many people have madegenerous contributions to the wide range of software distributedthrough that system in reliance on consistent application of thatsystem; it is up to the author/donor to decide if he or she is willingto distribute software through any other system and a licensee cannotimpose that choice.

This section is intended to make thoroughly clear what is believed tobe a consequence of the rest of this License.

9. If the distribution and/or use of the Program is restricted incertain countries either by patents or by copyrighted interfaces, theoriginal copyright holder who places the Program under this Licensemay add an explicit geographical distribution limitation excludingthose countries, so that distribution is permitted only in or amongcountries not thus excluded. In such case, this License incorporatesthe limitation as if written in the body of this License.

10. The Free Software Foundation may publish revised and/or newversions of the General Public License from time to time. Such newversions will be similar in spirit to the present version, but may differ indetail to address new problems or concerns.

Each version is given a distinguishing version number. If the Programspecifies a version number of this License which applies to it and “anylater version’’, you have the option of following the terms and conditionseither of that version or of any later version published by the FreeSoftware Foundation. If the Program does not specify a version number ofthis License, you may choose any version ever published by the FreeSoftwareFoundation.

Page 95: C Tools manual

FSF General Public License

A – 7

A

11. If you wish to incorporate parts of the Program into other freeprograms whose distribution conditions are different, write to the authorto ask for permission. For software which is copyrighted by the FreeSoftware Foundation, write to the Free Software Foundation; wesometimes make exceptions for this. Our decision will be guided by thetwo goals of preserving the free status of all derivatives of our freesoftware and of promoting the sharing and reuse of software generally.

NO WARRANTY

12. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THEREIS NO WARRANTY FOR THE PROGRAM, TO THE EXTENTPERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISESTATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHERPARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUTNOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OFTHE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVEDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARYSERVICING, REPAIR OR CORRECTION.

13. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW ORAGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANYOTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THEPROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FORDAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL ORCONSEQUENTIAL DAMAGES ARISING OUT OF THE USE ORINABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITEDTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE ORLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OFTHE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVENIF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THEPOSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

Page 96: C Tools manual

A FSF General Public License

A – 8

Appendix: How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under theseterms.

To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelyconvey the exclusion of warranty; and each file should have at leastthe “copyright” line and a pointer to where the full notice is found.

one line to give the program’s name and a brief idea of what it does.Copyright (C) 19yy name of author

This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or(at your option) any later version.

This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.

You should have received a copy of the GNU General Public Licensealong with this program; if not, write to the Free SoftwareFoundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like thiswhen it starts in an interactive mode:

Gnomovision version 69, Copyright (C) 19yy name of authorGnomovision comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’.This is free software, and you are welcome to redistribute itunder certain conditions; type ‘show c’ for details.

Page 97: C Tools manual

FSF General Public License

A – 9

A

The hypothetical commands ‘show w’ and ‘show c’ should show theappropriate parts of the General Public License. Of course, thecommands you use may be called something other than ‘show w’ and‘show c’; they could even be mouse-clicks or menu items—whateversuits your program.

You should also get your employer (if you work as a programmer) or yourschool, if any, to sign a “copyright disclaimer” for the program, ifnecessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in the program‘Gnomovision’ (which makes passes at compilers) written by James Hacker.

signature of Ty Coon, 1 April 1989Ty Coon, President of Vice

This General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applicationswith the library. If this is what you want to do, use the GNU LibraryGeneral Public License instead of this License.

Contributors to GNU CC

In addition to Richard Stallman, several people have written partsof GNU CC.

• The idea of using RTL and some of the optimization ideas came fromthe program PO written at the University of Arizona by Jack Davidsonand Christopher Fraser. See “Register Allocation and ExhaustivePeephole Optimization’’, Software Practice and Experience 14 (9), Sept.1984, 857-866.

• Paul Rubin wrote most of the preprocessor.

• Leonard Tower wrote parts of the parser, RTL generator, and RTLdefinitions, and of the Vax machine description.

• Ted Lemon wrote parts of the RTL reader and printer.

Page 98: C Tools manual

A FSF General Public License

A – 10

• Jim Wilson implemented loop strength reduction and some otherloop optimizations.

• Nobuyuki Hikichi of Software Research Associates, Tokyo, contributedthe support for the Sony NEWS machine.

• Charles LaBrec contributed the support for the Integrated Solutions68020 system.

• Michael Tiemann of Cygnus Support wrote the front end for C++, aswell as the support for inline functions and instruction scheduling.Also the descriptions of the National Semiconductor 32000 series cpu,the SPARC cpu and part of the Motorola 88000 cpu.

• Jan Stein of the Chalmers Computer Society provided support forGenix, as well as part of the 32000 machine description.

• Randy Smith finished the Sun FPA support.

• Robert Brown implemented the support for Encore 32000 systems.

• David Kashtan of SRI adapted GNU CC to the Vomit-Making System(VMS).

• Alex Crain provided changes for the 3b1.

• Satz and Chris Hanson assisted in making GNU CC work on HP-UXfor the 9000 series 300.

• William Schelter did most of the work on the Intel 80386 support.

• Christopher Smith did the port for Convex machines.

• Paul Petersen wrote the machine description for the Alliant FX/8.

• Alain Lichnewsky ported GNU CC to the Mips cpu.

• Devon Bowen, Dale Wiles and Kevin Zachmann ported GNU CC totheTahoe.

• Jonathan Stone wrote the machine description for the Pyramidcomputer.

Page 99: C Tools manual

FSF General Public License

A – 11

A

• Gary Miller ported GNU CC to Charles River Data Systems machines.

• Richard Kenner of New York University wrote the machinedescriptions for the AMD 29000, the IBM RT PC, and the IBM RS/6000as well as the supportfor instruction attributes. He also made changesto better support RISC processors including changes to commonsubexpression elimination, strength reduction, function callingsequence handling, and condition code support, in addition togeneralizing the code for frame pointer elimination.

• Richard Kenner and Michael Tiemann jointly developed reorg.c, thedelay slot scheduler.

• Mike Meissner and Tom Wood of Data General finished the port to theMotorola 88000.

• Masanobu Yuhara of Fujitsu Laboratories implemented the machinedescription for the Tron architecture (specifically, the Gmicro).

• NeXT, Inc. donated the front end that supports the Objective Clanguage.

• James van Artsdalen wrote the code that makes efficient use ofthe Intel 80387 register stack.

• Mike Meissner at the Open Software Foundation finished the port tothe MIPS cpu, including adding ECOFF debug support.

• Ron Guilmette implemented the protoize and unprotoize tools, thesupport for Dwarf symbolic debugging information, and much of thesupport for System V Release 4. He has also worked heavily on theIntel 386 and 860 support.

• Torbjorn Granlund of the Swedish Institute of Computer Scienceimplemented multiply-by-constant optimization and better long longsupport, and improved leaf function register allocation.

Page 100: C Tools manual

A FSF General Public License

A – 12

Protect Your Freedom—Fight “Look And Feel”

This section is a political message from the League for ProgrammingFreedom to the users of GNU CC. It is included here as an expressionof support for the League on the part of the Free Software Foundation.

Apple and Lotus are trying to create a new form of legal monopoly: acopyright on a class of user interfaces. These monopolies would causeserious problems for users and developers of computer software andsystems. Xerox, too, has tried to make a monopoly for itself on windowsystems; their suit against Apple was thrown out on a technicality, butXerox has not said anything to indicate it wouldn’t try again.

Until a few years ago, the law seemed clear: no one could restrictothers from using a user interface; programmers were free to implementany interface they chose. Imitating interfaces, sometimes with changes,was standard practice in the computer field. The interfaces we knowevolved gradually in this way; for example, the Macintosh user interfacedrew ideas from the Xerox interface, which in turn drew on work done atStanford and SRI. 1-2-3 imitated VisiCalc, and dBase imitated adatabase program from JPL.

Most computer companies, and nearly all computer users, were happywith this state of affairs. The companies that are suing say it does notoffer “enough incentive” to develop their products, but they must haveconsidered it “enough” when they made their decision to do so. Itseems they are not satisfied with the opportunity to continue to competein the marketplace—not even with a head start.

If companies like Xerox, Lotus, and Apple are permitted to make lawthrough the courts, the precedent will hobble the software industry:

• Gratuitous incompatibilities will burden users. Imagine if eachcar manufacturer had to arrange the pedals in a different order.

• Software will become and remain more expensive. Users will be“locked in” to proprietary interfaces, for which there is no realcompetition.

• Large companies have an unfair advantage wherever lawsuits becomecommonplace. Since they can easily afford to sue, they can intimidatesmall companies with threats even when they don’t really have a case.

Page 101: C Tools manual

FSF General Public License

A – 13

A

• User interface improvements will come slower, since incrementalevolution through creative imitation will no longer be permitted.

• Even Apple, etc., will find it harder to make improvements ifthey can no longer adapt the good ideas that others introduce, forfear of weakening their own legal positions. Some users suggest thatthis stagnation may already have started.

• If you use GNU software, you might find it of some concern that userinterface copyright will make it hard for the Free Software Foundationto develop programs compatible with the interfaces that you alreadyknow.

To protect our freedom from lawsuits like these, a group of programmersand users have formed a new grass-roots political organization, theLeague for Programming Freedom.

The purpose of the League is to oppose new monopolistic practices suchas user-interface copyright and software patents; it calls for a returnto the legal policies of the recent past, in which these practices werenot allowed. The League is not concerned with free software as anissue, and not affiliated with the Free Software Foundation.

The League’s membership rolls include John McCarthy, inventor of Lisp,Marvin Minsky, founder of the Artificial Intelligence lab, Guy L. Steele, Jr.,author of well-known books on Lisp and C, as well as Richard Stallman,the developer of GNU CC. Please join and add your name to the list.Membership dues in the League are $42 per year for programmers,managers and professionals; $10.50 for students; $21 for others.

The League needs both activist members and members who only pay theirdues.

To join, or for more information, phone (617) 492-0023 or write to:

League for Programming Freedom1 Kendall Square #143P.O. Box 9171Cambridge, MA 02139

You can also send electronic mail to [email protected].

Page 102: C Tools manual

A FSF General Public License

A – 14

Here are some suggestions from the League for things you can do toprotect your freedom to write programs:

• Don’t buy from Xerox, Lotus or Apple. Buy from their competitors orfrom the defendants they are suing.

• Don’t develop software to work with the systems made by thesecompanies.

• Port your existing software to competing systems, so that youencourage users to switch.

• Write letters to company presidents to let them know their conductis unacceptable.

• Tell your friends and colleagues about this issue and how it threatensto ruin the computer industry.

• Above all, don’t work for the look-and-feel plaintiffs, and don’taccept contracts from them.

• Write to Congress to explain the importance of this issue.

House Subcommittee on Intellectual Property2137 Rayburn BldgWashington, DC 20515

Senate Subcommittee on Patents, Trademarks and CopyrightsUnited States SenateWashington, DC 20510

(These committees have received lots of mail already; let’s give themeven more.)

Express your opinion! You can make a difference.

Page 103: C Tools manual

2

X – 1

Index

G21 Command Line Switches–$ ....................................................... 2–39–a (architecture) ................................... 2–6–ansi (ANSI standard C compilation)

............................................... 2–6, 2–47–C (comments) ........................... 2–7, 2–39–c (compile only) .................................. 2–7–D (define macro) .... 2–7, 2–9, 2–13, 2–39–dD (document defined macros)

............................................... 2–7, 2–39–dM (document macros) ........... 2–7, 2–39–dN (document defined macro names)

............................................... 2–7, 2–39–E (end after preprocessing) .............. 2–7–fcond-mismatch (allow conditional expression mismatch) ..................... 2–8–finline-functions (force function inlining) ................................... 2–8, 2–24–fkeep-inline-functions (force keeping of inlined functions) ................... 2–8, 2–24–fno-asm (no assembler keywords) .. 2–8–fno-builtin (no builtin functions) ..... 2–8–fsigned-bitfields (make bitfields signed) ............................................... 2–9–fsigned-char (make char signed) ..... 2–9–fsyntax-only (just check syntax) ...... 2–9–funsigned-bitfields (make bitfields unsigned) .......................................... 2–9–funsigned-char (make char unsigned)

......................................................... 2–9–fwritable-strings (write strings) ....... 2–9–g (generate debugging information)

............................. 2–9, 2–46, 4–4, 4–13–H ....................................................... 2–39–I (include search directory)

......................... 2–10, 2–11, 2–39, 2–43–I– (include “file “ search directory)

................................... 2–10, 2–39, 2–43–imacros (introduce macros file)

............................................... 2–9, 2–39–L (library search directory) ............. 2–10–l (link library) ......................... 2–10, 2–11

–M (make only) .................................... 2–7–map (generate a memory map) ..... 2–10–MD (make document) ..................... 2–11–MM (make macros only) ................... 2–8–MMD (make macro document) ..... 2–11–mno-doloops (no do loops) ............ 2–10–mreserved (mark register(s) reserved)

............................................... 2–10, 3–3–nostdinc (no standard directory search for include) ................. 2–11, 2–39, 2–43–nostdlib (no standard library) ........ 2–11–o (output) .......................................... 2–11–P (pound prefix) ....................... 2–8, 2–39–pedantic (issue ANSI standard C compilation warnings) ........ 2–11, 2–39–pedantic-errors (issue ANSI standard C compilation warnings) ........ 2–12, 2–39–runhdr (runtime header)

................................... 2–12, 2–46, 3–15–S (stop after compilation) ............... 2–12–save-temps (save intermediate temporary files) .................... 2–12, 4–13–traditional (traditional C compilation)

............................................. 2–12, 2–47–traditional-cpp (traditional C preprocessing) ................................ 2–13–U (undefine macro)

............................. 2–7, 2–9, 2–13, 2–39–v (verbose) ........................................ 2–13–W (warnings extra) .......................... 2–13–w (warnings off) ............................... 2–13–Wall (all recommended warnings)

....................................................... 2–14–Wchar-subscripts (warnings for type char subscripts) .............................. 2–14–Wcomment (warnings for comment string) .............................................. 2–14–Werror (warnings as errors) ........... 2–14–Wformat ............................................ 2–14–Wimplicit (warnings for implicit declarations) ................................... 2–14–Wparentheses (warnings for omitted parentheses) .................................... 2–14

Page 104: C Tools manual

3 Index

X – 2

–Wreturn-type (warnings for int return types) ............................................... 2–15–Wswitch (warnings for switch index/ case mismatch) ............................... 2–15–Wtrigraphs (warnings for ANSI trigraphs) ........................................ 2–15–Wuninitialized.................................. 2–15–Wunused ........................................... 2–15

Defines__ADSP21XX__ .................................. 2–46__ADSP2100__ ................................... 2–46__ADSP2101__ ................................... 2–46__ADSP2105__ ................................... 2–46__ADSP2111__ ................................... 2–46__ADSP2150__ ................................... 2–46__ADSP2171__ ................................... 2–46__asm__ ......................................... 2–6, 2–8__BASE_FILE__.................................. 2–46__DATE__ ........................................... 2–46__DEBUG__ ................................ 2–9, 2–46__FILE__ .............................................. 2–46__GNUC__ .......................................... 2–46__INCLUDE_LEVEL__ ..................... 2–47__inline__ ...................................... 2–6, 2–8__LINE__............................................. 2–47__STDC__ ............................................ 2–47__STRICT_ANSI__ .................... 2–6, 2–47__TIME__ ............................................ 2–47__typeof__ ..................................... 2–6, 2–8__VERSION__ .................................... 2–47_exit ........................................................ 2–6

A – BAbort ...................................................... 2–6abs ......................................................... 2–8ADI_DSP ............................................... 2–4AF ......................................................... 3–4Alter(number) .................................... 3–12ANSI .............. 2–6, 2–11, 2–15, 2–46, 2–47AR ................................................. 3–4, 3–6Architecture description file .............. 2–6asm ............................ 2–6, 2–8, 2–24, 2–27,

2–29, 2–30, 3–16asm_sprt.h ........................................... 3–10Assembler ........................................... 2–32Assembler command line switches ... 3–2Assignments ............................. 2–19, 2–33Automatic variable ................. 2–12, 2–13,

2–15, 2–17, 2–34

AY1 ................................................ 3–4, 3–6Breakpoint .................... 4–3, 4–4, 4–6, 4–7,

4–8, 4–9, 4–10, 4–13, 4–14

C – DC Runtime Library ............. 3–3, 3–7, 3–24Case sensitive ....................................... 3–2Clobbered register ............................. 2–26Command line ..................... 2–2, 2–3, 2–6,

2–37, 2–38Concatenation ................ 2–13, 2–39, 2–44Conditional ....................... 2–8, 2–41, 2–42Constraint ........................................... 2–26Debugging ................ 2–9, 4–1, 4–12, 4–13dm ....................................................... 2–17

E – HEnvironment variables ................ 2–4, 2–6Exit ............................................... 2–6, 3–11fabs ......................................................... 2–8File extension ...... 2–2, 2–4, 2–5, 2–6, 2–37File type ......................................... 2–4, 2–6Frame pointer ........... 3–4, 3–5, 3–10, 3–11Free Software Foundation .................. 2–1Function_entry ................................... 3–10G21 reserved registers ......................... 3–3GCC ....................................................... 2–1getsfirst(register) ................................ 3–11Header files ..................... 2–11, 2–38, 2–47

I – MI1 ......................................................... 3–4I2 ............................................... 2–11, 3–3I3 ............................................... 2–11, 3–3I4 ......................................................... 3–4I6 ......................................................... 3–4Inline .......................... 2–6, 2–8, 2–12, 2–23Input operands ................................... 2–26Instruction template .......................... 2–25Interrupt ................................ 3–3, 3–7, 3–9L0 ......................................................... 3–3L1 ......................................................... 3–3L2 ............................................... 2–11, 3–3L3 ............................................... 2–11, 3–3L4 ......................................................... 3–3L5 ......................................................... 3–3L6 ......................................................... 3–3L7 ......................................................... 3–3Labs ........................................................ 2–8

Page 105: C Tools manual

3Index

X – 3

leaf_entry ............................................ 3–11leaf_exit ............................................... 3–11M1 ......................................................... 3–3M2 ......................................................... 3–3M3 ......................................................... 3–4M4 ......................................................... 3–4M5 ......................................................... 3–4M6 ......................................................... 3–3Map file ............................................... 2–10memcmp ............................................... 2–8memcpy ................................................. 2–8MF ......................................................... 3–4MR0 ........................................................ 3–4MR1 ........................................................ 3–4MR2 ........................................................ 3–4MY1 ........................................................ 3–4

N –PNon-leaf assembly routines.............. 3–15Notation conventions .......................... 1–2Operand constraints .......................... 2–26Output operands ................................ 2–26Parameter and return value transfer registers ............................................. 3–6pm ....................................................... 2–17putsfirst=register ............................... 3–11putsnext=register ............................... 3–11PX ......................................................... 3–4

R – Ureadsfirst(register) ............................. 3–11register=getsnext ................................ 3–12register=readsnext ............................. 3–11restore_reg .......................................... 3–12Runtime header ................ 2–12, 2–46, 3–2save_reg............................................... 3–12SB ......................................................... 3–4SE ......................................................... 3–4search path for include files ............. 2–10search path for library files .............. 2–10SI ......................................................... 3–4sqrt ......................................................... 2–8SR ......................................................... 3–6SR0 ................................................. 3–4, 3–6SR1 ................................................. 3–4, 3–6Stack pointer ....................... 3–4, 3–5, 3–12strcmp .................................................... 2–8strcpy ..................................................... 2–8string conversion ......................... 2–39, 44strlen ...................................................... 2–8System builder ..................................... 2–6System header file ................... 2–11, 2–47,

....................................... 3–2, 3–8, 3–10Template ............................................. 2–25Translation process .............................. 2–1typeof ......................... 2–6, 2–8, 2–12, 2–22User header files ................................ 2–48User reserved registers ....................... 3–3

Page 106: C Tools manual

3 Index

X – 4