Summary of Contents for Texas Instruments TMS320C2x
Page 1
TMS320C2x/C2xx/C5x Optimizing C Compiler User’s Guide Literature Number: SPRU024E August 1999 Printed on Recycled Paper...
Page 2
IMPORTANT NOTICE Texas Instruments and its subsidiaries (TI) reserve the right to make changes to their products or to discontinue any product or service without notice, and advise customers to obtain the latest version of relevant information to verify, before placing orders, that information being relied on is current and complete. All products are sold subject to the terms and conditions of sale supplied at the time of order acknowledgement, including those pertaining to warranty, patent infringement, and limitation of liability.
Page 3
Preface Read This First About This Manual The TMS320C2x/C2xx/C5x Optimizing C Compiler User’s Guide tells you how to use these compiler tools: Compiler Source interlist utility Optimizer Parser Library-build utility The TMS320C2x/C2xx/C5x C compiler accepts American National Standards Institute (ANSI) standard C source code and produces assembly language source code for the TMS320C2x/C2xx/C5x devices.
Page 4
How to Use This Manual / Notational Conventions How to Use This Manual The goal of this book is to help you learn how to use the Texas Instruments C compiler tools specifically designed for the TMS320C2x/C2xx/C5x devices. This book is divided into three distinct parts: Introductory information, consisting of Chapter 1, provides an overview of the TMS320C2x/C2xx/C5x development tools.
Page 5
Options are preceded by a hyphen. Related Documentation From Texas Instruments The following books describe the TMS320C2x/C2xx/C5x and related support tools. To obtain a copy of any of these TI documents, call the Texas Instru- ments Literature Response Center at (800) 477−8924. When ordering, identify the book by its title and literature number (located on the bottom-right corner of the back cover).
Page 6
TMS320C2x Software Development System Technical Reference (liter- ature number SPRU072) provides specific application and design in- formation for using the TMS320C2x Software Development System (SWDS) board. TMS320C5x Software Development System Technical Reference (liter- ature number SPRU066) provides specific application and design in- formation for using the TMS320C5x Software Development System (SWDS) board.
Page 7
MS-DOS is a registered trademark of Microsoft Corp. PC-DOS is a trademark of International Business Machines Corp. SPARC is a trademark of SPARC International, Inc. Sun-OS and Sun Workstation are trademarks of Sun Microsystems, Inc. XDS is a trademark of Texas Instruments Incorporated. Read This First...
TMS320 family of high-performance CMOS microprocessors optimized for digital signal processing applications. The TMS320C2x/C2xx/C5x DSPs are supported by a set of software develop- ment tools, which includes an optimizing C compiler, an assembler, a linker, an archiver, a software simulator, a full-speed emulator, and a software devel- opment board.
Software Development Tools Overview 1.1 Software Development Tools Overview Figure 1−1 illustrates the TMS320C2x/C2xx/C5x software development flow. The shaded portion of the figure highlights the most common path of software development for C language programs. The unshaded portions represent pe- ripheral functions that enhance the development process.
Page 19
Software Development Tools Overview The following list describes the tools that are shown in Figure 1−1. The C compiler accepts C source code and produces TMS320C2x, TMS320C2xx, or TMS320C5x assembly language source code. A shell program, an optimizer, and an interlist utility are included in the compiler package.
Page 20
Tools User’s Guide for more information about how to use the cross-refer- ence lister. The main product of this development process is a module that you can execute on a TMS320C2x/C2xx/C5x device. You can use one of several debugging tools to refine and correct your code. Available products include:...
The following list describes key characteristics of the compiler: ANSI-standard C The TMS320C2x/C2xx/C5x compiler fully conforms to the ANSI C stan- dard as defined by the ANSI specification and described in the second edi- tion of Kernighan and Ritchie’s The C Programming Language (K&R). The ANSI C standard includes extensions to C that provide maximum portability and increased capability.
Page 22
The compiler uses an optimization pass that employs several advanced techniques for generating efficient, compact code from C source. General optimizations can be applied to any C code, and TMS320C2x/C2xx/C5x- specific optimizations take advantage of the TMS320C2x/C2xx/C5x architecture. For more information about the C compiler’s optimization techniques, see Chapter 3, Optimizing Your Code.
Translating your source program into code that the TMS320C2x/C2xx/C5x can execute is a multistep process. You must compile, assemble, and link your source files to create an executable object file. The TMS320C2x/C2xx/C5x package contains a special shell program that enables you to execute all of these steps with one command.
About the Shell Program 2.1 About the Shell Program The compiler shell program (dspcl) lets you compile, assemble, and optionally link in one step. The shell runs one or more source modules through the following: The compiler, which includes the parser, optimizer, and code generator, accepts C source code and produces ’C2x, ’C2xx, ’C5x, assembly lan- guage source code.
COFF file files For a complete description of the assembler and the linker, see the TMS320C2x/C2xx/C5x Assembly Language Tools User’s Guide. For informa- tion about invoking the compiler tools individually, see section 2.9, Invoking the Tools Individually, on page 2-39.
Invoking the Compiler Shell 2.2 Invoking the Compiler Shell To invoke the compiler shell, enter: dspcl [options] filenames [−z] [linker options] [object files]] dspcl is the command that runs the compiler and the assembler. options affect the way the shell processes input files. filenames are one or more C source files, assembly source files, or object files.
Page 27
−q option: $ dspcl symtab [symtab] TMS320C2x/2xx/5x ANSI C Compiler Version X.XX Copyright (c) 1987−1995, Texas Instruments Incorporated ”symtab.c”: ==> main ”symtab.c”: ==> lookup TMS320C2x/2xx/5x ANSI C Codegen Version X.XX Copyright (c) 1987−1995, Texas Instruments Incorporated ”symtab.c”: ==>...
Changing the Compiler’s Behavior With Options 2.3 Changing the Compiler’s Behavior With Options Options control the operation of both the shell and the programs it runs. This section provides a description of option conventions and an option summary table. It also provides detailed descriptions of the most frequently used op- tions, including options used for type-checking and assembling.
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (a) Options that control the compiler shell Option Effect Page(s) −@filename Interprets contents of a file as one extension to the 2-14 command line −c Disables linking (negate −z) 2-14, −d name [=def ] Predefines name...
Page 30
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (Continued) (c) Options that change the default file extensions Option Effect Page −eaextension Sets default extension for assembly files 2-17 −eoextension Sets default extension for object files 2-17 (d) Options that specify directories Option Effect Page...
Page 31
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (Continued) (g) Options that control the parser Option Effect Page −p? Enables trigraph expansion 2-27 −pe Treats code-E errors as warnings 2-37 −pf Generates function prototype listing file 2-27 −pk Allows K&R compatibility −pl...
Page 32
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (Continued) (i) Options that control the assembler Option Effect Page −aa Enables absolute listing 2-20 −adname Defines variables from the command line 2-20 −ahcfilename Copies filename before any source statements from 2-20 the input file are assembled −ahifilename...
Page 33
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (Continued) (j) Options that control optimizations Option Effect Page −o0 Optimizes register usage −o1 Uses −o0 optimizations and optimizes locally −o2 or −o Uses −o1 optimizations and optimizes globally −o3 Uses −o2 optimizations and optimizes the file −oe...
Page 34
Changing the Compiler’s Behavior With Options −os Interlists optimizer comments with assembly state- 3-13 ments 2-12...
Page 35
Changing the Compiler’s Behavior With Options Table 2−1. Shell Options Summary (Continued) (k) Options that control the linker Options Effect Page −a Generates absolute executable output −ar Generates relocatable executable output −b Disables merge of symbolic debugging information 4-6 −c Autoinitializes variables at run time −cr Initializes variables at reset...
Changing the Compiler’s Behavior With Options 2.3.1 Frequently Used Options −@ filename Appends the contents of a file to the command line. You can use this option to avoid limitations on command line length imposed by the host operating system. Use a # or j; at the beginning of a line in the command file to include comments.
Page 37
Changing the Compiler’s Behavior With Options −s Invokes the interlist utility, which interweaves optimizer comments or C source with assembly source. If the optimizer is invoked (−on option), optimizer comments are interlisted with the assembly language output of the compiler. If the optimizer is not invoked, C source state- ments are interlisted with the assembly language output of the compiler, which allows you to inspect the code gener- ated for each C statement.
Changing the Compiler’s Behavior With Options 2.3.2 Specifying Filenames The input files that you specify on the command line can be C source files, assembly source files, or object files. The shell uses filename extensions to determine the file type. Extension File Type .c or none (.c is assumed)
Changing the Compiler’s Behavior With Options 2.3.4 Changing How the Shell Program Interprets and Names Extensions (−ea and −eo Options) You can use options to change how the shell program interprets filename ex- tensions and names the extensions of the files that it creates. The −ea and −eo options must precede the filenames they apply to on the command line.
Changing the Compiler’s Behavior With Options 2.3.6 Options That Overlook ANSI C Type Checking Following are options that you can use to overlook some of the strict ANSI C type checking on your code: −tf Overlooks type checking on redeclarations of prototyped func- tions.
Changing the Compiler’s Behavior With Options 2.3.7 Run-Time-Model Options −ma Assumes variables are aliased. The compiler assumes that pointers may alias (point to) named variables and aborts register optimizations when an assignment is made through a pointer. −mb Disables the noninterruptible RPTK instruction for moving structures.
Changing the Compiler’s Behavior With Options 2.3.8 Options That Control the Assembler Following are assembler options that you can use with the shell: −aa Invokes the assembler with the −a assembler option, which creates an absolute listing. An absolute listing shows the ab- solute addresses of the object code.
Changing the Compiler’s Behavior With Environment Variables 2.4 Changing the Compiler’s Behavior With Environment Variables You can define environment variables that set certain software tool parame- ters you normally use. An environment variable is a special system symbol that you define and associate to a string in your system initialization file. The compiler uses this symbol to find or obtain certain types of information.
Changing the Compiler’s Behavior With Environment Variables In the following examples, each time you run the compiler shell, it runs the linker. Any options following −z on the command line or in C_OPTION are passed to the linker. This enables you to use the C_OPTION environment vari- able to specify default compiler and linker options and then specify additional compiler and linker options on the shell command line.
The shell program allows you to control the preprocessor with macros and various other preprocessor directives. This section describes specific features that control the TMS320C2x/C2xx/ C5x preprocessor. Refer to Section A12 of K&R for a general description of C preprocessing.
Controlling the Preprocessor You can use the names listed in Table 2−2 the same manner as any other de- fined name. For example: printf ( ”%s %s” , _ _TIME _ _ , _ _ DATE _ _); translates to a line such as: printf (”%s %s”...
Controlling the Preprocessor 2.5.3 Changing the #include File Search Path With the −i Option The −i option names an alternative directory that contains #include files. The format of the −i option is: −i directory1 [−i directory2 ...] You can use up to 32 −i options per invocation of the compiler; each −i option names one directory.
Controlling the Preprocessor 2.5.4 Generating a Preprocessed Listing File (−pl Option) The −pl option allows you to generate a preprocessed version of your source file with a .pp extension. The compiler’s preprocessing functions perform the following on the source file: Each source line ending in backslash (\ ) is joined with the following line.
Controlling the Preprocessor 2.5.5 Creating Custom Error Messages with the #error and #warn Directives The standard #error preprocessor directive forces the compiler to issue a diagnostic message and halt compilation. The compiler extends the #error di- rective with a #warn directive. The #warn directive forces a diagnostic mes- sage but does not halt compilation.
Using Inline Function Expansion 2.6 Using Inline Function Expansion When an inline function is called, the C source code for the function is inserted at the point of the call. This is known as inline function expansion. Inline func- tion expansion is advantageous in short functions for the following reasons: It saves the overhead of a function call.
Using Inline Function Expansion 2.6.2 Controlling Inline Function Expansion (−x Option) The −x option controls the definition of the _INLINE preprocessor symbol and some types of inline function expansion. There are three levels of expansion: −x0 Causes no definition-controlled inline expansion. This option overrides the default expansions of the intrinsic operator functions, but it does not override the inline function expansions described in section 3.5, Automatic Inline Expansion (−oisize...
Page 52
Using Inline Function Expansion For a function to be eligible for inlining: The function must be declared with the inline keyword, or The optimizer must be invoked using the −o3 switch, and The function is very small (controlled by the −oi switch), and The function is declared before it is called A function may be disqualified from inlining if it: Returns a struct or union...
Page 53
Using Inline Function Expansion 2.6.3.1 Declaring a Function as Inline Within a Module By declaring a function as inline within a module (with the inline keyword), you can specify that the function is inlined within that module. A global symbol for the function is created (code is generated), but the function is inlined only with- in the module where it is declared as inline.
Using Inline Function Expansion 2.6.4 The _INLINE Preprocessor Symbol The _INLINE preprocessor symbol is defined (and set to 1) if you invoke the parser (or compiler shell utility) with the −x2 (or −x) option. It allows you to write code so that it runs whether or not the optimizer is used. It is used by standard header files included with the compiler to control the declaration of standard C run-time functions.
Using the Interlist Utility 2.7 Using the Interlist Utility The compiler tools include a utility that interlists C source statements into the assembly language output of the compiler. The interlist utility enables you to inspect the assembly code generated for each C statement. The interlist utility behaves differently depending on whether or not the optimizer is used, and de- pending on which options you specify.
Using the Interlist Utility Example 2−2. An Interlisted Assembly Language File ;>>>> main() ;>>>> int i, j; ******************************************* * FUNCTION DEF : _main ******************************************* _main: AR0,*+ AR1,* LARK AR0,3 AR0,*0+,AR2 ;>>>> i += j; LARK AR2,1 *− SACL ;>>>> j = i + 123; ADDK SACL *,AR1...
Understanding and Handling Compiler Errors 2.8 Understanding and Handling Compiler Errors One of the compiler’s primary functions is to detect and report errors in the source program. When the compiler encounters an error in your program, it displays a message in the following format: “file.c”, line n: [ECODE] error message “file.c”...
Understanding and Handling Compiler Errors Table 2−3. Example Error Messages Error Level Example Error Message Code W ”file.c”, line 42:[W029] extra text after preprocessor directive ignored Code E ”file.c”, line 66: [E055] illegal storage class for function ’f’ Code F ”file.c”, line 71: [F0108] structure member ’a’...
Understanding and Handling Compiler Errors Table 2−4. Selecting a Level for the −pw Option If you want to… Use option Disable all warning messages. This level is useful when you are −pw0 aware of the condition causing the warning and consider it innocuous. Enable serious warning messages.
Invoking the Tools Individually 2.9 Invoking the Tools Individually The TMS320C2x/C2xx/C5x C compiler offers you the versatility of invoking all of the tools at once using dspcl, or invoking each tool individually. To satisfy a variety of applications, you can invoke the compiler (parser, optimizer, and code generator), the assembler, and the linker as individual programs.
TMS320C1x/C2x/C2xx/C5x Assembly Language Tools User’s Guide. 2.9.1 Invoking the Parser The first step in compiling a TMS320C2x/C2xx/C5x C program is to invoke the C parser. The parser reads the source file, performs preprocessing functions, checks syntax, and produces an intermediate file that can be used as input for the code generator.
You can use any other options on this final pass. 2.9.3 Invoking the Optimizer Optimizing is an optional second step in compiling a TMS320C2x/C2xx/C5x C program. After parsing a C source file, you can choose to process the inter- mediate file with the optimizer. The optimizer improves the execution speed and reduces the size of C programs.
Invoking the Tools Individually To invoke the optimizer, enter: dspopt [input file [output file ]] [options] dspopt is the command that invokes the optimizer. input file names the intermediate file produced by the parser. The optimizer assumes that the extension is .if. If you do not speci- fy an input file, the optimizer prompts you for one.
5.6, Creating Global Register Variables, on page 5-10, for more information. 2.9.4 Invoking the Code Generator The third step in compiling a TMS320C2x/C2xx/C5x C program is to invoke the C code generator. The code generator converts the intermediate file pro- duced by the parser into an assembly language source file.
Suppress progress messages (quiet) −r −mr List register use information −s −ms Optimize for space instead of for speed −v25 −v25 Enable use of TMS320C2x instructions −v2xx −v2xx Enable use of TMS320C2xx instructions −v50 −v50 Enable use of TMS320C5x instructions −x −mx Avoid ’C5x silicon bugs...
Invoking the Tools Individually 2.9.5 Invoking the Interlist Utility The fourth step in compiling a TMS320C2x/C2xx/C5x C program is optional. After you have compiled a program, you can run the interlist utility as a stand- alone program. To run the interlist utility from the command line, the syntax is:...
Chapter 3 Optimizing Your Code The compiler tools include an optimization program that improves the execution speed and reduces the size of C programs by performing such tasks as simplifying loops, software pipelining, rearranging statements and expres- sions, and allocating variables into registers. This chapter describes how to invoke the optimizer and describes which opti- mizations are performed when you use it.
Using the C Compiler Optimizer Using the C Compiler Optimizer The optimizer runs as a separate pass between the parser and the code generator. Figure 3−1 illustrates the execution flow of the compiler with stand- alone optimization. Figure 3−1. Compiling a C Program With the Optimizer Code C source Parser...
Using the C Compiler Optimizer −o3 Performs all −o2 optimizations, plus: Removes all functions that are never called Simplifies functions with return values that are never used Inlines calls to small functions Reorders function declarations so that the attributes of called func- tions are known when the caller is optimized Propagates arguments into function bodies when all calls pass the same value in the same argument position...
Using the −o3 Option 3.2 Using the −o3 Option The −o3 option instructs the compiler to perform file-level optimization. You can use the −o3 option alone to perform general file-level optimization, or you can combine it with other options to perform more specific optimizations. The options listed in Table 3−1 work with −o3 to perform the indicated optimization: Table 3−1.
Using the −o3 Option 3.2.2 Creating an Optimization Information File (−onn Option) When you invoke the optimizer with the −o3 option, you can use the −on option to create an optimization information file that you can read. The number following the −on denotes the level (0, 1, or 2). The resulting file has an .nfo extension.
Performing Program-Level Optimization (−pm and −o3 Options) 3.3 Performing Program-Level Optimization (−pm and −o3 Options) You can specify program-level optimization by using the −pm option with the −o3 option. With program-level optimization, all of your source files are compiled into one intermediate file called a module. The module moves to the optimization and code generation passes of the compiler.
Performing Program-Level Optimization (−pm and −o3 Options) Table 3−4. Selecting a Level for the −op Option If your module … Use this option Has functions that are called from other modules and global vari- −op0 ables that are modified in other modules Does not have functions that are called by other modules but has −op1 global variables that are modified in other modules...
Performing Program-Level Optimization (−pm and −o3 Options) 3.3.2 Optimization Considerations When Mixing C and Assembly If you have any assembly functions in your program, you need to exercise cau- tion when using the −pm option. The compiler recognizes only the C source code and not any assembly code that might be present.
Performing Program-Level Optimization (−pm and −o3 Options) Situation Your application consists of C source code and assembly source code. The assembly functions are interrupt service routines that call C functions; the C functions that the assem- bly functions call are never called from C. These C functions act like main: they function as entry points into C.
Special Considerations When Using the Optimizer 3.4 Special Considerations When Using the Optimizer The optimizer is designed to improve your ANSI-conforming C programs while maintaining their correctness. However, when you write code for the optimizer, you should note the following special considerations to ensure that your pro- gram performs as you intend.
Use Caution With asm Statements in Optimized Code 3.4.3 Use Caution When Accessing Aliased Variables Aliasing occurs when you can access a single object in more than one way, such as when two pointers point to the same object or when a pointer points to a named object.
Automatic Inline Expansion (−oi Option) 3.5 Automatic Inline Expansion (−oi Option) The optimizer automatically inlines small functions when it is invoked with the −o3 option. A command-line option, −oisize, specifies the size of the functions inlined. When you use −oi, specify the size limit for the largest function to be inlined.
Using the Interlist Utility With the Optimizer Using the Interlist Utility With the Optimizer / Debugging Optimized Code 3.6 Using the Interlist Utility With the Optimizer You control the output of the interlist utility when running the optimizer (the −on option) with the −os and −ss options.
What Kind of Optimization Is Being Performed? 3.8 What Kind of Optimization Is Being Performed? The TMS320C2x/C2xx/C5x C compiler uses a variety of optimization tech- niques to improve the execution speed of your C programs and to reduce their size. Optimization occurs at various levels throughout the compiler.
With the optimizer, the compiler can detect loops con- trolled by counters and generate them using the efficient repeat forms. The it- eration count can be either a constant or an expression. For the TMS320C2x, which does not have a repeat block instruction, the compiler allocates an AR as the loop counter and implements the loop with a BANZ instruction.
What Kind of Optimization Is Being Performed? Example 3−2. Delayed Branch, Call, and Return Instructions main() int i0, i1; while (input(&i0) && input(&i1)) process(i0, i1); TMS320C2x/C2xx/C5x C Compiler Output: _main: AR0,*+ ; function prolog POPD ; save AR0 and return address AR1,* ;...
What Kind of Optimization Is Being Performed? 3.8.5 Algebraic Reordering / Symbolic Simplification / Constant Folding For optimal evaluation, the compiler simplifies expressions into equivalent forms requiring fewer instructions or registers. For example, the expression (a + b) − (c + d) takes six instructions to evaluate; it can be optimized to ((a + b) −...
Loops controlled by incrementing a counter are written as TMS320C2x/C2xx/C5x repeat blocks or by using efficient decrement-and- branch instructions. Induction variable analysis and strength reduction together often remove all references to your loop control variable, allowing it to be eliminated entirely.
Chapter 4 Linking C Code The C compiler and assembly language tools provide two methods for linking your programs: You can compile individual modules and link them together. This method is especially useful when you have multiple source files. You can compile and link in one step by using dspcl. This method is useful when you have a single source module.
Table 4−1. Run-Time-Support Source Libraries Library Name Library Source Contents rts25.lib TMS320C2x runtime support rts2xx.lib TMS320C2xx runtime support rts50.lib TMS320C5x runtime support...
Page 94
The linker uses a default allocation algorithm to allocate your program into memory. You can use the MEMORY and SECTIONS directives in the linker command file to customize the allocation process. For more information, see the TMS320C2x/C2x/C2xx/C5x Assembly Language Tools User’s Guide. Linking C Code...
Invoking the Linker With the Compiler Shell (−z Option) 4.2 Invoking the Linker With the Compiler Shell (−z Option) The options and parameters discussed in this section apply to both methods of linking; however, when you link while compiling, the linker options must fol- low the −z option (see section 2.2, Invoking the C Compiler Shell, on page 2-4).
Disabling the Linker (−c Shell Option) 4.3 Disabling the Linker (−c Shell Option) You can override the −z option by using the −c shell option. The −c option is especially helpful if you specify the −z option in the C_OPTION environment variable and want to selectively disable linking with the −c option on the command line.
Linker Options 4.4 Linker Options All command-line input following the −z shell option is passed to the linker as parameters and options. The following are options that control the linker along with detailed descriptions of their effects. −a Produces an absolute, executable module. This is the default;...
Page 98
Linker Options −o filename Names the executable output module. The filename must follow operating system conventions. If the −o op- tion is not used, the default filename is a.out. −q Requests a quiet run (suppresses the banner and prog- ress information) −r Retains relocation entries in the output module −s...
C functions as well as functions used by the compiler to manage the C environment. You must use the −l linker option to specify which TMS320C2x/C2xx/C5x run-time-support library to use. The −l option also tells the linker to look at the −i options and then the C_DIR environment variable to find an archive path or object file.
Controlling the Linking Process Note: The _c_int0 Symbol One important function contained in the run-time-support library is _c_int0. The symbol _c_int0 is the starting point in boot.obj; if you use the −c or −cr linker option, _c_int0 is automatically defined as the entry point for the program.
Page 101
Controlling the Linking Process When you link a C program, you must use either the −c or −cr linker option. These options tell the linker to select initialization at run time or load time. When you compile and link programs, the −c linker option is the default. If used, the −c linker option must follow the −z option.
Controlling the Linking Process 4.5.3 Specifying Where to Allocate Sections in Memory The compiler produces relocatable blocks of code and data. These blocks, called sections, are allocated in memory in a variety of ways to conform to a variety of system configurations. The compiler creates two basic kinds of sections: initialized and uninitialized.
Page 103
Controlling the Linking Process The following table shows the type of memory and the page designation each section type requires: Section Type of Memory Page .text ROM or RAM .cinit ROM or RAM .const ROM or RAM .switch ROM or RAM .bss .stack .sysmem...
Controlling the Linking Process 4.5.4 A Sample Linker Command File Example 4−1 shows a typical linker command file that links a C program. The command file in this example is named link.cmd and lists several linker op- tions: −c Tells the linker to use autoinitialization at run time. −m Tells the linker to create a map file;...
Page 105
Controlling the Linking Process Finally, the command file lists all the object libraries that the linker must search. (The libraries are specified with the −l linker option.) Because this is a C pro- gram, the run-time-support library (rts25.lib, rts2xx.lib, or rts50.lib) must be included.
Chapter 5 TMS320C2x/C2xx/C5x C Language The TMS320C2x/C2xx/C5x C compiler supports the C language standard that was developed by a committee of the American National Standards Insti- tute (ANSI) to standardize the C programming language. ANSI C supersedes the de facto C standard that is described in the first edition of The C Programming Language by Kernighan and Ritchie.
TMS320C2x/C2xx/C5x C compiler. The following list identifies all such cases and describes the behavior of the TMS320C2x/C2xx/C5x C compiler in each case. Each description also in- cludes a reference to more information. Many of the references are to the for- mal ANSI standard or to the second edition of The C Programming Language by Kernighan and Ritchie (K&R).
Characteristics of TMS320C2x/C2xx/C5x C Language 5.1.4 Expressions When two signed integers are divided and either is negative, the quotient is negative, and the sign of the remainder is the same as the sign of the numerator. The slash mark (/) is used to find the quotient and the percent symbol (%) is used to find the remainder.
Objects of type enum are represented as 16-bit values; the type enum is equivalent to int in expressions. All floating-point types (float, double, and long double) are equivalent and are represented in the TMS320C2x/C2xx/C5x’s 32-bit floating-point format. Longs and floats are stored in memory with the least significant word at the lower address.
ANSI further stipulates that when sizeof is applied to char, the result is 1. Since the TMS320C2x/C2xx/C5x char is 16 bits (to make it separately addressable), a byte is also 16 bits. This yields results you may not expect;...
Register Variables 5.3 Register Variables The C compiler uses up to two register variables within a function. You must declare the register variables in the argument list or in the first block of the function. Register declarations in nested blocks are treated as normal vari- ables.
Pragma Directives 5.4 Pragma Directives Pragma directives tell the compiler’s preprocessor how to treat functions. The TMS320C2x/C2xx/C5x C compiler supports the following pragmas: CODE_SECTION DATA_SECTION FUNC_EXT_CALLED Two of these pragmas use the arguments func and symbol. These arguments must have file scope; that is, you cannot define or declare them inside the body of a function.
Pragma Directives 5.4.2 The DATA_SECTION Pragma The DATA_SECTION pragma allocates space for the symbol in a section named section name. The syntax of the pragma is: #pragma DATA_SECTION (symbol, “section name”); The DATA_SECTION pragma is useful if you have data objects that you want to link into an area separate from the .bss section.
The asm Statement 5.5 The asm Statement The TMS320C2x/C2xx/C5x C compiler can embed ’C6000 assembly lan- guage instructions or directives directly into the assembly language output of the compiler. This capability is an extension to the C language—the asm state- ment.
Creating Global Register Variables 5.6 Creating Global Register Variables The TMS320C2x/C2xx/C5x compiler extends the C language by adding a special convention to the register keyword to allow the allocation of global reg- isters. In this special case, the register keyword is treated as a storage class modifier.
If you disable the compiler from using AR6 and AR7, you must compile all code with the −r option(s) and rebuild the run-time-support library. For example, the following command rebuilds the rts25.lib library to not use AR6 and AR7: dspmk −rAR6 −rAR7 −o −v25 rts.src −l rts25.lib TMS320C2x/C2xx/C5x C Language 5-11...
Initializing Static and Global Variables 5.7 Initializing Static and Global Variables The ANSI C standard specifies that static and global (extern) variables without explicit initializations must be initialized to 0 before the program begins running. This task is typically performed when the program is loaded. Because the loading process depends heavily on the specific environment of the target application system, the compiler itself makes no provision for preinitializing variables.
/* read port 10h and pass to call a = port10 + b; /* read port 10h, add b, assign to a port10 += a; /* read port 10h, add a, write to port 10h */ TMS320C2x/C2xx/C5x C Language 5-13...
Compatibility with K&R C 5.8 Compatibility with K&R C The ANSI C language is a superset of the de facto C standard defined in Ker- nighan and Ritchie’s The C Programming Language. Most programs written for other non-ANSI compilers correctly compile and run without modification. There are subtle changes, however, in the language that can affect existing code.
Page 120
K&R syntax allows a trailing comma in enumerator lists: enum { a, b, c, }; /* illegal unless −pk used */ K&R syntax allows trailing tokens on preprocessor directives: #endif NAME /* illegal unless −pk used */ TMS320C2x/C2xx/C5x C Language 5-15...
Compiler Limits 5.9 Compiler Limits Due to the variety of host systems that the TMS320C2x/C2xx/C5x C compiler supports and the limitations of some of these systems, the compiler might not be able to successfully compile source files that are excessively large or com- plex.
2) This limit reflects the number of characters before concatenation. All other charac- ter strings are unrestricted. 3) This limit includes argument substitutions. 4) This limit includes −i and C_DIR directories. 5) May be further limited by available system memory. TMS320C2x/C2xx/C5x C Language 5-17...
Page 123
Compiler Limits Table 5−2. Absolute Compiler Limits (Continued) Description Limits Number of unique string constants 1000 All others Number of unique floating-point con- stants 1000 All others Notes: 1) This limit reflects the number of characters after splicing of \ lines. This limit also applies to any single macro definition or invocation.
Chapter 6 Run-Time Environment This chapter describes the TMS320C2x/C2xx/C5x C run-time environment. To ensure successful execution of C programs, it is critical that all run-time code maintain this environment. It is also important to follow the guidelines in this chapter if you write assembly language functions that interface with C code.
Memory Model 6.1 Memory Model The TMS320C2x/C2xx/C5x C compiler treats memory as two linear blocks of program memory and data memory: Program memory contains executable code. Data memory contains external variables, static variables, and the system stack. Each block of code or data generated by a C program is placed into a contig- uous block in the appropriate memory space.
For more information about COFF sections, see the introductory COFF information in the TMS320C1x/C2x/C2xx/C5x Assembly Language Tools User’s Guide. The TMS320C2x/C2xx/C5x compiler creates the following types of sections: Initialized sections contain data tables or executable code. The C compiler creates the following initialized sections: The .text section contains all the executable code as well as floating-...
Memory Model The linker takes the individual sections from different modules and combines sections with the same name to create output sections. The complete program is made up of these output sections, which include the assembler’s .data section. You can place these output sections anywhere in the address space as needed in order to meet system requirements.
Memory Model The C environment manipulates these registers automatically. If you write assembly language routines that use the run-time stack, be sure to use these registers correctly. For more information about using these registers, see sec- tion 6.2, Register Conventions, on page 6-9. For more information about the stack, see section 6.3, Function Calling Conventions, on page 6-14.
Dynamic Memory Allocation Dynamic memory allocation is not a standard part of the C language. The run- time-support library supplied with the TMS320C2x/C2xx/C5x compiler con- tains several functions (such as malloc, calloc, and realloc) that allow you to allocate memory dynamically for variables at run time.
Memory Model Dynamically allocated objects are not addressed directly (they are always accessed with pointers) and the memory pool is in a separate section (.sys- mem); therefore, the dynamic memory pool can have a size limited only by the amount of available memory in your system. To conserve space in the .bss section, you can allocate large arrays from the heap instead of defining them as global or static.
Memory Model 6.1.7 Field/Structure Alignment When the compiler allocates space for a structure, it allocates as many words as are needed to hold all of the structure’s members. In an array of structures, each structure begins on a word boundary. All nonfield types are aligned on word boundaries.
However, the conventions for preserving registers across function calls are identical with or without the optimizer. The following table summarizes how the compiler uses the TMS320C2x/C2xx/ C5x registers and shows which registers are defined to be preserved across function calls.
A dash in this column indicates that the compiler does not expect a particular value. The modified column indicates if code generated by the compiler ever modifies this field. Table 6−2. Status Register Fields (a) TMS320C2x, TMS320C2xx and TMS320C5x fields Field Name Presumed Value...
Register Conventions Register AR1 is dedicated as the stack pointer. The compiler uses the SP in the conventional way: the stack grows towards higher addresses, and the SP points to the next available word on the stack. Register AR0 is dedicated as the frame pointer. The FP points to the beginning of the local frame for the current function.
Register Conventions Setting up a register variable at run time requires approximately four instruc- tions per register variable. To use this feature efficiently, use register variables only if the variable is accessed more than twice. 6.2.4.2 Register Variables When the Optimizer is Used When the optimizer is used, all user register declarations are ignored.
Function Structure and Calling Conventions 6.3 Function Structure and Calling Conventions The C compiler imposes a strict set of rules on function calls. Except for special run-time-support functions, any function that calls or is called by a C function must follow these rules. Failure to adhere to these rules can disrupt the C envi- ronment and cause a program to fail.
Function Structure and Calling Conventions 6.3.1 How a Function Makes a Call A function (parent function) performs the following tasks when it calls another function (child function). Be aware that the ARP must be set to AR1. 1) The caller pushes the arguments on the stack in reverse order (the right- most declared argument is pushed first, and the leftmost is pushed last).
Function Structure and Calling Conventions Example 6−1 is an example of TMS320C2x code that performs the tasks listed in section 4.3.2. Example 6−1. TMS320C2x Code as a Called Function ; presume ARP = AR1 (SP) POPD ; pop return address, push on software stack AR0,*+ ;...
Page 140
Function Structure and Calling Conventions 6.3.3.1 Returning a structure If the function returns a structure, the caller (parent function) allocates space for the structure and then passes the address of the return space to the called function (child function) as an additional and final argument on the stack. To return a structure, the called function then copies the structure to the memory block pointed to by this argument.
Function Structure and Calling Conventions 6.3.3.4 Using the TMS320C5x RETD instruction The debugger expects the compiler to generate the frame as described above. When generating code for the ’C5x that will not be run under the debugger, the compiler switches steps 2 and 3 of section 6.3.2, How a Called Function Responds, on page 6-15, as well as steps 11 and 12.
Interfacing C with Assembly Language 6.4 Interfacing C with Assembly Language The following are ways to use assembly language with C code: Use separate modules of assembled code and link them with compiled C modules (see section 6.4.1, Using Assembly Language Modules With C Code).
Page 143
Interfacing C with Assembly Language When using only the ’C5x: if your assembly routine does not change the NDX bit of status register PMST from 0 to 1, then the INDX register shadows AR0; preserving AR0 preserves INDX as well. If your routine does change the NDX bit, then both AR0 and INDX must be preserved explicitly.
Interfacing C with Assembly Language Example 6−2 illustrates a C function called main, which calls an assembly language function called asmfunc. The asmfunc function takes its single argu- ment, adds it to the C global variable called gvar, and returns the result. Example 6−2.
Interfacing C with Assembly Language 6.4.2 Using Inline Assembly Language Within a C program, you can use the asm statement to inject a single line of assembly language into the assembly language file that the compiler creates. A series of asm statements places sequential lines of assembly language into the compiler output with no intervening code.
Interfacing C with Assembly Language 6.4.3 Accessing Assembly Language Variables From C Code It is sometimes useful for a C program to access variables defined in assembly language. Accessing uninitialized variables from the .bss section or from a named section is straightforward: 1) Use the .bss or .usect directive to define the variable.
Interfacing C with Assembly Language Example 6−4 shows an example that accesses a variable that is not defined in .bss. Example 6−4. Accessing a Variable Not Defined in .bss From C (a) C program extern float sine[]; /* This is the object f = sine[4];...
Interrupt Handling 6.5 Interrupt Handling As long as you follow the guidelines in this section, you can interrupt and return to C code without disrupting the C environment. When the C environment is initialized, the startup routine does not enable or disable interrupts. Interrupts are disabled if the system is initialized via a hardware reset.
Interrupt Handling 6.5.2 Using C Interrupt Routines You can handle interrupts directly with C functions by using one of two conven- tions: Any function with the name c_intd, where d is a digit 0−9, is presumed to be an interrupt routine. The name c_int0 is reserved for the system reset interrupt;...
Interrupt Handling 6.5.3 Using Assembly Language Interrupt Routines You can handle Interrupts with assembly language code as long as you follow the same register conventions the compiler. Keep the following points in mind: The word pointed to by the SP (AR1) may be in use by the compiler. It must be saved.
6.6.1 Arithmetic Overflow and Underflow The TMS320C2x/C2xx/C5x produces a 32-bit result even when 16-bit values are used as data operands; thus, arithmetic overflow and underflow cannot be handled in a predictable manner. If code depends on a particular type of over- flow/underflow handling, there is no assurance that this code will execute correctly.
Integer Expression Analysis 6.6.4 C Code Access to the Upper 16 Bits of 16-Bit Multiply The following method provides access to the upper 16 bits of a 16-bit multiply in C language. For example: Signed results: intm1, m2; intresult; result = ((long) m1 * (long) m2) >> 16; Unsigned results: unsigned m1, m2;...
Floating-Point Expression Analysis 6.7 Floating-Point Expression Analysis The TMS320C2x/C2xx/C5x C compiler represents floating-point values as IEEE single-precision numbers. Both single-precision and double-precision floating-point numbers are represented as 32-bit values; there is no difference between the two formats. The TMS320C2x/C2xx/C5x run-time-support library, rts.src, contains a...
System Initialization 6.8 System Initialization Before you can run a C program, you must create the C run-time environment. The C boot routine performs this task using a function called c_int0. The run- time-support source library, rts.src, contains the source to this routine in a module named boot.asm.
System Initialization 6.8.1 Run-time Stack The run-time stack is allocated in a single contiguous block of memory and grows up from low addresses to higher addresses. Register AR1 usually points to the next available word in the stack (top of the stack plus one word). The compiler can use this word as a temporary memory location, so it must be saved by interrupt routines.
System Initialization 6.8.3 Initialization Tables The tables in the .cinit section consist of variable-size initialization records. Each variable that must be autoinitialized has a record in the .cinti section. Figure 6−2 shows the format of the .cinit section and the initialization records. Figure 6−2.
System Initialization When you use the − c or − cr linker option, the linker combines the .cinit sections from all the C modules and appends a null word to the end of the composite .cinit section. This terminating record appears as a record with a size field of 0, marking the end of the initialization tables.
System Initialization 6.8.5 Initialization of Variables at Load Time Initialization of variables at load time enhances performance by reducing boot time and by saving the memory used by the initialization tables. To use this method, invoke the linker with the − cr option. When you use the −cr linker option, the linker sets the STYP_COPY bit in the .cinit section’s header.
C language itself. However, the ANSI C standard defines a set of run-time-sup- port functions that perform these tasks. The TMS320C2x/C2xx/C5x C compil- er implements the complete ANSI standard library except for those facilities that handle exception conditions and locale issues (properties that depend on local language, nationality, or culture).
Libraries 7.1 Libraries The following libraries are included with the TMS320C2x/C2xx/C5x C com- piler: rts25.lib, rts2xx.lib and rts50.lib—run-time-support object libraries. The libraries do not contain functions involving signals and locale issues. They do contain the following: ANSI C standard library...
Libraries 7.1.2 Modifying a Library Function You can inspect or modify library functions by using the archiver to extract the appropriate source file or files from the source libraries. For example, the fol- lowing command extracts two source files: dspar −x rts.src atoi.c strcpy.c To modify a function, extract the source as in the previous example.
Header Files Header Files Each run-time-support function is declared in a header file. Each header file declares the following: A set of related functions (or macros) Any types that you need to use the functions Any macros that you need to use the functions These are the header files that declare the run-time-support functions: assert.h limits.h...
Header Files 7.2.1 Diagnostic Messages (assert.h) The assert.h header defines the assert macro, which inserts diagnostic failure messages into programs at run time. The assert macro tests a run-time expression. If the expression is true (nonzero), the program continues running. If the expression is false, the macro outputs a message that contains the expression, the source file name, and the line number of the statement that contains the expression;...
Limits (float.h and limits.h) The float.h and limits.h headers define macros that expand to useful limits and parameters of the TMS320C2x/C2xx/C5x’s numeric representations. Table 7−1 and Table 7−2 list these macros and their limits. Table 7−1. Macros That Supply Integer Type Range Limits (limits.h)
Header Files Table 7−2. Macros That Supply Floating-Point Range Limits (float.h) Macro Value Description FLT_RADIX Base or radix of exponent representation FLT_ROUNDS Rounding mode for floating-point addition (rounds toward integer) FLT_DIG Number of decimal digits of precision for a float, double, or DBL_DIG long double LDBL_DIG...
Inport/Outport Macros (ioports.h) The ioports.h header defines two macros and their associated functions, which are used to access the TMS320C2x/C2xx/C5x I/O ports. The macros are the easiest way to access the I/O ports and include: inport, a macro that reads a value from the specified port and returns the...
Header Files 7.2.6 Floating-Point Math (math.h) The math.h header defines several trigonometric, exponential, and hyperbolic math functions. These functions are listed in Table 7−3 (d) on page 7-16. The math functions expect double-precision floating-point arguments and return double-precision floating-point values. Except where all trigonometic func- tions use angles expressed as radians.
Header Files A variable-argument function can use the macros declared by stdarg.h to step through its argument list at run time when the function knows the number and types of arguments actually passed to it. You must ensure that a call to a variable-argument function has visibility to a prototype for the function in order for the arguments to be handled correctly.
Header Files Searching and sorting functions that allow you to search and sort arrays Sequence-generation functions that allow you to generate a pseudo- random sequence and allow you to choose a starting point for a sequence Program-exit functions that allow your program to terminate normally or abnormally Integer-arithmetic that is not provided as a standard part of the C language The general utility functions are listed in Table 7−3 (g) on page 7-17.
Header Files clock_t, an arithmetic type that represents time time_t, an arithmetic type that represents time tm, a structure that holds the components of calendar time, called broken- down time. The structure has the following members: int tm_sec; /* seconds after the minute (0−59) int tm_min;...
7.3 Summary of Run-Time-Support Functions and Macros Table 7−3 summarizes the run-time-support header files (in alphabetical order) provided with the TMS320C2x/C2xx/C5x ANSI C compiler. Most of the functions described are per the ANSI standard and behave exactly as described in the standard.
Page 173
Summary of Run-Time-Support Functions and Macros Table 7−3. Summary of Run-Time-Support Functions and Macros (a) Error message macro (assert.h) Macro Description Page ‡ void assert(int expr); Inserts diagnostic messages into programs 7-23 (b) Character typing and conversion functions (ctype.h) Function Description Page int isalnum(int c);...
Page 174
Summary of Run-Time-Support Functions and Macros (c) Inport/outport macros (ioports.h) Macro Description Page int inport(int port, int *ret); Returns a value from the specified port via the point- 7-34 er ret void outport(int port, int value); Writes a value to the specified port and has no return 7-34 value Run-Time-Support Functions...
Page 175
Summary of Run-Time-Support Functions and Macros (d) Floating-point math functions (math.h) Function Description Page double acos(double x); Returns the arc cosine of x 7-22 double asin(double x); Returns the arc sine of x 7-22 double atan(double x); Returns the arc tangent of x 7-24 double atan2(double y, double x);...
Page 176
Summary of Run-Time-Support Functions and Macros (e) Nonlocal jumps macro and function (setjmp.h) Function or Macro Description Page int setjmp(jmp_buf env); Saves calling environment for use by longjmp; this 7-45 is a macro void longjmp(jmp_buf env, int _val); Uses jmp_buf argument to restore a previously 7-45 saved environment (f) Variable argument macros (stdarg.h)
Page 177
Summary of Run-Time-Support Functions and Macros (g) General functions (stdlib.h)(Continued) Function Description Page long labs(long i); Returns the absolute value of i; expands inline 7-21 unless −x0 is used ldiv_t ldiv(register long numer, Divides numer by denom 7-30 register long denom); int ltoa(long val, char *buffer);...
Page 178
Summary of Run-Time-Support Functions and Macros (h) String functions (string.h)(Continued) Function Description Page char *strchr(const char *string, int c); Finds the first occurrence of character c in s; 7-48 expands inline if −x is used int strcmp(register const char *string1, Compares strings and returns one of the following 7-48 register const char *s2);...
Page 179
Summary of Run-Time-Support Functions and Macros Time-support functions (time.h) Function Description Page char *asctime(const struct tm *timeptr); Converts a time to a string 7-22 clock_t clock(void); Determines the processor time used 7-28 char *ctime(const time_t *timer); Converts calendar time to local time 7-29 double difftime(time_t time1, time_t time0);...
Page 180
The abs function returns the absolute value of an integer j. The labs function returns the absolute value of a long integer k. Since int and long int are functionally equivalent types in TMS320C2x/C2xx/ C5x C, the abs and labs functions are also functionally equivalent. The abs and labs functions are expanded inline unless the −x0 option is used.
Page 181
acos Arc Cosine acos Syntax #include <math.h> double acos(double x ); Defined in acos.c in rts.src Description The acos function returns the arc cosine of a floating-point argument x, which π must be in the range [−1,1]. The return value is an angle in the range [0, radians.
Page 182
assert Insert Diagnostic Information Macro assert Syntax #include <assert.h> void assert(int expr); Defined in assert.h as a macro Description The assert macro tests an expression; depending upon the value of the expression, assert either issues a message and aborts execution or continues execution.
Page 183
atan Polar Arc Tangent atan Syntax #include <math.h> double atan(double x ); Defined in atan.c in rts.src Description The atan function returns the arc tangent of a floating-point argument x. The π π return value is an angle in the range [− /2] radians.
Page 184
The first character that cannot be part of the number terminates the string. Since int and long are functionally equivalent in TMS320C2x/C2xx/C5x C, the atoi and atol functions are also functionally equivalent.
Page 185
bsearch Array Search bsearch Syntax #include <stdlib.h> void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar )(const void *, const void * )); Defined in bsearch.c in rts.src Description The bsearch function searches through an array of nmemb objects for a mem- ber that matches the object that key points to.
Page 186
ceil Allocate and Clear Memory calloc Syntax #include <stdlib.h> void *calloc(size_t num, size_t size); Defined in memory.c in rts.src Description The calloc function allocates size bytes (size is an unsigned integer or size_t) for each of nmemb objects and returns a pointer to the space. The function ini- tializes the allocated memory to all 0s.
clock Processor Time clock Syntax #include <time.h> clock_t clock(void ); Defined in clock.c in rts.src Description The clock function determines the amount of processor time used. It returns an approximation of the processor time used by a program since the program began running.
Page 188
difftime Hyperbolic Cosine cosh Syntax #include <math.h> double cosh(double x ); Defined in cosh.c in rts.src Description The cosh function returns the hyperbolic cosine of a floating-point number x. A range error occurs (errno is set to the value of EDOM) if the magnitude of the argument is too large.
Page 189
The sign of the remainder is the same as the sign of numer. Because ints and longs are equivalent types in TMS320C2x/C2xx/C5x C, these functions are also equivalent. Example int 1 = −10...
Page 190
You can modify the exit function to perform application-specific shutdown tasks. The unmodified function simply runs in an infinite loop until the system is reset. The exit function cannot return to its caller. The TMS320C2x/C2xx/C5x implementation of the abort function makes it equivalent to the exit function. Exponential Syntax #include <math.h>...
Page 191
floor Floor floor Syntax #include <math.h> double floor(double x ); Defined in floor.c in rts.src Description The floor function returns a floating-point number that represents the largest integer less than or equal to x. The floor function is expanded inline if the −x option is used.
Page 192
gmtime Fraction and Exponent frexp Syntax #include <math.h> double frexp(double value, int *exp); Defined in frexp30.asm in rts.src Description The frexp function breaks a floating-point number into a normalized fraction (f) and the integer power of 2. The function returns f and exp such that 0.5−|f|<1.0 and value ==f x 2 .
Page 193
_PSWITCH to 1. The macros always work, regardless of the value of _PSWITCH. For additional information on I/O ports, refer to the TMS320C2x User’s Guide, the TMS320C2xx User’s Guide, or the TMS320C5x User’s Guide.
Page 194
isxxx Character Typing isxxx Syntax #include <ctype.h> int isalnum( int c ); int islower( int c ); int isalpha ( int c ); int isprint ( int c ); int isascii( int c ); int ispunct ( int c ); int iscntrl ( int c );...
Page 195
labs See abs/labs on page 7-21 labs Multiply by a Power of Two ldexp Syntax #include <math.h> double ldexp(double x, int exp ); Defined in ldexp.c in rts.src Description The ldexp function multiplies a floating-point number x by 2 and returns (x ×...
Page 196
ltoa Natural Logarithm Syntax #include <math.h> double log(double x ); Defined in log.c in rts.src Description The log function returns the natural logarithm of a real number x. A domain er- ror occurs if x is negative; a range error occurs if x is 0. Example float x, y;...
Page 197
malloc Allocate Memory malloc Syntax #include <stdlib.h> void *malloc(size_t size ); Defined in memory.c in rts.src Description The malloc function allocates space for an object of size bytes and returns a pointer to the space. If malloc cannot allocate the packet (that is, if it runs out of memory), it returns a null pointer (0).
Page 198
memmove Memory Compare memcmp Syntax #include <string.h> int memcmp(const void *cs, const void *ct, size_t n ); Defined in memcmp.c in rts.src Description The memcmp function compares the first n characters of the object that ct points to with the object that cs points to. The function returns one of the follow- ing values: <...
Page 199
memset Duplicate Value in Memory memset Syntax #include <string.h> void *memset(void *mem, int ch, size_t length ); Defined in memset.c in rts.src Description The memset function copies the value of ch into the first length characters of the object that mem points to. The function returns the value of mem. The memset function is expanded inline when the −x option is used.
Page 200
mktime Convert to Calendar Time mktime Syntax #include <time.h> time_t *mktime(struct tm *timeptr ); Defined in mktime.c in rts.src Description The mktime function converts a broken-down time, expressed as local time, into proper calendar time. The timeptr argument points to a structure that holds the broken-down time.
Page 201
modf Signed Integer and Fraction modf Syntax #include <math.h> double modf(double value, double *iptr ); Defined in modf.c in rts.src Description The modf function breaks a value into a signed integer and a signed fraction. Each of the two parts has the same sign as the input argument. The function returns the fractional part of the value and stores the integer part as a double at the object pointed to by iptr.
Page 202
qsort Array Sort qsort Syntax #include <stdlib.h> void qsort(void *base, size_t nmemb, size_t size, int (*compar) (const void *, const void * )); Defined in qsort.c in rts.src Description The qsort function sorts an array of nmemb members. Argument base points to the first member of the unsorted array;...
Page 203
Description Two functions work together to provide pseudorandom sequence generation: The rand function returns pseudorandom integers in the range 0—RAND_MAX. For the TMS320C2x/C2xx/C5x C compiler, the value of RAND_MAX is 2 147 483 646 (2 −2). The srand function sets the value of the seed so that a subsequent call to the rand function produces a new sequence of pseudorandom numbers.
Page 204
setjmp/longjmp Nonlocal Jumps setjmp/longjmp Syntax #include <setjmp.h> int setjmp(jmp_buf env ); void longjmp(jmp_buf env, int returnval ); Defined in setjmp.asm in rts.src Description The setjmp.h header defines a type and a macro and declares a function for bypassing the normal function call and return discipline: The jmp_buf type is an array type suitable for holding the information needed to restore a calling environment.
Page 205
/* return value = 0.0 */ Write Stream sprintf The run-time-support functions supplied with the TMS320C2x/C2xx/C5x C compiler do not include I/O functions such as sprintf. However, since the time function uses sprintf, a minimal version of sprintf() is supplied that performs only the formatting required by time().
Page 206
strcat Square Root sqrt Syntax #include <math.h> double sqrt(double x ); Defined in sqrt.c in rts.src Description The sqrt function returns the nonnegative square root of a real number x. A domain error occurs if the argument is negative. Example double x, y;...
Page 207
strchr Find First Occurrence of a Character strchr Syntax #include <string.h> char *strchr(const char *string, char c ); Defined in strchr.c in rts.src Description The strchr function finds the first occurrence of c in string. If strchr finds the character, it returns a pointer to the character; otherwise, it returns a null point- er (0).
Page 208
strcspn String Copy strcpy Syntax #include <string.h> char *strcpy(char *string1, const char *string2 ); Defined in strcpy.c in rts.src Description The strcpy function copies string2 (including a terminating null character) into string1. If you attempt to copy strings that overlap, the function’s behavior is undefined.
Page 209
strerror String Error strerror Syntax #include <string.h> char *strerror(int errno ); Defined in strerror.c in rts.src Description The strerror function returns the string “string error”. This function is supplied to provide ANSI compatibility. Format Time strftime Syntax #include <time.h> size_t *strftime(char *out, size_t maxsize, const char *format, const struct tm *time );...
Page 210
strncat The week number of the year (Sunday is the first day of the week) as a decimal number (00−52) The date representation The time representation The year without century as a decimal number (00−99) The year with century as a decimal number The time zone name, or by no characters if no time zone exists For more information about the functions and types that the time.h header declares and defines, see section 7.2.12, page 7-11.
Page 211
strncmp Example In the following example, the character strings pointed to by *a, *b, and *c were assigned the values shown in the comments. In the comments, the notation \0 represents the null character: char *a, *b, *c; size_t size = 13; /* a−−>...
Page 212
strncpy String Copy strncpy Syntax #include <string.h> char *strncpy(const char *dest, const char *src, size_t n ); Defined in strncpy.c in rts.src Description The strncpy function copies up to n characters from src into dest. If src is n characters long or longer, the null character that terminates src is not copied. If you attempt to copy characters from overlapping strings, the function’s be- havior is undefined.
Page 213
strpbrk Find Any Matching Character strpbrk Syntax #include <string.h> char *strpbrk(const char *string, const char *chs ); Defined in strpbrk.c in rts.src Description The strpbrk function locates the first occurrence in string of any character in chs. If strpbrk finds a matching character, it returns a pointer to that character; otherwise, it returns a null pointer (0).
Page 214
strstr Find Number of Matching Characters strspn Syntax #include <string.h> size_t *strspn(const char *string, const char *chs ); Defined in strspn.c in rts.src Description The strspn function returns the length of the initial segment of string, which is entirely made up of characters in chs. If the first character of string is not in chs, the strspn function returns 0.
Page 215
strtod/strtol/strtoul Convert String to Numeric Value strtod/strtol/ strtoul Syntax #include <stdlib.h> double strtod(const char *test, char **endptr ); long int strtol(const char *test, char **endptr, int base ); unsigned long int strtoul(const char *test, char **endptr, int base ); Defined in strtod.c in rts.src, strtol.c in rts.src and strtoul.c in rts.src Description Three functions convert ASCII strings to numeric values.
Page 216
Break String Into Token strtok Syntax #include <string.h> char *strtok(char *str1, const char *str2 ); Defined in strtok.c in rts.src Description Successive calls to the strtok function break str1 into a series of tokens, each delimited by a character from str2. Each call returns a pointer to the next token. The first call to strtok uses the string str1.
tanh Hyperbolic Tangent tanh Syntax #include <math.h> double tanh(double x ); Defined in tanh.c in rts.src Description The tanh function returns the hyperbolic tangent of a floating-point number x. Example double x, y; x = 0.0; y = tanh(x); /* return value = 0.0 */ Time time Syntax...
Page 218
toascii Special Version of sprintf ti_sprintf Syntax #include <stdlib.h> int ti_sprintf ( char *s, const char *format, ...); Defined in tsprintf.c in rts.src Description The ti_sprintf function is a minimal version of sprintf() that supports only those functions required by time(). Specifically, ti_sprintf supports only the following conversions: % [ 0 ] [ digits ] ( s | d ) if present, indicates that the field will be padded with 0s instead of...
Page 219
tolower/toupper Convert Case tolower/toupper Syntax #include <ctype.h> int tolower(int c ); int toupper(int c ); Defined in tolower.c in rts.src toupper.c in rts.src Description Two functions convert the case of a single alphabetic character c into upper- case or lowercase: The tolower function converts an uppercase argument to lowercase.
Page 220
va_arg/va_end/va_start The va_end macro resets the stack environment after va_start and va_arg are used. You must call va_start to initialize ap before calling va_arg or va_end. Example int printf (char *fmt, ...) va_list ap; va_start(ap, fmt); /* Get next arg, an integer i = va_arg(ap, int);...
Chapter 8 Library-Build Utility When using the C compiler, you can compile your code under a number of dif- ferent configurations and options that are not necessarily compatible with one another. Since it would be cumbersome to include all possible combinations in individual run-time-support libraries, this package includes the source file, rts.src, that contains all run-time-support functions.
Invoking the Library-Build Utility 8.1 Invoking the Library-Build Utility The dspmk utility runs the shell program on each source file in the archive to compile and/or assemble it. Then, the utility collects all the object files into the object library. All tools must be placed in your PATH. The utility ignores and dis- ables the environment variables TMP, C_OPTION, and C_DIR.
Library-Build Utility Options 8.2 Library-Build Utility Options Most of the options that are included on the command line correspond directly to options of the same name used with the compiler, assembler, linker, and shell. The following options apply only to the library-build utility. −−c Extracts C source files contained in the source archive from the library and leaves them in the current directory after the utility has...
Options Summary 8.3 Options Summary The other options you can use with the library-build utility correspond directly to the options that the compiler uses. Table 8−1 lists these options. Table 8−1. Summary of Options and Their Effects (a) Options that control the compiler shell Option Effect −g...
Page 225
Options Summary (e) Options that control the runtime model Option Effect −ma Assumes aliased variables −mb Avoids RPTK for structure moves −ml Disables LDPK optimization −mn Enables optimization disabled by − g −ms Optimizes for space instead of for speed −mx Avoids ’C5x silicon bugs (f) Options that overlook type checking...
Appendix A Appendix A Glossary ANSI: See American National Standards Institute. absolute address: An address that is permanently assigned to a memory location. aliasing: The ability for a single object to be accessed in more than one way, such as when two pointers point to the same object. It can disrupt opti- mization because any indirect reference could refer to any other object.
ANSI further stipulates that when sizeof is applied to char, the result is 1. Since the TMS320C2x/C2xx/C5x char is 16 bits (to make it separately addressable), a byte is also 16 bits. This yields results you may not expect;...
Page 229
This is accomplished by defining a large memory pool (heap) and using the functions to allocate memory from the heap. emulator: A hardware development system that duplicates TMS320C2x, TMS320C2xx, or TMS320C5x operation. entry point: The point in target memory where execution starts.
Page 230
Glossary field: For the TMS320C2x, TMS320C2xx, and TMS320C5x, a software- configurable data type whose length can be programmed to be any value in the range of 1−16 bits. file_leve optimization: A level of optimization where the compiler uses the information that it has about the entire file to optimize your code (as op- posed to program_level optimization, where the compiler uses informa- tion that it has about the entire program to optimize your code).
Page 231
Glossary integrated preprocessor: The C preprocessor is integrated with the parser, allowing for faster compilation. Stand-alone preprocessing or a prepro- cessed listing is also available. interlist utility: A utility that inserts as comments your original C source statements into the assembly language output from the assembler. The C statements are inserted next to the equivalent assembly instructions.
Page 232
Glossary memory map: A map of target-system memory space that is partitioned into functional blocks. object file: An assembled or linked file that contains machine-language ob- ject code. object library: An archive library made up of individual object files. operand: An argument of an assembly language instruction, assembler di- rective, or macro directive that supplies information to the operation per- formed by the instruction or directive.
Page 233
Glossary raw data: Executable code or initialized data in an output section. relocation: A process in which the linker adjusts all the references to a symbol when the symbol’s address changes. runtime environment: The runtime parameters in which your program must function.
Page 234
The system on which the object code you have developed is executed. target memory: Physical memory in a TMS320C2x-, TMS320C2xx-, or TMS320C5x-based system into which executable object code is loaded. .text section: One of the default COFF sections. The .text section that is ini- tialized contains executable code.
Page 235
TOKEN REFERENCE SEE (ALSO) . . . assembly language interfacing C with assembly language C compiler compiler C language ANSI C C language interfacing C with assembly language C language K&R clist command interlist utility dspac command parser dspac command preprocessor dspcg command code generator...
Page 236
TOKEN SEE (ALSO) . . . REFERENCE parser preprocessor pointer frame FP register pointer frame frame pointer pointer stack SP register pointer stack stack pointer string constants constants, string sprintf function ti_sprintf function system stack stacks time functions, ti_sprintf ti_sprintf function tm structure broken-down time...
Page 237
6-19 to 6-21 compatibility with K&R C 5-14 to 5-15 assembly listing file overlooking type-checking 2-17 creating 2-19 TMS320C2x/C2xx/C5x differs from 5-2 to 5-3 assert function 7-22 −ap assembler option 2-19 assert.h header 7-5, 7-14 −app assembler option 2-19...
Page 238
Index −au shell option 2-19 C preprocessor 2-22 C source statements and assembly language 2-33 autoinitialization at runtime 6-34 _c_int00 initialization tables 6-33 described 4-10 of constants 6-32 C_OPTION environment variable 2-20 of variables 6-7, 6-32 calendar time 7-11, 7-28, 7-40, 7-57 types of 4-9 called function 6-15 to 6-18 −ax shell option 2-19...
Page 239
Index COFF 1-3, 1-5, 6-3 conversions 5-3, 7-5 C language 5-2 command file, linker 4-13 copy file example 4-13 −ahc assembler option 2-19 common logarithm 7-36 cos function 7-27 common object file format. See COFF cosh function 7-28 compare strings 7-51 cosine 7-27 compatibility with K&R C 5-14 to 5-15 −cr linker option 4-2, 4-9, 6-7...
Page 240
Index dspcl command 1-5, 2-4 errors treated as warnings 2-36 See also compiler escape sequences 5-2, 5-15 dsplnk command 4-2 exit function 7-20, 7-23, 7-30 See also linker exp function 7-30 dspmk command 8-2 exponential math function 7-9, 7-30 See also library-build utility expression analysis dspopt command 2-41 floating-point 6-30...
Page 241
Index float.h header 7-6 function alphabetic reference 7-20 floating-point call 6-15 expression analysis 6-30 conventions 6-14 to 6-18 math functions 7-9 using the stack 6-4 acos 7-21 general utility 7-16 asin 7-21 inlining 2-27 to 2-32 atan 7-23 parameters maximum number of 5-17 atan2, 7-23 prototype ceil 7-26...
Page 243
Index invoking the libraries 7-2 C compiler 2-4 library-build utility 1-3, 1-6, 8-1 to 8-6 C compiler tools individually 2-38 optional object library 8-2 code generator 2-43 options 8-3 interlist utility 2-33, 2-45 limits library-build utility 8-2 absolute compiler 5-17 linker 4-2 compiler 5-16 to 5-18 optimizer 2-41...
Page 244
Index listing file 2-25 memory management functions assembly language calloc 7-26 −k shell option 2-13 free 7-31 register use (−mr option) 2-18 malloc 7-37 creating cross-reference 2-19 minit 7-39 realloc 7-43, 7-45 load time initialization 6-35 memory model 6-2 to 6-8 loader 5-12 allocating variables 6-7 local initializers maximum number 5-17...
Page 245
Index optimizer 1-3, 2-41 to 2-43 and interrupts 3-11 invoking 2-41 invoking with shell options 3-2 −o linker option 4-7 options 2-42 −o shell option 3-2 parser output 2-42 special considerations 3-10 .obj extension 2-15 aliasing 3-11 object library volatile keyword 3-10 linking code with 7-2 use with debugger 2-18 options 2-6 to 2-19...
Page 246
Index port variables ioport keyword 5-13 pow function 7-41 −−q library-build utility option 8-3 power 7-41 −q interlist option 2-45 #pragma directive 5-3 −q linker option 4-7 pragma directives −q shell option 2-5, 2-13 CODE_SECTION 5-7 −qq shell option 2-13 DATA_SECTION 5-8 qsort function 7-42 FUNC_EXT_CALLED 5-8...
Page 247
Index run-time environment 6-1 to 6-36 sections 6-3 defining variables in assembly language 6-23 allocating memory 4-11 floating-point expression analysis 6-30 .bss 6-3 function call conventions 6-14 to 6-18 .cinit 6-4, 6-33 inline assembly language 6-22 created by the compiler 4-11 integer expression analysis 6-28 .data 6-3 interfacing C with assembly language 6-19 to...
Page 248
Index stddef.h header 7-10 strtol function 7-55 stdlib.h header 7-10 strtoul function 7-55 summary of functions 7-16 structure members 5-3 strcat function 7-46 structure packing 6-8 strchr function 7-47 structures strcmp function 7-47 nesting of declarations strcoll function 7-47 maximum number of 5-17 strcpy function 7-48 STYP_CPY flag 4-10 strcspn function 7-48...
Page 249
See also broken-down time variable argument macros, summary of 7-16 TMP environment variable 2-21 variable argument function 7-59 _TMS320C25, 2-22 variables TMS320C2x/C2xx/C5x C language, compatibility register with ANSI C language 5-14 to 5-15 global 5-10 _TMS320C2xx 2-22 volatile 3-10 _TMS320C50, 2-22...
Page 250
Index −z shell option 2-2, 2-4, 2-14 overriding with −c option 4-5 overriding with −n option 2-13 Index-14...
Need help?
Do you have a question about the TMS320C2x and is the answer not in the manual?
Questions and answers