spru034h.pdf

March 28, 2018 | Author: vka_prince | Category: C (Programming Language), Compiler, Assembly Language, Library (Computing), Source Code


Comments



Description

TMS320C3x/C4x Optimizing C Compiler User’s GuideLiterature Number: SPRU034H June1998 Printed on Recycled Paper IMPORTANT NOTICE Texas Instruments (TI) reserves the right to make changes to its products or to discontinue any semiconductor product or service without notice, and advises its customers to obtain the latest version of relevant information to verify, before placing orders, that the information being relied on is current. TI warrants performance of its semiconductor products and related software to the specifications applicable at the time of sale in accordance with TI’s standard warranty. Testing and other quality control techniques are utilized to the extent TI deems necessary to support this warranty. Specific testing of all parameters of each device is not necessarily performed, except those mandated by government requirements. Certain applications using semiconductor products may involve potential risks of death, personal injury, or severe property or environmental damage (“Critical Applications”). TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED, INTENDED, AUTHORIZED, OR WARRANTED TO BE SUITABLE FOR USE IN LIFE-SUPPORT APPLICATIONS, DEVICES OR SYSTEMS OR OTHER CRITICAL APPLICATIONS. Inclusion of TI products in such applications is understood to be fully at the risk of the customer. Use of TI products in such applications requires the written approval of an appropriate TI officer. Questions concerning potential risk applications should be directed to TI through a local SC sales office. In order to minimize risks associated with the customer’s applications, adequate design and operating safeguards should be provided by the customer to minimize inherent or procedural hazards. TI assumes no liability for applications assistance, customer product design, software performance, or infringement of patents or services described herein. Nor does TI warrant or represent that any license, either express or implied, is granted under any patent right, copyright, mask work right, or other intellectual property right of TI covering or relating to any combination, machine, or process in which such semiconductor products or services might be or are used. Copyright © 1998, Texas Instruments Incorporated Preface Read This First About This Manual The TMS320C3x/C4x Optimizing C Compiler User’s Guide tells you how to use these compiler tools: - Compiler Source interlist utility Optimizer Preprocessor Library-build utility This compiler accepts American National Standards Institute (ANSI) standard C source code and produces assembly language source code for the TMS320C3x/4x devices. This user’s guide discusses the characteristics of the TMS320C3x/4x optimizing C compiler. It assumes that you already know how to write C programs. The C Programming Language (second edition), by Brian W. Kernighan and Dennis M. Ritchie, describes C based on the ANSI C standard. Use the Kernighan and Ritchie book as a supplement to this manual. Before you can use this book, you should read the TMS320C3x/C4x Code Generation Tools Getting Started Guide to install the C compiler tools. Read This First iii How to Use This Manual / Notational Conventions How to Use This Manual 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 TMS320C3x/4x devices. This book is divided into three distinct parts: - Introductory information, in chapter one, provides an overview of the TMS320C3x/4x development tools. Compiler description, in chapter two, describes how to operate the C compiler and the shell program, and discusses specific characteristics of the C compiler as they relate to the ANSI C specification. It contains technical information on the TMS320C3x/4x architecture and includes information needed for interfacing assembly language to C programs. It describes libraries and header files in addition to the macros, functions, and types they declare. Finally, it describes the library-build utility. Reference material, in chapters three through six and the glossary, provides supplementary information on TMS320C3x/4x specific optimizations, and definitions of terms used in the book. Notational Conventions This document uses the following conventions. - Program listings, program examples, and interactive displays are shown in a special typeface similar to a typewriter’s. Examples use a bold version of the special typeface for emphasis; interactive displays use a bold version of the special typeface to distinguish commands that you enter from items that the system displays (such as prompts, command output, error messages, etc.). Here is a sample program listing: 0011 0012 0013 0014 0005 0005 0005 0006 0001 0003 0006 .field .field .field .even 1, 2 3, 4 6, 3 Here is an example of a system prompt and a command that you might enter: - C: csr –a /user/ti/simuboard/utilities In syntax descriptions, the instruction, command, or directive is in a bold typeface font and parameters are in an italic typeface. Portions of a syntax that are in bold should be entered as shown; portions of a syntax that are in italics describe the type of information that should be entered. Here is an example of a directive syntax: iv Notational Conventions .asect ”section name”, address .asect is the directive. This directive has two parameters, indicated by section name and address. When you use .asect, the first parameter must be an actual section name, enclosed in double quotes; the second parameter must be an address. - Square brackets ( [ and ] ) identify an optional parameter. If you use an optional parameter, you specify the information within the brackets; you don’t enter the brackets themselves. Here’s an example of an instruction that has an optional parameter: LALK 16–bit constant [, shift] The LALK instruction has two parameters. The first parameter, 16-bit constant, is required. The second parameter, shift, is optional. As this syntax shows, if you use the optional second parameter, you must precede it with a comma. Square brackets are also used as part of the pathname specification for VMS pathnames; in this case, the brackets are actually part of the pathname (they are not optional). - Braces ( { and } ) indicate a list. The symbol | (read as or) separates items within the list. Here’s an example of a list: { * | *+ | *– } This provides three choices: *, *+, or *–. Unless the list is enclosed in square brackets, you must choose one item from the list. - Some directives can have a varying number of parameters. For example, the .byte directive can have up to 100 parameters. The syntax for this directive is: .byte value1 [, ... , valuen ] This syntax shows that .byte must have at least one value parameter, but you have the option of supplying additional value parameters, separated by commas. Read This First v Related Documentation From Texas Instruments Related Documentation From Texas Instruments The following books describe the TMS320C3x/C4x and related support tools. To obtain a copy of any of these TI documents, call the Texas Instruments Literature Response Center at (800) 477–8924. When ordering, please identify the book by its title and literature number. TMS320C3x/C4x Code Generation Tools Getting Started Guide (literature number SPRU119) describes how to install the TMS320C3x/C4x assembly language tools and the C compiler. Installation instructions are included for MS-DOS™, Windows™ 3.x, Windows NT, Windows 95, SunOS™, Solaris, and HP-UX™ systems. TMS320C3x/C4x Assembly Language Tools User’s Guide (literature number SPRU035) describes the assembly language tools (assembler, linker, and other tools used to develop assembly language code), assembler directives, macros, common object file format, and symbolic debugging directives for the ’C3x and ’C4x generations of devices. TMS320C3x C Source Debugger User’s Guide (literature number SPRU053) tells you how to invoke the ’C3x emulator, evaluation module, and simulator versions of the C source debugger interface. This book discusses various aspects of the debugger interface, including window management, command entry, code execution, data management, and breakpoints. It also includes a tutorial that introduces basic debugger functionality. TMS320C4x C Source Debugger User’s Guide (literature number SPRU054) tells you how to invoke the ’C4x emulator and simulator versions of the C source debugger interface. This book discusses various aspects of the debugger interface, including window management, command entry, code execution, data management, and breakpoints. It also includes a tutorial that introduces basic debugger functionality. TMS320C3x User’s Guide (literature number SPRU031) describes the ’C3x 32-bit floating-point microprocessor (developed for digital signal processing as well as general applications), its architecture, internal register structure, instruction set, pipeline, specifications, and DMA and serial port operation. Software and hardware applications are included. TMS320C32 Addendum to the TMS320C3x User’s Guide (literature number SPRU132) describes the TMS320C32 floating-point microprocessor (developed for digital signal processing as well as general applications). Discusses its architecture, internal register structure, specifications, and DMA and serial port operation. Hardware applications are also included. vi TMS320 Third-Party Support Reference Guide (literature number SPRU052) alphabetically lists over 100 third parties that provide various products that serve the family of TMS320 digital signal processors. the university program. internal register structure. etc. The book gives additional information about the TMS320C30 evaluation module. Parallel Processing with the TMS320C4x (literature number SPRA031) describes parallel processing and how the ’C4x can be used in parallel processing. Also covered are available documentation. pipeline. etc. emulators. instruction set. Covered are its architecture. TMS320C30 Evaluation Module Technical Reference (literature number SPRU069) describes board-level operation of the TMS320C30 evaluation module. as well as C coding tips. and other TI DSPs. and factory repair and exchange. TMS320C4x General-Purpose Applications User’s Guide (literature number SPRU159) describes software and hardware applications for the ’C4x processor. Read This First vii . linkers. Also provides sample parallel processing applications. parts lists. specifications. and operation of its six DMA channels and six communication ports. ’C5x. TMS320 DSP Development Support Reference Guide (literature number SPRU011) describes the TMS320 family of digital signal processors and the tools that support these devices. etc. image processing. and XDS510 emulator design considerations. Digital Signal Processing Applications With the TMS320C30 Evaluation Module Selected Application Notes (literature number SPRA021) contains useful information for people who are preparing and debugging code. Included are code-generation tools (compilers. speech recognition. evaluation modules. A myriad of products and applications are offered—software and hardware development tools. seminars. ’C4x. developed for digital signal processing as well as parallel processing applications. noise cancellation.Related Documentation From Texas Instruments TMS320C4x User’s Guide (literature number SPRU063) describes the ’C4x 32-bit floating-point processor.). ’C3x. Also includes development support information.) and system integration and debug tools (simulators. assemblers. TMS320 DSP Designer’s Notebook: Volume 1 (literature number SPRT125) presents solutions to common design problems using ’C2x. modems. 1988. Krekelberg..Related Documentation / Trademarks Related Documentation Related Documentation The C Programming Language (second edition). You may find these documents helpful as well: Advanced C: Techniques and Applications. Gintaras R. by Brian W. Kernighan and Dennis M. SunOS is a trademark of Sun Microsystems. licensed exclusively through X/Open Company Limited. Inc.. Gircys. MS-DOS is a registered trademark of Microsoft Corporation. American National Standard for Information Systems—Programming Language C x3. Kochan. Gerald E. describes ANSI C. Inc. Hayden Book Company Understanding and Using COFF. PC-DOS is a trademark of International Business Machines Corporation. Solaris is a trademark of Sun Microsystems. XDS is a trademark of Texas Instruments Incorporated. and David E. Ritchie. Englewood Cliffs. published by O’Reilly and Associates.. Inc Trademarks HP-UX is a trademark of Hewlett-Packard Company. Steve G. viii . Sobelman. published by Prentice-Hall. New Jersey. Que Corporation American National Standards Institute C Specification.159–1989 (ANSI standard for C) Programming in C. You can use it as a reference. UNIX is a registered trademark in the United States and other countries. Factory Repair/Hardware Upgrades (281) 274-2285 U.com/pub/tms320bbs Email: [email protected] North America.tit.A. Middle East. please include the following information that is on the title page: the full title of the book. . Read This First ix . Technical Training Organization (972) 644-5580 DSP Hotline (281) 274-2320 Fax: (281) 274-2324 DSP Modem BBS (281) 274-2323 DSP Internet BBS via anonymous ftp to ftp://ftp. South America.tw/pub/TI/ - Japan Product Information Center +0120-81-0026 (in Japan) +03-3457-0972 or (INTL) 813-3457-0972 DSP Hotline +03-3769-8735 or (INTL) 813-3769-8735 DSP BBS via Nifty-Serve Type “Go TIASP” Fax: +0120-81-0036 (in Japan) Fax: +03-3457-1259 or (INTL) 813-3457-1259 Fax: +03-3457-7071 or (INTL) 813-3457-7071 Documentation When making suggestions or reporting errors in documentation. Africa European Product Information Center (EPIC) Hotlines: Multi-Language Support +33 1 30 70 11 69 Email: epic@ti. please specify the literature number of the book.com - Europe.com/dsps http://www. Box 1443 Houston.edu.If You Need Assistance If You Need Assistance . and the literature number. .com http://www.com Technical Documentation Services. the publication date.ti.com Deutsch +49 8161 80 33 11 or +33 1 30 70 11 68 English +33 1 30 70 11 65 Francais +33 1 30 70 11 64 Italiano +33 1 30 70 11 67 EPIC Modem BBS +33 1 30 70 11 99 European Factory Repair +33 4 93 22 25 40 Europe Customer Training Helpline Fax: +33 1 30 70 10 32 Fax: +49 81 61 80 40 10 - Asia-Pacific Literature Response Center +852 2 956 7288 Fax: +852 2 956 2200 Hong Kong DSP Hotline +852 2 956 7268 Fax: +852 2 956 1002 Korea DSP Hotline +82 2 551 2804 Fax: +82 2 551 2828 Korea DSP Modem BBS +82 2 551 2914 Singapore DSP Hotline Fax: +65 390 7179 Taiwan DSP Hotline +886 2 377 1450 Fax: +886 2 377 2718 Taiwan DSP Modem BBS +886 2 376 2592 Taiwan DSP Internet BBS via anonymous ftp to ftp://dsp.ee. MS 702 P.S. Mail: Texas Instruments Incorporated Email: [email protected]/sc/docs/dsps/support. Texas 77251-1443 Note: When calling a Literature Response Center to order documentation.ti.htm http://www.ti.S. - World-Wide Web Sites TI Online Semiconductor Product Information Center (PIC) DSP Solutions 320 Hotline On-line t http://www.S.ti.com/sc/docs/pic/home. (800) 477-8924 Software Registration/Upgrades (214) 638-0333 Fax: (214) 638-7742 U.O. Central America Product Information Center (PIC) (972) 644-5580 TI Literature Response Center U.ti.A. . . . . . –po Options) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 38 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 30 2. Discusses the interlist utility. . . 2 37 Using the C Compiler Optimizer . . . . . . . . . . . 2 46 Using the Interlist Utility . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Automatic Inline Expansion Option (–oisize Option) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 28 Controlling the Preprocessor . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . 2 45 2. . . . . . . assembles. . . . . . . . . . . .2. . and use of the linker and archiver with the compiler 2. . . 2 2 2. . . . . . . . . . . . . . . . . .Contents Contents 1 Introduction . . . . . . . . . . . . . . . . . . . . 2 28 2. . . . . . . 2 41 Function Inlining . . 2 32 2.4. . . . .5 Using the TMP Environment Variable . .2. . . . . . . . . . . . . .1. . . . . . 2 34 Using Runtime Models . . . . . .3 Using the Optimizer with the Interlist Option (–os option) . . . . . . . . . . . . . . . 2 1 Describes how to operate the C compiler and the cl30 shell program. . . . . . . .1 Predefined Names . . . .1. . . . . . . . . . . . . . . . . . . . . .5. . .2 Definition Controlled Inline Expansion Option (–x Option) . . .3 Compiler Options . . . . . . . . . . . . . . . . . . .4 Using the C_OPTION Environment Variable .4. . . . . . . . . . . . . . . . . . . . . . . . 2 36 2. . . . . . . . . . . . . 2 39 2. . . . . . . . . . . . .2 #include File Search Paths . . . . . . .1 Optimization Levels .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . .3 2. . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Specifying Filenames . . . . . . . . . . . . . . . . . . . . 2 31 2. . . . . . . . . . . . . . . . . . 1 5 C Compiler Description . . . . . . .2 The Register-Argument and Standard Models . . .4 2. . 2 43 2. . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . .4. . . . . . . . . . . . . .3 Generating a Preprocessed Listing File (–pl. . . . . . . . . . . . . . . . . . . . . .1 1. . . . . . . . . . . . . . . . . . . . 2 40 2. . . . . .1 The Big and Small Memory Models . . . . . . . . . . . . . 2 5 2. compiler options. . . . . .4. . . . . . . . . . . . . . . . Contains instructions for invoking the shell program. . . . . . . . . . . . . . . . .1. . . . . . . . . . .5 2. . . . . . . . . . . 2 45 2. . . . . . . . .2 2 Software Development Tools Overview . . . . .1 Invoking the C Compiler . . . . . . . . . . . . . . . . . . . . . . . 1 1 Provides an overview of the TMS320C3x/4x software development tools 1. . . . . . . . . . .4. . . . . 2 49 xi 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 . . . . . . compiler errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . –pn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 2 TMS320C3x/C4x C Compiler Overview . . . . . . .3 _INLINE Preprocessor Symbol . . . . . . . . .1 Controlling Inline Expansion (–x Option) . . . . . . . . . . . . . such as the optimizer. . . . . . . and for invoking the individual compiler components. . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 35 2. . . . . . . . . . and links a C source file. . . . . . . 2 4 2. 2 3 2. .1 Compiling C Code . . . . . . . . . . filename specifications. . . . . . . . . . . . . . . . . . . . .5 Special Considerations When Using the Optimizer . 2 40 2. . 2 40 2. . . . . . . . . . . . . . .4 Debugging Optimized Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . which compiles. .1. . . . . . . . . . . . . . .6 3. . . . . . . . . . . . . . . . . . . 3 16 The asm Statement . . . . . . . .10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 16 3. . . . . . . . . . . . . . . . . . . . . 3 21 Compatibility With K&R C (–pk Option) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . How the Compiler Handles Errors . . . . .8 3.4 The FUNC_EXT_CALLED Pragma . . . . . . . . . . .9 The FUNC_NO_IND_ASG Pragma . . . . . . . . . . . . . . . . . . . 3 15 3. . . . . . . . . . 3 1 Discusses the specific characteristics of the TMS320C3x/C4x C compiler as they relate to the ANSI C specification 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The cregister Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . 3 13 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . .1 Treating Code-E Errors as Warnings (–pe Option) . . . . . . . . . . . . . .3 Characteristics of TMS320C3x/C4x C . . . . . . . .2 Using the Shell to Invoke the Linker (–z Option) . . . . . . . . . . . . . . . . . . .2 The near and far Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Controlling the Linking Process . . . . . . . . . . . . . . . . . . . Invoking the Tools Individually . . . . . . . . . . . . . . .3. . . . . . . . . . .3 The FUNC_CANNOT_INLINE Pragma . . .3 An Example of How You Can Use Error Options . . . . . . . . . . . . . . . . . . . . . . . . 3 5 Keywords .5. . .1 Using the Interlist Utility Without the Optimizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 10 Pragma Directives . 3 8 Register Variables . . . . . . . . . .2 Using the Interlist Utility With the Optimizer . . . . . . .4 Invoking the Interlist Utility . . . . . . . .8 The FUNC_NO_GLOBAL_ASG Pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 3. . . . . . . . . . . . . . . 3 24 3. . . . . . . . . . . . . . . . . . . . . .2 The DATA_SECTION Pragma . . . . . Intrinsics . . 2. . . . . .1 The Long Double Data Type . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . .10 3. . . . . .5.5. . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . .5. . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 12 3. . . 3 7 3. . . . . . . . .7 The FUNC_NEVER_RETURNS Pragma . . . . . . . . . . . . . . . . . . .2 Suppressing Warning Messages (–pw Option) . . . . . . . . . .9. . . . . . .7 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 15 3. . . . . . . . . . . . .5. . . . . . . .9 2. . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 14 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . .9. . . . . . . . . . . . . . . . .Contents 2. . . . . . . . . . . . . . . . . . . .2 Optimizing Parser Output . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 49 50 51 52 52 53 54 56 57 59 62 64 65 65 66 68 3 TMS320C3x/C4x C Language . . . . . . . . . . . . . . .7. . . . . . . 3 14 3. . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 The FUNC_IS_SYSTEM Pragma . . . . . . . . . . . . . .3 Invoking the Code Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . Linking C Code . . . . . . . . . .10. . . . . . . . . . . . . . . . . . . . . . . . 3 17 Initializing Static and Global Variables . . . . . . . 2. . . 2. . . . . . . .10 2. . . . . 3 15 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 2. . 3 2 Data Types . . . . . 3 13 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 7 3. . . . . .7 3. . . . . . . . . . . . . . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . .5 The FUNC_IS_PURE Pragma . . . . 3 11 3. . . . . . 3 18 Far Call Support . . . . . . . . . . . . . . . . . . . . . . . .1 3. . 3 22 Compiler Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 3. . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . 2. . . . . . . . . 2. .11 xii . .9 3. . . . . . . . . . . . . . . . . . .1 The CODE_SECTION Pragma . . . . . .9. . . . . .4 3. . . . . . .10 The INTERRUPT Pragma . . . . . . . . . . . . . . . . . .1 Invoking the Parser . . . . . . . . . .1 Invoking the Linker . . . . . . . . . . . . . . . . . . . . 3 20 Delay Slot Filling for Branches . . . . . . . . . . . . 2. 2. . . .4 Character String Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 35 4. . . . . . . . . . . . . . 4 31 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1 Describes the header files included with the C compiler. . . . . . . .4 Big and Small Memory Models . . . . .1 Function Call. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 16 4. . . . . .2 Object Representation . Summarizes the runtime-support functions according to category (header). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Interrupt Handling . . . . 4 22 4. 4 7 4. . . . . . . . . . . . . . . . . . . . . 4 13 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 12 4. . . . . . . . . . . . .3 Inline Assembly Language . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . 4 4 4. . . . . . . . . . . . . . . . stack organization. . . . . . . . . . .5 The Constant Table . .1 Runtime-Support Libraries . . . . . . . . . . . . . . . . 4 7 4. .7. . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 11 4. . . . . . . . . . 4 5 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2 4. . . . . . . . .4 Stack and Frame Pointers . .5 Interfacing C With Assembly Language . .3. . . . . .4. . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . 4 30 4. . . . . . . . . . . 4 14 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Memory Model . . .3 Return Values . . . . . . 4 15 4. . . . . . . . . 4 13 4. . . . . . . . . . . .4. . . . 4 1 Contains technical information on how the compiler uses the TMS320C3x/C4x architecture. . . . . . . . . 4 7 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . .1 Autoinitialization of Variables and Constants . . . .2 Long Immediate Values . . . 4 6 4. . . . . . . . . . . . 5 2 Contents xiii 5 . .3. . 4 7 4. . . . . . . . . . . . . . . . functions. .2 Expression Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Data Type Storage . . . . . . . . Standard Runtlme Model . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . function-call conventions. . . . . . . . . . . . . . . . . . . . .3 Dynamic Memory Allocation . . . . . . . . . . . . . . . .2 Function Call. . . . . . . . . . . . . . . . . . . . .2 C System Stack . . . . . . . . . . . . . . . . . . . . . . . . . .3 Register Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . 4 8 4. . . . . . . . . .8 System Initialization . .4 Accessing Arguments and Local Variables . . . . . . . . . . . . . . . . system initialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . 4 12 4. . . .2 Assembly Language Interrupt Routines . . . . . . . . . . . . . . 4 25 4. . . . . . . . . . . . . .8. . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Discusses memory and register conventions. . . . . . .4 Function Structure and Calling Conventions . 4 21 4. . . . . . . . . . . . . . . . . . . .2 Accessing Assembly Language Variables From C . . . . . . . . . . . . . . . . . .1. . 4 36 4. . . . . . . . . as well as the macros. . .1. . . . . . . . . Register Argument Runtime Model . 4 2 4. . . .5. . . . . . . . 4 17 4. . . 4 32 4. . . . . . . . .5 Other Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . .3 Addressing Global Variables . Provides information needed for interfacing assembly language to C programs 4. . . . . . . . . . . . . . . . . . 4 19 4. . . . . .1. . . . . . . . . . .Contents 4 Runtime Environment . . . . 4 36 Runtime-Support Functions . . . . . . . . . . . . . . . . . .1 Assembly Language Modules . . . 4 3 4. . . . . . . . and types they declare. . . . . . . . . . . . . . . . . . . . . . . . . .1 Precision Considerations . . . . . .6. . . . . . . . . . . . 4 22 4. . . . . . .4. . . . 4 9 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . .1 Register Variables . . . . . . . . . .7 Runtime-Support Arithmetic Routines .3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . 4 30 4. . . . 4 28 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 RAM and ROM Models . . . . . . . . . . .1 Saving Registers During Interrupts . . . . . . . . . . . . and provides an alphabetical reference of the runtime-support functions 5. . . . . . . . . . . . . . . . . . . . . . . . . and TMS320C3x/C4x C compiler optimizations. . . . . . . . . . . . . . .1 Sections . .5. . . . . . . . . . . . . . . . .1. . . . . . . . . .3 Responsibilities of a Called Function . .1 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 9 5. . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . This utility can also be used to install header files in a directory and to create custom libraries from source archives 6. . . . . . . . . .3. . . . . . . . . . . . .h) . . . . . . . . . . . . . . . . . . .h) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . 5 5 5. . . . . . . .2. . . . . .2 5. . . . . . . . . . . . . . . . . . .h) . . . . . . . . . . . . . . . 5 8 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . 5 4 5. . . . . . . . . . . . . . . . . . . .2 B. . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B 5 B C Glossary . . . . . . . .2. . . . . . . . . . . .5 Limits (float. . . . . . . . . .13 Time Functions (time. . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 11 Summary of Runtime-Support Functions and Macros . . . . . . . . . . . . . . . . . . . . . . . . . .6 Floating-Point Math (math. . . . . . .2. . . . . . . . . .h) . . .1 Diagnostic Messages (assert. . . . . . . . . . . . . . . . . . .2. . . . . . . . . 5 10 5. . . . . . . .4 6 5. . . . . . . . . . . . . . . .h) . . . . . . . . . . 5 21 Library-Build Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 Standard Definitions (stddef. . B 1 Describes the C I/O library included with the C compiler. . . . . . . . . . . 5 5 5. . . . . . . . . . . . . . . . . . . . . . B 2 Overview of Low-Level I/O Implementation . . . . D 4 D xiv . .2. . . . . . . . . . . . . . . . . .h) . . . . . . . . . . . . . . . . . . . . . . . . . .10 stdio. . . . . . . . . . . . 5 5 5. . . . . . . . . . . . . . . . . . . . . . . . . .h) . . . . . . . . . . . . B 3 Adding a Device For C I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Using the I/O Functions . . . . . . . . . . . . . . . .4 Low-Level I/O Functions (file. . . . . . . . . . . . . .1 B. . . . . .2. . . . . . . . . . . . . . . . . . 5 6 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 13 Functions Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1 Describes the utility that custom-makes runtime-support libraries for the options used to compile code. . . . 5 11 5. . . . . . . . . . . . . . . . . . . . . . . . . .3 5.h) . . . . . . . . . . .h) . . . . . . . . . . . . . . 5 3 5. . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . .Contents 5. . . . . . . . . . . . . . . . . . . 5 3 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Modifying a Library Function . . . . . . . . .2 Invoking the Library-Build Utility . . . . . . . . . . . . . . . . . . .2 Building a Library With Different Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 8 5. D 3 3. . . . . . . . . . . . . . . .1 The cregister Keyword . . . . . . . . . . . . . . . . .2. . .11 General Utilities (stdlib. . . . . . . . . . . . . . .h—I/O Functions . B. . . . . . . . . . . . . . . . . . . . . . . . . .2 Character-Typing and Conversion (ctype. . . . . . . . . . . . . . . .h) . . C 1 Defines terms and acronyms used in this book Summary of Updates in This Document . . . . . . . . . . . . .h) . . . . .8 Variable Arguments (stdarg. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 1 Describes general optimizations that improve any C code and specific optimizations designed especially for the TMS320C3x/C4x architecture The C I/O Functions . . . . . . 5 9 5.h) . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . .2 The near and far Keywords . . . . . . . . . .12 String Functions (string. . . . . . . . . D 1 Provides a summary of the updates in this version of the document 3. . . . . . . . . . . . .1. . 6 2 Options Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .h and limits. . . . . . . . . .1 6. . . . . . . 6 4 A Description of Compiler Optimizations . . . . . . . . . . . . . . . . .3 Error Reporting (errno. . . . . .2. . . . . . . . . . . . . 5 8 5. . . . . . . . . . . . . . . . . . . . . . . 5 4 5. . . . . . . . . . . . . . . . . . . .7 Nonlocal Jumps (setjmp. . . . . . . . . . . . . . . . D 3 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 37 RAM Model of Autoinitialization . . . . . . . . . . . . . . . . . . . . B 3 The First Three Streams in the Stream Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B 4 Contents xv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 40 Interaction of Data Structures in I/O Functions . . . . . . . . . . . . . . . . . . . . . . .Figures Figures 1–1 2–1 2–2 2–3 2–4 2–5 4–1 4–2 4–3 4–4 4–5 B–1 B–2 TMS320C3x/C4x Software Development Flow . . . . . . . . . . . . . . . 1 2 The cl30 Shell Program Overview . . . . . . . 2 38 Compiler Overview . . . . . . . . . . . . . . . .cinit Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 72 Sample Linker Command File for TMS320C4x C Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 17 Format of Initialization Records in the . . . . . . . . . . . . . . . . . . . 2 2 Compiling a C Program with the Optimizer . . . . . . . . . . . . . . . . . . . . . 4 16 Register Argument Conventions . . . . . . 2 73 Stack Use During a Function Call . . . . . . . . . . . . . . . . . . . . 4 39 ROM Model of Autoinitialization . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 56 Sample Linker Command File for TMS320C3x C Programs . . . . . . . . . . . 4 34 Macros That Supply Integer Type Range Limits (limits. . . . . . . . . .h) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 61 Code Generator Options and Shell Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 63 Sections Created by the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 6 Predefined Macro Names . . . . 4 19 Summary of Runtime-Support Arithmetic Functions . . . . . . . . . . . . . . . . . . . 4 11 Registers Reserved for Register Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 70 TMS320C3x/C4x C Data Types . . . . . . . . . . . . 5 7 xvi . . . . . . . . . . . . 3 7 Absolute Compiler Limits . . . . . . . . . . . . . 2 54 Parser Options and Shell Options . . . . . . . . . . . . . . . . . 3 25 Register Use and Preservation Conventions . . . . . . . 2 58 Optimizer Options and Shell Options . . . . . . . . . . 5 6 Macros That Supply Floating-Point Range Limits (float. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .h) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .Tables Tables 2–1 2–2 2–3 2–4 2–5 2–6 2–7 3–1 3–2 3–3 4–1 4–2 4–3 4–4 5–1 5–2 Compiler Options Summary Table . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 4 Valid Control Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 12 Runtime-Support Functions Using Modified Calling Convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 31 Supported Intrinsic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 5 TMS320C3x/C4x Delayed Branch Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and Loop Test Replacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . part two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Register Variables. . . . . . . . . 4 28 Register Variables and Register Tracking/Targeting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . part one . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Parallel Instructions. . . . . . . A 11 Copy Propagation and Control-Flow Simplification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 47 An Interlisted Assembly Language File . . . 3 13 An Assembly Language Function Called From C . . . . Strength Reduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Induction Variable Elimination. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 26 Accessing a Variable Not Defined in . . . . . . . . . . . . . . . . . . . . . . 4 27 Accessing an Assembly Language Constant From C . . . . . . .bss From C . . . . . . . . . . . . . . . . . . 2 49 Define and Use Control Registers . . . . . . . . . . . . . . . . . . . . . . A 15 Inline Function Expansion. . . . . . .bss From C . . . . . . . . . . . . . . . . 3 12 Using the DATA_SECTION Pragma . . .Examples Examples 2–1 2–2 3–1 3–2 3–3 4–1 4–2 4–3 4–4 A–1 A–2 A–3 A–4 A–5 A–6 A–7 A–8 A–9 How the Runtime Support Library Uses the _INLINE Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A 14 Inline Function Expansion. . . . . . . A 6 TMS320C4x-Specific Features . A 13 Loop Unrolling . . . . . . . . . . . . . . . . . Autoincrement Addressing. . A 16 Contents xvii . . . . 4 25 Accessing a Variable Defined in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 8 Using the CODE_SECTION Pragma . . . . . . A 8 Data-Flow Optimizations . . . . . . . . . . . . A 3 Repeat Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 36 All Functions Must Be Prototyped . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 41 Function Inlining May Greatly Increase Code Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 4 Avoid Locals and Arguments With Large Offsets . . . . 2 37 Files That Redefine Standard Library Functions . . . . . . 4 29 Initializing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 2 Stack Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 37 Variable–Argument Functions Must Have Prototypes . 3 5 Avoid Disrupting the C Environment With asm Statements . . . . . . . . . . . . . . . 5 8 Writing Your Own Clock Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 76 Use Unique Function Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and Warnings Notes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 17 The Linker Defines the Memory Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 44 A TMS320C3x/C4x Byte Is 32 Bits . . . . . . . . . . . . . . . . 4 21 Assembler Support for Runtlme Models . . . . . . 2 40 Symbolic Debugging and Optimized Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cautions. . . . . . . 5 51 Writing Your Own Time Function . . . . . . . . . . . . . . . . . . . . . . 5 33 Accessing Objects After Calling the minit Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and Warnings Size Restrictions on Small Model are not Tested . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B 5 xviii . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 27 Avoid Disrupting the C Environment With asm Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Cautions. . . . . . 4 22 Use the –mf Option When Using the Optimizer . . . . . . . . .Notes. . . . . . . . . . . . . . . The TMS320C3x/C4x DSPs are fully supported by a complete set of code generation tools including an optimizing C compiler. . . . . . an archiver. . . This chapter provides an overview of these tools and introduces the features of the optimizing C compiler. a full-speed emulator. 1-2 TMS320C3x/C4x C Compiler Overview . . . The assembler and linker are discussed in detail in the TMS320C3x/C4x Assembly Language Tools User’s Guide. . . . . . an assembler. . . . . . . . . . . . . and a software development board. . 1-5 Introduction 1-1 .1 1. . a linker.Chapter 1 Introduction The TMS320 family of digital signal processors (DSPs) combines the high performance required in DSP applications with special features for these applications. . . . . . . . . . . . .2 Page Software Development Tools Overview . . . . . . Topic 1. a software simulator. . . . . the other portions are optional. Figure 1–1. TMS320C3x/C4x Software Development Flow C Source Files Macro Source Files C Compiler Archiver Assembly Language Source Macro Library Assembler Archiver COFF Object Files Library-Build Utility Library of Object Files Linker RuntimeSupport Library Hex Conversion Utility Executable COFF File EPROM Programmer Target System: TMS320C3x TMS320C4x Debugging Tools 1-2 .Software Development Tools Overview 1. The shaded portion of the figure highlights the most common path of software development.1 Software Development Tools Overview Figure 1–1 illustrates the TMS320C3x/C4x software development flow. Eight object libraries are shipped with the C compiler. J J J rts. One of the most useful applications of the archiver is building a library of object modules. to build your own customized runtime-support library.3 for a description of these libraries. extracting. The archiver (ar30) allows you to collect a group of files into a single archive file. it performs relocation and resolves external references. The TMS320C3x/C4x Assembly Language Tools User’s Guide explains how to use the assembler. - The assembler translates assembly language source files into machine language object files.src contains C and assembly language routines for handling peripherals/interrupts for ’C3x devices Introduction 1-3 . mathasm. The linker (lnk30) combines object files into a single executable object module. or adding members. called a library. an optimizer (opt30). See Section 2. and the interlist utility. A shell program (cl30). replacing. The linker accepts relocatable COFF object files and object libraries as input. The interlist utility interlists C source statements with assembly language output. Use the library-build utility (mk30). J J J The shell program enables you to automatically compile. Chapter 2 describes how to invoke and operate the compiler. and an interlist utility (clist) are included in the compiler package. The optimizer modifies code to improve the efficiency of C programs. and link source modules. Standard runtime-support library functions are provided as source code. The machine language is based on common object file format (COFF). the optimizer. These libraries contain ANSI–standard runtime support functions and compiler–utility functions for the TMS320C3x and TMS320C4x.src contains standard runtime functions for the TMS320C3x/C4x processors. As it creates the executable module.src contains assembly language source for trigonometric functions prts30. It also allows you to modify a library by deleting.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 TMS320C3x or TMS320C4x assembly language source code. the shell. assemble. The TMS320C3x/C4x Assembly Language Tools User’s Guide explains how to use the hex conversion utility. and monitor the execution of your program as it runs on the debugging platform. These debugging platforms share a common screen-oriented interface that allows you to display machine status information. inspect and modify C variables.src contains C and assembly language routines for handling peripherals and interrupts for ’C4x devices The hex conversion utility (hex30) converts a COFF object file into ASCII–hex. The converted file can be downloaded to an EPROM programmer. in-circuit emulator that features the same screen-oriented interface as the simulator An EVM (evaluation module). An XDS (extended development system) emulator. You can use one of several debugging tools to refine and correct your code before downloading it to a TMS320C3x/C4x target system. display C source code. which is a PCresident. or Tektronix object format. TI–Tagged. The main purpose of this development process is to produce a module that can be executed in a TMS320C3x/C4x target system. The simulator executes linked COFF object modules. real-time. Intel. Motorola–S. such as a C30. that can be used to evaluate CPU performance 1-4 .Software Development Tools Overview J - prts40. Available debugging tools include: - An instruction-accurate software simulator that simulates the TMS320C3x/C4x functions. which is a plug-in PC board that contains a target CPU. 1 on page 2-36. Big and Small Memory Models The compiler supports two memory models. enabling you to see the code generated from the C source files. Optimization The compiler uses a sophisticated optimization pass that employs several advanced techniques for generating efficient. These extensions provide maximum portability and increased capability.2 TMS320C3x/C4x C Compiler Overview The TMS320C3x/C4x C compiler is a full-featured optimizing compiler that translates standard ANSI C programs into TMS320C3x/C4x assembly language source. The ANSI standard includes recent extensions to C that are now standard features of the language. which enables you to compile. refer to subsection 2. Compiler Shell Program The compiler package includes a shell program. ANSI Standard Runtime Support The compiler package comes with eight complete runtime libraries. The following list describes key features of the compiler: ANSI Standard C The TMS320C3x/C4x compiler fully conforms to the ANSI C standard as defined by the ANSI specification and described in Kernighan and Ritchie’s The C Programming Language (second edition). Introduction 1-5 .3.4 on page 2-38 and to Appendix A. The libraries include functions for string manipulation. and TMS320C3x/C4x-specific optimizations take advantage of the particular features of the TMS320C3x/C4x architecture. Assembly Source Output The compiler generates assembly language source that is easily inspected. The big memory model allows unlimited data space. For more information about the C compiler’s optimization techniques. All library functions conform to the ANSI C library standard. because these are target-system specific. data conversion. and trigonometry.TMS320C3x/C4x C Compiler Overview 1. compact code from C source. For more information.1 on page 2-2. assemble. General optimizations can be applied to any C code. refer to Section 2. timekeeping. refer to Section 2. For more information. refer to Chapter 5. and link programs in a single step. Functions for I/O and signal handling are not included. plus exponential and hyperbolic functions. For more information. The small memory model enables the compiler to efficiently access memory by restricting the global data space to a single 64K-word data page. dynamic memory allocation. Runtime Environment. int. refer to Section 3. refer to Section 2. For more information.2 on page 3-4.6 on page 2-49. and double are 32 bits. This utility provides you with an easy method for inspecting the assembly code generated for each C statement. long. 1-6 . For more information. allowing you to easily write assembly and C functions that call each other. COFF also provides rich support for source-level debugging. Standalone preprocessing or preprocessed listing is also available. 32-Bit and 40-Bit Data Sizes Data sizes char. Integrated Preprocessor The C preprocessor is integrated with the parser. Source Interlist Utility The compiler package includes a utility (clist) that interlists your original C source statements into the assembly language output of the compiler. Library-Build Utility A library-build utility called mk30 allows you to easily custom-build object libraries from source for any combination of runtime models or target CPUs. refer to Chapter 4. allowing for faster compilation. ROM-able Code For standalone embedded applications. This maximizes performance by enabling you to link C code and data objects into specific memory areas. This allows all types of data to take full advantage of the TMS320C3x/C4x integer and floating-point arithmetic capabilities. float. the compiler enables you to link all code and initialization data into ROM. refer to Section 2.TMS320C3x/C4x C Compiler Overview Flexible Assembly Language Interface The compiler has straightforward calling conventions. allowing C code to run from reset.2 on page 2-30. Data size long double is 40 bits. COFF Object Files Common object file format (COFF) allows you to define your system’s memory map at link time. For more information. short. For more information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and link your programs. . . . . . . .7 2. . . . . . . . . . . . . . . . . 2-49 How the Compiler Handles Errors . . . . 2-30 Using Runtime Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . and link your source files to create an executable object file. . . . . . . You must compile. . . . . . . . . . The interlist utility is explained in Section 2. 2-56 2. . . . . . . . . . . . .2 2. . . . . . . . . . . . . . . . . assemble. . . . . . . . . . The optimizer is explained in Section 2.6. . . . . . . . . . . . . .Chapter 2 C Compiler Description Translating your source program into code that the TMS320C3x/C4x can execute is a process consisting of several steps. 2-35 Using the C Compiler Optimizer .9 Page Compiling C Code . . . . . . . . . . . . . . . . . . . . . . . 2-38 Function Inlining . . . . . . . . . . . . . 2-54 Invoking the Tools Individually .6 2. . . . . . . . . . . . 2-2 Controlling the Preprocessor . . . . . .1 2. . . .3 2.10 Linking C Code .8 2. The compiler package also includes a utility that interlists your original C source statements into the compiler’s assembly language output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This chapter includes the following topics: Topic 2. 2-65 C Compiler Description 2-1 . . . . . . . . . . . . . . . . assemble. . . . . . . The TMS320C3x/C4x package contains a special cl30 shell program that enables you to execute all of these steps with one command. . . . . . . . . This chapter provides a complete description of how to use the shell program to compile. . . . . . . . 2-43 Using the Interlist Utility . . . . . . . . . . . . . . . . . . . . .4. . . .5 2. . . . . . . . . . . . . . 2-51 Intrinsics . . . . . . . The TMS320C3x/C4x C compiler includes an optimizer that allows you to produce highly optimized code. . . . . This enables you to inspect the assembly language code generated for each C statement. . . . .4 2. For more information about the floating-point assembler and linker. The cl30 Shell Program Overview C Compiler Parser Optimizer (Optional) Code Generator C Source Files Assembler Source Assembler Linker COFF Object Files Executable COFF File 2-2 .1 Compiling C Code The cl30 shell program is a utility that lets you compile. refer to the TMS320C3x/C4x Assembly Language Tools User’s Guide. and optionally link in one step. which generates a COFF object file. Figure 2–1. or you can compile and assemble various files with the shell and link at a later time. The shell runs one or more source modules through the following: The compiler The assembler The linker (optional) which includes the parser. if you use the –z option. The linker can be invoked as part of the larger process. and the code generator. Figure 2–1 illustrates the path the shell takes with and without the –z option. however. the optimizer. assemble. the shell also links your files. which links your files to create an executable object file. By default.Compiling C Code 2. the shell compiles and assembles files. if you wanted to compile two files named symtab and file.asm. –options filenames –z link_options object files Options control how the compiler processes files. and the filenames provide a method of identifying source files. Options and filenames can be specified in any order on the command line.1. However. is the option that runs the linker.1 Invoking the C Compiler To run the compiler. For example.Compiling C Code 2. intermediate files. the –z option and its associated information must follow all filenames and compiler options on the command line. and use the quiet option (–q). or object files. control the linking process. Entering the command above produces: [symtab] [file] <seek. enter: cl30 [–options] [filenames] [–z [link_options] [object files]] cl30 is the command that invokes the compiler and the assembler. assemble a third file named seek. it prints the filename in square brackets [for C files] or angle brackets <for asm files>. The example above uses the –q option to suppress the additional progress information that cl30 produces. and output files. assembly source files. you would enter: cl30 –q symtab file seek. affect the way the compiler processes input files.asm> C Compiler Description 2-3 . are one or more C source files. name the object files that the compiler creates.asm As cl30 encounters each source file. 2 Specifying Filenames The input files specified on the command line can be C source files.c”:==> main ”symtab. Texas Instruments Incorporated ”symtab. .Compiling C Code The normal progress information consists of a banner for each compiler pass and the names of functions as they are defined. as shown in the example on page 2-3. No Warnings 2.o* (extension begins with o) File Type assembly language source file C source file object file Files without extensions are assumed to be C source files.c extension (by default. use the appropriate form. and a . causing the shell to associate different extensions with assembly source files or object files.c”:==> lookup TMS320C3x/4x ANSI C Codegen Version x. The conventions for filename extensions allow you to compile C files and assemble assembly files with a single command. Texas Instruments Incorporated ”symtab.c 2-4 . The shell uses filename extensions to determine the file type. You can also use the –f option on the command line to override these file type interpretations for individual files.abs. enter the following (DOS system): cl30 *.asm. or object files.c extension is assumed. Texas Instruments Incorporated PASS 1 PASS 2 No Errors. all C files). The example below shows the output from compiling a single module without the –q option.c”:==> main ”symtab. To compile all the files in a directory that have a . refer to page 2-14.s* (extension begins with s) . Extension .xx Copyright (c) 1987–1997. For more information about the –e and –f options. Wildcard specifications vary by system. assembly source files.c or no extension .1.c”:==> lookup TMS320C3x/4x COFF Assembler Version x. or . You can use wildcard filename specifications to compile multiple files. You can use the –e option to change these default extensions.xx Copyright (c) 1987–1997.xx Copyright (c) 1987–1997. $ cl30 symtab [symtab] TMS320C3x/4x ANSI C Compiler Version x. 1. The table is followed by in-depth descriptions of each of the options. –mrq is invalid. such as –uname and –idir. on page 2-28. –sgq is equivalent to –s –g –q. You can set up default options for the shell by using the C_OPTION environment variable. Using the C_OPTION Environment Variable. Compiler options: - Consist of single letters or letter groupings Are not case sensitive Are preceded by a hyphen Can be combined if there are single-letter options without parameters: for example. refer to subsection 2. For example.1.4. an option summary table. Table 2–1 summarizes all compiler options. Cannot be combined with other options if they have parameters. Cannot be combined in a grouping that contains a two-letter pair option and a single-letter option. because it would be parsed as –mr and –mq. For a detailed description of the C_OPTION environment variable.Compiling C Code 2. and a detailed description of each of the options. C Compiler Description 2-5 . Can be combined if two-letter pair options without parameters have the same first letter: for example. –mr and –mb can be combined as –mrb. This section provides a description of option conventions.3 Compiler Options Command line options control the operation of both the shell and the programs it runs. For more information. otherwise interlist C and assembly source statements interlist C and assembly source statements undefine a constant specify processor.asm file) suppress progress messages (quiet) suppress all messages (super quiet) interlist optimizer comments and assembly source statements if available. xx = 30. Example: –msrev6 –v31 : enable new (1996) ’C31 parallel instructions –msrev2 – v32 : enable new (1996) ’C32 parallel instructions –n –q –qq –s compile only (create . or 44 (default is –v30) (see also –msrev) enable linking (all options following are passed to linker) –ss –uname –vxx –z 2-6 . Compiler Options Summary Table General Shell Options These options control the overall operation of the cl30 shell. 40.Compiling C Code Table 2–1. 32. information see page 2-12.asm file specifies the silicon revision of the target chip to enable additional functionality for more recent silicon releases. 31. Option –@filename –c –dname[=def] –g –idir –k –msrevx Effect causes the compiler shell to read options from the specified file no linking (negates –z) predefine a constant enable symbolic debugging define #include search path keep . Used in conjunction with –v flag. For more information. checking and errorhandling behavior of the compiler. Compiler Options Summary Table (Continued) File Specifiers These options use the extensions of each filename to determine how to process the file. see page 2-16.s*) identify C source file (default for . Option –pe –pf –pk –pl –pm –pn –po –pr –pw1 –pw2 –px filename Effect set default extension for assembly files set default extension for object files identify assembly language file (default for .pp) file combines source files to perform program-level optimization suppress #line directives in . For more file information.Compiling C Code Table 2–1. 2-14.o*) specify object file directory specify assembly file directory override TMP environment variable Effect treat code-E errors as warnings generate prototypes for functions allow compatibility with pre-ANSI K&R C generate preprocessed listing (. Option –ea –eo –fa file –fc file –fo file –frdir –fsdir –ft Parser Options These options control the preprocessing.pp file preprocess only write parser error messages to file enable serious warning messages (default) enable all warning messages names the output file created when using the –pm option –pw0 (or –pw) suppress all warning messages C Compiler Description 2-7 .asm or .c or no extension) identify object file (default for . syntaxchecking. see page 2 14. Compiler Options Summary Table (Continued) These options control the preprocessing. refer to page 2-18. Options –x0 –x1 –x2 Option –tf –tp Effect disable inlining default inlining level define _INLINE + invoke optimizer at level 2 Effect relax prototype checking relax pointer combination checking 2-8 . For more information. Type-Checking Options These options allow relaxation of compiler ty e-checking rules type-checking rules.Compiling C Code Table 2–1. For more information. refer to page 2-19. –p? enable trigraph expansion Inlining Options These options control expansion of functions declared as inline. For more information. see page 2-16. and errorhandling behavior of the compiler. syntaxchecking. Compiling C Code Table 2–1. For more information. Options –ma –mb –mc –mf –mi –ml –mm –mn –mp Effect assume aliased variables select big memory configuration use faster float to int conversions force indirect access to external objects. far data flag disable RPTS instructions use far calls for runtime support assembly calls enable short multiply (’C3x only) reenable optimizer options disabled by –g perform speed operations at the cost of conservatively increased code size use TI register argument model assume all memory is accessible when optimizing (see page 2-22) generate Ada compatible frame structure generate legacy Tartan C function names Effect create absolute listing predefine a constant produce assembly listing file keep labels as symbols undefine a constant produce cross-reference file –mr –ms –mt –mtc Assembler Options These options control the assembler’s behavior. g Options –aa –adname[=def] –al –as –auname –ax C Compiler Description 2-9 . Compiler Options Summary Table (Continued) Runtime Model Options These options are used to customize the executable out ut output of the com iler for compiler y your specific application. see page 2-20. For more information. see information page 2-23. and the –z option must follow all other options and fil th ti d filenames on the command line. Compiler Options Summary Table (Continued) Linker Options These options are valid only when the compiler has been invoked with the –z option for linking. They control the linking process.Compiling C Code Table 2–1. see page 2-23. g Options –a –ar –b –c –cr –e sym –fval –g name –h –heap size –heap8 size –heap16 size –i dir –l lib –m file –n –o file –q –r –s –stack size –u sym –vval –w Effect generate absolute output generate relocatable output disable the merging of symbolic debug information use ROM initialization use RAM initialization define entry point define fill value keep named global regardless of the use of –h set heap size (words) set heap size (words) for 8–bit memory (C32) set heap size (words) for 16–bit memory (C32) define library search path supply library name name the map file ignore all fill specifications in memory directives name the output file suppress banner and progress information generate relocatable output strip symbol table set stack size (bytes) undefine entry point generates version val COFF generate warning if output section is created that was not specified with SECTIONS directive force rereading of libraries symbol make all global symbols static –x 2-10 . For more information. They must follow the –z option on the z command line. For more information. but modifiable functions may be used interlist optimizer comments with assembly source statements allow zero-overhead loop operations –op1 –op2 –op3 –os –ou C Compiler Description 2-11 .Compiling C Code Table 2–1. Compiler Options Summary Table (Continued) Optimizer Options These options control the behavior of the optimizer. see 2 26 page 2-26. Options –o0 –o1 –o2 (or –o) –o3 –oisize –ol0 (–oL0) –ol1 (–oL1) –ol2 (–oL2) –on0 –on1 –on2 –op0 Effect perform level 0 (register) optimization perform level 1(level 0 + local) optimization perform level 2 (level 1 + global) optimization perform level 3 (level 2 + file) optimization set automatic inlining size (–o3 only) specify that this file alters a standard library function specify that this file defines a standard library function specify that this file does not define or alter library functions disable optimizer information file produce optimizer information file produce a verbose information file specify that callable functions and/or modifiable variables are used in this module specify that no callable functions are used in this module (default) specify that no modifiable variables or callable functions are used in this module specify that no modifiable variables are used in this module. Compiling C Code General Shell Options You can use the options described below to control the overall operation of the cl30 shell. causes the shell to compile only. This option is especially useful when you have –z specified in the C_OPTION environment variable and you don’t want to link.2. be sure to separate –i options with spaces. This is equivalent to inserting #define name def at the top of each C source file. –dname sets name equal to 1. For more information. You can use this option a maximum of 32 times to define several directories. The commands can be on one line or on several lines.) or a pound (#) character and end at the end of a line or can begin with the characters “/*” and end with “*/”. –idir –k –n 2-12 . –g causes the compiler to generate symbolic debugging directives that are used by the C source level debuggers and/or the interlist utility. but using –k allows you to retain the assembly language output from the compiler. suppresses the linking option. refer to subsection 2. If you use –n. Options in addition to those specified in the command file can be specified on the command line or with the C_OPTION environment variable. adds dir to the list of directories to be searched for #include files. For more information. Comments in the command file can begin with a semicolon (. refer to page 2-67. This option overrides –z and –c. the shell deletes the output assembly language file after assembling completes. keeps the assembly language file.2 on page 2-32. it causes the shell not to run the linker even if –z is specified. The output of –n is assembly language output from the compiler. –@filename read shell options and commands from a command file. Note that if you don’t specify a directory name. –c –dname[=def] predefines the constant name for the preprocessor. the specified source files are compiled but not assembled or linked. Normally. If the optional def is omitted. the preprocessor ignores the –i option. and interpreted by.10. see Section 2.Compiling C Code –q suppresses banners and progress information from all the tools.6. page 2-49. The –z option and its parameters follow all other compiler options and source files on the command line. or ’C44. interlists optimizer comments with assembly language output. which interlists C source statements into the compiler’s assembly language output. specifies the target processor. this option invokes the interlist utility.1 on page 2-65. C Compiler Description 2-13 .6. page 2-49. invokes the interlist utility. suppresses all output except error messages. All arguments that follow –z on the command line are passed to.3 on page 2-35. see Section 2. For more information. which interlists C source statements into the compiler’s assembly language output. Choices are: –qq –s –ss –uname –vxx - –v30 for a TMS320C30 processor –v31 for a TMS320C31 processor –v32 for a TMS320C32 processor –v40 for a TMS320C40 processor –v44 for a TMS320C44 processor By default. refer to subsection 2. –z enables the linking option. All code used in the eventual executable module. ’C32. undefines the predefined constant name. For more information. You must specify the appropriate option to generate code for the ‘C31. Overrides any –d options for the specified constant. For more information. ’C40. It causes the shell to run the linker on specified object files. refer to Section 2. the linker. if the comments are available. Only source filenames and error messages are output. the tools produce code for the ’C30 processor. must be compiled under the same version. otherwise. including all library-resident code. For more information. rrr for assembly language files for object files assembles the file fit. The “.” in the extension and the space between the option and the extension are optional.] new extension –eo[. The syntax for the –e option is: –ea[.rrr and creates an object file named fit.odsp.Compiling C Code File Specifiers –e allows you to change the default naming conventions for file extensions for assembly language files and object files. The example above could be written as: cl30 –earrr –eoodsp fit. 2-14 .rrr The –e option should precede any filenames on the command line. If you don’t use the –e option. This affects the interpretation of source filenames as well as the naming of files that the shell creates.obj for object files.odsp fit.rrr –eo .] new extension For example: cl30 –ea . the default extensions are .asm for assembly files and . If the –fs option is not specified.. You can insert an optional space between the –f option and the filename. insert the directory’s pathname on the command line after the –ft option: cl30 –ft d:\temp .. To specify an object file directory. if you have a C source file called file. or object files.1. assembly files.. The –f options are: –fafile –fcfile –fofile for assembly source file for C source file for object file For example.asm. the shell will place object files in the current directory. To specify a temporary directory.s –fa asmbly Note that –f cannot be applied to a wildcard specification. To specify an assembly file directory.5 ). If your naming conventions do not conform to those of the shell.Compiling C Code –f overrides default interpretations for source file extensions.s and an assembly file called asmbly. insert the directory’s pathname on the command line after the –fr option: cl30 –fr d:\object . If the –fr option is not specified.. C Compiler Description 2-15 .. The –ft option overrides the TMP environment variable (described in subsection 2. –fs permits you to specify a directory for assembly files. the shell will place assembly files in the current directory. insert the directory’s pathname on the command line after the –fs option: cl500 –fs d:\assembly . you can use –f options to specify which files are C source files.. –fr permits you to specify a directory for object files. use –f to force the correct interpretation: cl30 –fcfile. –ft permits you to specify a directory for temporary intermediate files. produces a function prototype listing file.2.3 on page 2-34. Normally. It does not contain any comments. This facilitates compatibility between existing K&R-compatible programs and the TMS320C3x ANSI compiler. and that are newly imposed by the ANSI C standard. For more information about errors and about –pe. refer to subsection 2. The parser creates a file containing the prototype of every procedure in all corresponding C files. allowing complete compilation.Compiling C Code Parser Options –pe treats code-E errors as warnings. generates a preprocessed listing file. or generating a listing of procedures defined. For more information. –pf is useful when conforming code to the ANSI C standard. The compiler writes a modified version of the source file to an output file called file. When you use the –pe option.10 on page 3-22.pp. The effects of the –pk options are described in Section 3. with a . relaxes certain requirements that are stricter than those required by earlier K&R compilers. the parser treats code-E errors as warnings.7 on page 2-51. the code generator does not run if the parser detects any code-E errors. Each function prototype file is named as its corresponding C file.pro extension. This file contains all the source from #include files and expanded macros. –pf –pk –pl 2-16 . refer to Section 2. creates a parser error message file. The error file has the base name of the input file and the . refer to subsection 2. sets the warning message level. the compiler removes the function. the name of the resulting object file or assembly file is the same as the name of the first input C file. –pr –pwn - –pw or –pw0 disables all warning messages. Section 2. If a function is not called. #include files. The module proceeds to the optimization and code generation passes of the compiler. For more information. When invoked with –po. Because the compiler can now see the entire C program.pp extension. directly or indirectly.7 on page 2-51 discusses the diagnostic information reported by the compiler. the compiler processes only macro expansions. The compiler writes the preprocessed file with a . it performs several optimizations that are not usually done during file-level optimization: - If a particular argument in a function always has the same value.3 on page 2-34. By default. –pw1 enables serious warning messages (default) –pw2 enables all warning messages C Compiler Description 2-17 .c. to be suppressed in a file generated with –po or –pl. The file contains all error messages generated by the parser. and conditional compilation. –pn suppresses line and file information. You may find –pn useful when compiling machine-generated source.2. the compiler deletes the return code in the function. If a return value of a function is never used.Compiling C Code –pm when used with the –o3 option. –pn causes #line directives of the form: #123 file. –po runs the compiler for preprocessing only. combines source files into one intermediate file called a module to perform programlevel optimization instead of file-level optimization. the compiler replaces the argument with the value and passes the value instead of the argument.err extension. 2. refer to the ANSI specification. It occurs whether or not the optimizer is invoked and whether or not any –x options are specified.c two. For example. the compiler does not recognize trigraphs.Compiling C Code –px filename when using the –pm option. 2-18 . cl30 –pm one. By default. The last option may be specified as –x or –x2 interchangeably. subsection 2. The ANSI C standard defines these sequences for the purpose of compiling programs on systems with limited character sets.1. or K&R § A 12.c –px prog1 results in an object file named prog1. which causes all functions defined or declared as inline to be expanded in line Note that –x1 is the default inlining option. For more information. use –p? to enable trigraphs.c three. specifies the name of the final output file. –p? enables trigraph expansion.obj. The possibilities are: - –x0 disables all inlining –x1 inlines all intrinsic operators (default) –x2 or –x invokes the optimizer at level 2 and defines the _INLINE preprocessor symbol.1. See Section 2. Trigraphs are special escape sequences of the form: ??c where c is a character.1. Inlining Options –x n controls function inlining done by the optimizer when functions have been defined or declared as inline.5 on page 2-43 for more details. p = pc. this generates an error because the parameter types in the prototype disagree with the default argument conversions (which convert float to double and char to int). /* Illegal unless -tp used */ - Pointers to differently qualified types can be combined: char *p. such as: int func(float a. C Compiler Description 2-19 . pi = pu. With the –tf option. unsigned *pu. char b). –tp relaxes type checking on pointer combinations. const char *pc. In ANSI C. and then later declared with a prototype. if a function is declared with an oldformat declaration. because the passed pointer type would ordinarily disagree with the declared parameter type in the prototype. This option has two effects: - A pointer to a signed type can be combined in an operation with a pointer to the corresponding unsigned type: int *pi.Compiling C Code Type-Checking Options –tf relaxes type checking on redeclarations of prototyped functions. the compiler overlooks such redeclarations of parameter lists. /* Illegal unless -tp used */ –tp is especially useful when you pass pointers to prototyped functions. such as: int func( ). and constants. If the ANSI standard behavior is not important to your application. refer to Section 2. effectively rounding towards zero. the –mc option suppresses the correction sequence for faster execution.Compiling C Code Runtime-Model Options –ma assumes that variables are aliased. The ANSI C standard specifies that when an object of floating-point type is converted to an integer type. including all library resident code. which rounds toward negative infinity. In the small memory model. All code used in the eventual executable module. The compiler uses the TMS320C3x/C4x FIX instruction for these conversions. must be compiled under the same model. selects the big memory model. the fractional part is discarded. The compiler assumes that pointers may alias (point to) named variables and therefore aborts certain optimizations when an assignment is made through a pointer. static data. uses faster float-to-int conversion. For more information. –mb –mc 2-20 . allowing unlimited space for global data. followed by a fourinstruction sequence to correct negative values. this space is limited to 64K words. which is the default.3 on page 2-35. DIV_I30. –ml runtime support assembly calls use far calls.bss */ struct sss ext_ptr = &ext_obj /* object pointer */ The optimizer may convert an expression such as structure member ext_ptr–>f1 to ext_obj. generating MPYI instructions for integer multiplies rather than runtime support calls.5. This allows loops to be interrupted. See Section 3. refer to Section 4. etc. /* object not in .2 on page 4-25. For more information. The compiler allows objects not declared in the .f1 because the optimizer assumes that all variables are in the .Rx. CALLU Rx rather than the traditional 16-bit displacement form of CALL MPY_I30. –mi disables the use of RPTS instructions for loops and uses RPTB instead.bss section to be accessed indirectly via pointers. as described in subsection 4. With this option. This transformation is invalid if ext_obj is not in the .8 on page 3-20 for more information on far calls.bss being accessed incorrectly.bss section. In some cases the optimizer may convert such indirect accesses into direct accesses. –mm (TMS320C3x only) enables short multiplies. The –mf option inhibits the transformation and preserves the indirection.7 on page 4-32. will use 32-bit far calls of the form: LDI &MPY_I30. For example: extern struct sss ext_obj. C Compiler Description 2-21 . possibly resulting in objects in the . Such objects cannot be accessed directly because they are not on the data page addressed by the DP. If your application does not need 32-bit integer multiplication. use –mm to enable the MPYI instruction. it is significantly faster because it performs 24x24 bit multiplication using a single instruction rather than a call to a 32-bit library function. calls to runtime support assembly arithmetic functions such as MPY_I30.bss section.Compiling C Code –mf forces the compiler to always honor indirection on external objects. the code generator may inline many commonly used functions. uses the register-argument model. See Section 3.9 on page 3-21 for further information on how the compiler handles branch delay slots. Calling functions compiled with the TMS320C3x/C4x compiler from within Tartan–compiled code will exact a penalty of two cycles per call. such as MPY_I30. but still allows some compatibility with existing Tartan assembly code and libraries. to save the overhead of a function call. Code compiled under this model is completely incompatible with code compiled under the default model. Refer to Section 3. This option may be removed in a future release. If you use the –g option to generate symbolic debugging information. For more information. including all library resident code.9 on page 3-21. refer to Section 2. allowing it to be used with the Tartan LAJ function calling method. performs speed optimizations at the cost of increased code size. This is most often seen in copying (rather than moving) instructions into branch delay slots from the destination block. assumes all memory is accessible when optimizing. must be compiled under the same model.3 on page 2-35. When this option is specified. so the legacy Tartan code should be recompiled. many code generator optimizations are disabled because they disrupt the debugger. –mp –mr –ms –mt –mtc 2-22 . causes the compiler to generate code that supports the Tartan Ada function calling conventions. The –ms option causes the code generator to assume that no access to memory will cause the bus to block. generates an additional header for every C function compiled. All code used in the eventual executable module.Compiling C Code –mn re-enables the optimizations disabled by –g. The –mp option causes the code generator to increase code size when doing so will increase performance. out –l rts30. see the TMS320C3x/C4x Assembly Language Tools User’s Guide. predefines the constant name for the assembler.Compiling C Code Assembler Options –aa invokes the assembler with the –a option. –c. An absolute listing shows the absolute addresses of object code. This is equivalent to inserting #define name def at the top of each source file.2. Label definitions are written to the COFF symbol table for use with symbolic debugging. on page 2-66). invokes the assembler with the –x option to produce a symbolic cross-reference in the listing file. and –l linker options to the linker. Linking C Code. undefines the predefined constant name. –o. Linker Options Linker options can be used with the compiler. which creates an absolute listing. For example: cl30 –q symtab. on page 2-12. the file symtab. (See Section 2. invokes the assembler with the –l (lowercase L) option to produce an assembly listing file. –adname sets name equal to 1. The –z option causes the shell to invoke the linker and pass the –a. or with the linker as a standalone.lib In this example. all linker options should follow the –z option described in General Options. C Compiler Description 2-23 . the –z option followed by the linker options must be the last shell option specified on the command line. For this reason.c will be compiled with the –q (quiet) option. All options on the command line following the –z option will be passed to the linker and not the compiler. –adname[=def] –al –as –auname –ax For more information about assembler options. retains labels.10. When used with the compiler shell. All compiler command line options following –z are passed to the linker.c –z –a –c –o symtab. Overrides any –ad options for the specified constant. If the optional def is omitted. makes all global symbols static. disables merging of symbolic debugging information. produces a relocatable. when needed. For more information on the linker. Options Summary Table. enables linking conventions defined by the RAM autoinitialization model of the TMS320C23x/4x C compiler. page 2-12. the linker acts as if –a is specified. This is the default initialization method. creates the C32 8-bit memory heap and sets heap size to size words and defines a global symbol that specifies the heap size. defines a global_symbol that specifies the primary entry point for the output module.Compiling C Code The –c and –n options suppress the linker option and cause the shell not to run the linker even if –z has been specified (see General Shell Options. if neither –a nor –r is specified. fill_value is a 16-bit constant.) Linker options are summarized in Table 2–1. executable object module. For more information about linker options. refer to Section 2. enables linking conventions defined by the ROM autoinitialization model of the TMS320C3x/4x C compiler. Default = 1K words. This is the default. creates the C32 16-bit memory heap and sets heap size to size words and defines a global symbol that specifies the heap size. sets heap size (for the dynamic memory allocation in C) to size words and defines a global symbol that specifies the heap size. page 2-65. instructs the linker to maintain the specified symbol as global. executable module. when needed. regardless of the use of the –h option. for more information. –ar –b –c – cr – e global_symbol –f fill_value –g global_symbol –h – heap size – heap8 size – heap16 size 2-24 . sets the default fill value for holes within output sections. beginning on page 2-6.10. Default = 1K words. see Chapter 8 of The TMS320C3x/C4x Assembly Language Tools User’s Guide. Default = 1K words. –a produces an absolute. and must follow operating system conventions. and must follow operating system conventions. and places the listing in filename. and resolves back references. generates a warning when an output section that is not specified with the SECTIONS directive is created. Default = 1K words. The default filename is a. This option must appear before the – l option. produces a map or listing of the input and output sections. names an archive library file as linker input. – l filename – m filename –n – o filename –q –r –s –stack size – u symbol –vn –w –x C Compiler Description 2-25 . filename is an archive library name.Compiling C Code – i dir alters the library-search algorithm to look in dir before looking in the default location. suppresses banner and progress information.out. names the executable output module. sets the C system stack size to size words and defines a global symbol that specifies the stack size. instructs the linker to ignore all fill specifications in memory directives. places the unresolved external symbol symbol into the output module’s symbol table. strips symbol table information and line number entries from the output module. The directory must follow operating system conventions. The filename must follow operating system conventions. generates version n COFF format. including holes. forces rereading of libraries. retains relocation entries in the output module. 2-26 . the optimizer will use known properties of the standard library functions. etc.4 on page 2-38 and Appendix A. Note that this option controls only the inlining of functions that have not been explicitly defined or declared as inline. use –ol1 to compile the standard library. Setting the size to 0 (–oi0) disables automatic inlining completely. (lowercase L) controls file–level optimizations. For example. If the file you are compiling redefines any of the standard functions. For more information about the optimizer. –o1. You specify the size limit for the largest function that will be inlined (times the number of times it is called). There are three levels of optimizations: –o0. –ol1: Use this option if the file you are compiling contains unaltered definitions for standard library functions. the optimizer defaults to level 2. Use the –oln options to notify the optimizer if any of the following situations exist: –oln - - –ol0: Use this option if the file you are compiling alters a standard library function. refer to Section 2. –oisize controls automatic inlining of functions (not defined or declared as inline) at optimization level 3. Following the –ol2 option. When you invoke the optimizer at level 3 (–o3). If you do not indicate a level (0. n denotes the level of optimization. 3) after the –o option.Compiling C Code Optimizer Options –on causes the compiler to optimize the intermediate file that is produced by the parser. –o2. 1. an environment variable. and –o3. the compiler may produce incorrect code. The –x options control the inlining of functions declared as inline. –ol2: Use this option to restore the default behavior of the optimizer after you have used one of the other two options in a command file. if you have defined a function with the same name as a standard library function or you have altered the source code of a standard library function. the optimizer will inline only very small functions. it makes use of known properties of the standard library functions. For example. If no size is specified. 2. use –ol0 to inform the optimizer not to assume the known properties of the standard library function. - – op0 signals the optimizer that functions in this module may be called by other modules. For more information. –on2 produce a verbose optimization information file. Restores the default behavior of the optimizer if you have used one of the other two options in a command file. etc. This disables some of the – o3 optimizations. or modify this file’s EXTERN variables. page 2-49. –os interlists optimizer comments into the compiler’s assembly language output. Level 3 optimization combines this information with its own file-level analysis to decide whether to treat this file’s EXTERN function and variable definitions as if they had been declared STATIC. –ou C Compiler Description 2-27 . but no variables declared within the module may be altered by other modules. –on1 produce an optimization information file.6. – op1 signals the optimizer that no functions in this module will be called by other modules and no interrupt functions declared elsewhere will call functions defined in this module. and variables declared within the module may be altered by other modules. an environment variable. To use this option. This is the default when – o3 is used. There are three levels available: – opn –on0 do not produce an information file. The following levels are defined. – op3 signals the optimizer that functions in this module may be called by other modules. specifies whether functions in other files can call this file’s EXTERN functions.nfo extension. you must be certain that these loops will iterate fewer than 231 times. This option works only when the –o3 option is used. – op2 or –op signals the optimizer that no functions in this module are called by other modules and no variable declared in this module will be altered by another module. This disables some of the – o3 optimizations. see Section 2. allows the compiler to use zero-overhead loop instructions. RPTS and RPTB to control unsigned loop counters.Compiling C Code –onn causes the compiler to produce a user readable optimization information file with a . if you want to always run quietly. Later. After the shell reads the entire command line and the input filenames. Using the –z option enables linking. on PCs. you can name a specific directory for temporary files. enable symbolic debugging.bat file. These examples assume C_OPTION is set as shown previously: cl30 cl30 cl30 cl30 *. if you do this. However. .c –z c. For example.4 Using the C_OPTION Environment Variable An environment variable is a system symbol that you define and assign to a string. these default options and/or input filenames are used every time you run the shell.1. You may find it useful to set the shell default options using the C_OPTION environment variable. It also allows source files to be compiled from a remote directory without writing any files into the directory where the source resides.c –c *.1. This feature allows use of a RAM disk or other high-speed storage files.c –z c. for example. if you need to invoke the shell without linking.cmd –c *. Setting up default options with the C_OPTION environment variable is especially useful when you want to run the shell consecutive times with the same set of options and/or input files.c *.cmd . If you plan to link most of the time when using the shell.Compiling C Code 2. compiles and links only compiles compiles/links using command file only compiles (–c overrides –z) 2. the shell puts intermediate files in the current directory. Options specified with the environment variable are specified in the same way and have the same meaning as they do on the command line. the parser phase of the shell creates a temporary file used as input by the code generation phase. it reads the C_OPTION environment variable and processes it.5 Using the TMP Environment Variable The shell program creates intermediate files as it processes your program. you can specify the –z option with C_OPTION. . then set up the C_OPTION environment variable as follows: Host DOS or OS/2 UNIX Enter set C_OPTION= – qg –z setenv C_OPTION ”–qg –z” You may want to set C_OPTION in your system initialization file. you can use –c on the command line to override the –z specified with C_OPTION. For example. 2-28 . This is useful for protected directories. . By default. and link. in your autoexec. overrides the TMP environment variable. C Compiler Description 2-29 .Compiling C Code There are two ways to specify a temporary directory: 1) Use the TMP environment variable: set TMP=d:\temp This example is for a PC. 2) Use the –ft option on the command line: cl30 –ft d:\temp.. The –ft option.. if used. Use the appropriate command for your host.. which are built into the first pass of the compiler (parser). 2-30 .2 Controlling the Preprocessor The TMS320C3x/C4x C compiler includes standard C preprocessing functions. A general description of C preprocessing is in Section A12 of K&R. The preprocessor handles: - Macro definitions and expansions #include files Conditional compilation Various other preprocessor directives (specified in the source file as lines beginning with the # character) This section describes specific features of the TMS320C3x/C4x preprocessor.Controlling the Preprocessor 2. in the form mm dd yyyy expands to the compilation time. † Specified by the ANSI standard You can use macro names in the same manner as any other defined name.1 Predefined Names The compiler maintains and recognizes the predefined macro names listed in Table 2–2: Table 2–2. expands to 1 if the target processor is a TMS320C4x processor. undefined otherwise. otherwise it is undefined. otherwise it is undefined. otherwise it is undefined.Controlling the Preprocessor 2. undefined otherwise. expands to 1 if the –mb option is used.__TIME__. expands to 1 if target processor is defined to be TMS320C32. expands to 1 if target processor is defined to be TMS320C31. Predefined Macro Names Macro Name _ _LINE_ _ † _ _FILE_ _ † _ _DATE_ _ † _ _TIME_ _ † _ _STDC_ _ † _C3x _TMS320C3x _C30 _TMS320C30 _C31 _TMS320C31 _C32 _TMS320C32 _C4x _TMS320C4x _C40 _TMS320C40 _C44 _TMS320C44 _INLINE _REGPARM _BIGMODEL Description expands to the current line number expands to the current source filename expands to the compilation date. For example: printf (” %s %s” . expands to 1 under the –x or –x2 optimizer option. otherwise it is undefined. could translate to a line such as: printf (” %s %s”. ”Jan 14 1997”. otherwise it is undefined. expands to 1 if target processor is defined to be TMS320C30. otherwise it is undefined. C Compiler Description 2-31 . expands to 1 if the target processor is a TMS320C40 processor. otherwise it is undefined. ”13:58”17”). expands to 1 if the target processor is a TMS320C44 processor. in the form hh:mm:ss expands to 1 (identifies the compiler as ANSI standard) expands to 1 if the target processor is a TMS320C3x processor. __DATE__). undefined otherwise expands to 1 if the register argument runtime model is used.2. If you enclose the filename in angle brackets. (The current source file refers to the file that is being compiled when the compiler encounters the #include directive. The filename can be a complete pathname. the compiler does not search for the file in the current directory.c This has the same effect as including these lines at the beginning of each source file: #define NAME 1 #define REGS 6 2.2 #include File Search Paths The #include preprocessor directive tells the compiler to read source statements from another file. have partial path information. Include files are sometimes stored in directories.2. The syntax for this directive is: # include ”filename” or # include <filename> The filename names the #include file that the compiler reads statements from. Note that if you enclose the filename in angle brackets. 3) Any directories set with the environment variable C_DIR. - 2-32 . in the order given: 1) Any directories named with the –i option in the shell. You can augment the compiler’s directory search algorithm by using the –i shell option or the environment variable C_DIR to identify a directory name. or have no path information. 2) Any directories set with the environment variable C_DIR.) 2) Any directories named with the –i compiler option in the shell. The line number and the filename where the error occurred are printed along with a diagnostic message. the compiler searches for the file in the following directories. - If you enclose the filename in double quotes.Controlling the Preprocessor The preprocessor produces self-explanatory error messages. You can enclose the filename in double quotes or in angle brackets. the compiler searches for the file in the following directories. in the order given: 1) The directory that contains the current source file. You can predefine additional names from the command line by using the –d option: cl30 –dNAME –dREGS=6 *. assume that a file called source. as in the previous example. The pathnames specified with C_DIR are directories that contain #include files. To specify the same directory for #include files.c is in the current directory.c C_DIR Environment Variable The compiler uses the environment variable C_DIR to name alternate directories that contain #include files. Host DOS or OS/2 UNIX Pathname for alt. you can specify the path information with the –i option. For example.c This results in the compiler using the path in the environment variable to find the #include file.c cl30 –i/dsp/files source.h Invocation Command cl30 –ic:\dsp\files source.h> and invoke the compiler without the –i option: cl30 source.h> The table below lists the complete pathname for alt.Controlling the Preprocessor –i Shell Option The –i shell option names an alternate directory that contains #include files. This file contains one of the following directive statements: #include ”alt. you can use the #include directive without specifying any path information for the file.h /dsp/files/alt. You can separate pathnames with a semicolon or with blanks. set C_DIR with one of these commands: Host DOS or OS/2 UNIX Enter set C_DIR=c:\dsp\files setenv C_DIR /dsp/files Then you can include alt. In C source. The format for the –i option is: cl30 –i pathname ..h” or #include <alt.h” or #include <alt.c c:\dsp\files\alt. instead.h: #include ”alt. each –i option names one pathname..c and shows how to invoke the compiler. You can use up to 32 –i options per invocation. select the row for your host system. In C C Compiler Description 2-33 . –pn. If you use the –po option.Controlling the Preprocessor source. including #line directives and conditional compilation. (These functions correspond to translation phases 1–3 as specified in Section A12 of K&R. no #line directives are inserted. are executed.) The preprocessed output file contains no preprocessor directives other than #line. Comments are removed. The –po option can be useful when debugging macro definitions or when host memory limitations dictate separate preprocessing (refer to Parsing in Two Passes on page 2-59). and all macros are expanded. you can specify the path information with C_DIR. 2-34 . Trigraph sequences are expanded (if enabled with the –p? option). Macro definitions are processed. The environment variable remains set until you reboot the system or reset the variable by entering one of these commands: Host DOS or OS/2 UNIX Enter set unsetenv C_DIR= C_DIR 2. no syntax checking or code generation takes place. If you use the –pn option. instead.3 Generating a Preprocessed Listing File (–pl. All other preprocessing directives. The resulting preprocessed listing file is a valid C source file that can be rerun through the compiler. you can use the #include directive without specifying any path information. the compiler performs only the preprocessing functions listed above and then writes out the preprocessed listing file.2. #include files are copied into the file. The compiler’s preprocessing functions perform the following actions on the source file: - Each source line ending in backslash (\) is joined with the following line. –po Options) The –pl shell option allows you to generate a preprocessed version of your source file. the compiler inserts #line directives to synchronize line and file information in the output files with input position from the original source files. page 2-36. The linker will issue an error message if you try to link TMS320C4x code with TMS320C3x code. includes symbolic debugging information register-argument model register-argument model.lib rts30g.lib rts40g.lib rts40gr.lib rts40.Using Runtime Models 2.3 Using Runtime Models The compiler has three options that allow you to affect the runtime model. All linked modules must use the same runtime model in order to correctly interface with other C modules.lib Processor TMS320C3x TMS320C3x TMS320C3x TMS320C3x TMS320C4x TMS320C4x TMS320C4x TMS320C4x Model Option(s) Used small memory model. With these exceptions. you must choose a configuration and then make sure that all the modules you link use the same model. includes symbolic debugging information small memory model. includes symbolic debugging information register-argument model register-argument model. –v32) All code linked together in any program. assembly modules. includes symbolic debugging information C Compiler Description 2-35 . All are compiled for the small memory model convention: Runtime Library rts30. stack-based model stack-based model. –v44) small memory model (default) stack-based model (default) TMS320C3x model (–v30. The big and small memory models are further explained in subsection 2.3. that is. Runtime models are mutually exclusive.3. The following conventions are mutually exclusive and must be chosen before you begin to compile: Mutually Exclusive Runtime Model Options big memory model (–mb) register-argument model (–mr) TMS320C4x model (–v40. page 2-37. Eight runtime libraries are shipped with the compiler. compiler options including runtime model options do not affect compatibility with other modules. including assembly language and library modules. but it will not run correctly. Register-argument and stack-based models are explained in subsection 2.lib rts40r.2. must agree on these three options. –v31. Mixed model code may link without error.lib rts30gr. and library resident modules. stack-based model stack-based model.1.lib rts30r. If you have large arrays. To make sure that the . Thus rts40rb.Using Runtime Models Refer to Section 5. will force the . 2. By default. you must be sure the . For example. Neither the compiler nor the linker checks these restrictions against the model used. automatic data. See Chapter 6 for more information on using this utility. and a ‘b’ for the big model.1 The Big and Small Memory Models The small memory model (default) requires that all external variables.bss section conforms to these two rules. However. However. This allows the compiler to access any of these objects without modifying the data page pointer (DP) register.1 for further information. append a suffix that contains the target CPU number (30 or 40). you must build a compatible version of the runtime library with the library build utility (mk30). Use the small model whenever possible. you may wish to adopt a naming convention that makes it obvious which models were used. the mk30 utility will create a runtime-support library called rts.lib would be easily recognized as the runtime support library for the TMS320C4x.bss: load = block (0x10000) when used with the SECTIONS directive.lib would be for the TMS320C3x small model and stack-based or standard runtime model.bss does not violate the restrictions. and compiler-generated constants in the program (after linking) fit into a single 64K word long data page (65536 words). The statement: . global variables. If you want to use a model that is incompatible with these. allocate them dynamically from the heap (using malloc) rather than declaring them as global or static. static variables. You should check the link map after linking to verify that the . Note: Size Restrictions on Small Model are not Tested When you use the small model. an ‘r’ for the register-argument model. link the .bss section into a 64K data page if the size of the . this model also forces the compiler to reload the data page pointer before accessing any external variables or compiler generated constants. The big model (–mb option) removes the 64K restriction.lib. with the register-argument runtime model. This is less efficient since it forces an extra instruction and possibly one or more extra pipeline delay cycles each time the compiler accesses one of these objects. big model.bss section is less than 64K. 2-36 . if you use more than one library.3. and rts30.bss section is less than 64K words and does not cross any 64K page boundaries. or dynamically allocated data. Neither model restricts the size of code.bss section using the block attribute of the SECTIONS directive. lib. Note: All Functions Must Be Prototyped When using the register-argument model. all functions must be prototyped.lib. some or all of the arguments are passed in registers. rts40r. but you must access them indirectly.Using Runtime Models If you have variables declared in assembly language outside the . Technical details of both models are explained in Section 4. In the standard runtime model (default) the compiler passes all arguments to functions on the stack.lib (shipped with the compiler) are compatible with the register-argument model. 2.3. When you invoke the compiler with the –mr option. The –pw2 option will issue a warning for a function call that has no prototype in scope. the compiler probably will generate incorrect code for the call. The compiler must be able to “see” the types of function parameters when the function is called. and you may need to use the –mf option as well. The runtime-support libraries rts30r.5 on page 4-22 discusses interfacing C with assembly language. This results in less overhead for function calls in your program. and rts40gr.2 The Register-Argument and Standard Models You can choose from two different argument passing models.bss section.4 on page 4-15.lib. Section 4. you can still use the small model. C Compiler Description 2-37 . The –pf option will generate prototypes for all functions you define. If there is a function call with no prototype visible. rts30gr. The library build utility is described in Chapter 6. The –o option may be followed by a digit specifying the level of optimization. to invoke the compiler using full optimization with inline function expansion. The easiest way to invoke the optimizer is to use the cl30 shell program. –ma. To invoke the optimizer outside cl30.asm File The optimizer also recognizes cl30 options –s.3.if File .c) Parser Optimizer Code Generator .9 on page 2-56 for more information). refer to Section 2. and –pk. 2-38 .Using the C Compiler Optimizer 2. these options are discussed in subsection 2. specifying the –o option on the cl30 command line (you may also invoke the optimizer outside cl30.c Figure 2–2 illustrates the execution flow of the compiler with standalone optimization. –q.opt File .1. refer to subsection 2. the default is level 2. and allocating variables into registers. For example. Compiling a C Program with the Optimizer C Source File (.9. rearranging statements and expressions. enter: cl30 –o3 –x function.2. Figure 2–2.4 Using the C Compiler Optimizer The compiler package includes an optimization program that improves the execution speed and reduces the size of C programs by doing such things as simplifying loops. The optimizer runs as a separate pass between the parser and the code generator. If you do not specify a level digit. 1. 2. - Level 0 - J J J J J J J J J J J J J J J J J J J J performs control-flow-graph simplification allocates variables to registers performs loop rotation eliminates dead code simplifies expressions and statements expands calls to functions declared as inline Level 1 performs all level 0 features. plus: performs local copy/constant propagation removes local dead assignments eliminates local common subexpressions - Level 2 performs all level 1 features. plus: performs loop optimizations eliminates global common subexpressions eliminates global redundant assignments converts array references in loops to incremented pointer form performs loop unrolling - Level 3 performs all level 2 features. plus: removes all functions that are never called simplifies functions that have return values that are never used expands calls to small functions inline reorders function definitions so the attributes of called functions are known when the caller is optimized propagates arguments into function bodies when all call sites pass the same value in the same argument position identifies file-level variable characteristics C Compiler Description 2-39 . These levels control the type and degree of optimization.Using the C Compiler Optimizer 2.4.1 Optimization Levels There are four levels of optimization: 0. and 3. Therefore. 2. because the optimizer extensively rearranges your program. That is.4.5. For more information. if the –o option is not specified separately) and defines the _INLINE preprocessor symbol as equal to 1. refer to Appendix A.4 Debugging Optimized Code The best way to debug code that is also optimized is to debug it in an unoptimized form and then reverify its correctness after it has been optimized.3.Using the C Compiler Optimizer Note: Files That Redefine Standard Library Functions The optimizer uses known properties of the standard library functions to perform level 3 optimizations. it does so regardless of whether or not you invoke the optimizer. Inlining makes a program faster by eliminating the overhead caused by function calls. Function Inlining. If you have files that redefine standard library functions. see Section 2. For more information about the meaning and effect of specific optimizations. 2. which show the optimized C statements. The code generator performs several additional optimizations. 2.5. see subsection 2. The –x2 option automatically invokes the optimizer at the default level (level 2.) This list describes optimizations performed by the standalone optimization pass. Note that occasionally the optimizer interlist comments may be misleading because of copy propagation or assignment of multiple or equivalent variables to the same register. but inlining sometimes increases code size. code for the function will be inserted (inlined) into your function at each place it is called whenever the optimizer is invoked and the –x option is not equal to –x0.4. 2-40 . particularly TMS320C3x/C4x-specific optimizations.3 Using the Optimizer with the Interlist Option (–os option) Optimization makes normal source interlisting impractical.2 Definition Controlled Inline Expansion Option (–x Option) When the optimizer is invoked. The comments also include a list of the allocated register variables. page 2-43. These optimizations are always enabled and are not affected by the optimization level you choose. the –x optimizer option controls inline expansion of functions that have been declared as inline by inhibiting or allowing the expansion of their code in place of calls. which causes expansion of functions declared as inline and controlled by the _INLINE symbol (For more information about _INLINE. page 2-46).4. (See page 2-26. use the –ol (lowercase L) options to inform the optimizer. the optimizer writes reconstructed C statements (as assembly language comments). use the –mn option on cl30.Using the C Compiler Optimizer The debugger may be used with optimized code. The compiler won’t optimize out any references to volatile variables. when you write code for the optimizer. However. If you want to use symbolic debugging and still generate fully optimized code.5 Special Considerations When Using the Optimizer The optimizer is designed to improve your ANSI-conforming C programs while maintaining their correctness. uses registers freely. 2. The optimizer rearranges code segments. C Compiler Description 2-41 . the surrounding environment where the assembly code is inserted may differ significantly from its apparent context in the C source code. while (*ctrl !=0xFF). It is usually safe to use asm statements to manipulate hardware controls such as interrupt registers or I/O ports. Although the compiler will never optimize out an asm statement (except when it is totally unreachable). After compilation. but asm statements that attempt to interface with the C environment or access C variables may have unexpected results. asm Statements You must be extremely careful when using asm (inline assembly) statements in optimized code. you must use the volatile keyword to identify these accesses. many code generator optimizations are disabled because they disrupt the debugger.4. check the assembly output to make sure your asm statements are correct and maintain the integrity of the program. you should note the following special considerations to insure that your program performs as you intend. Note: Symbolic Debugging and Optimized Code If you use the –g option to generate symbolic debugging information. In the following example. the loop waits for a location to be read as 0xFF: unsigned int *ctrl. but the extensive rearrangement of code and the many-to-one allocation of variables to registers often makes it difficult to correlate source code with object code. –mn re-enables the optimizations disabled by –g. and may completely remove variables or expressions. If you have code that depends on memory accesses exactly as written in the C code. Volatile Keyword The optimizer analyzes data flow to avoid memory accesses whenever possible. To correct this. such as when two pointers point to the same object or when a pointer points to a named object. the called function cannot assign the local’s address to a global variable or return it. The compiler assumes that if the address of a local variable is passed to a function. The optimizer analyzes the code to determine where aliasing can and cannot occur. declare ctrl as: volatile unsigned int *ctrl Aliasing Aliasing occurs when a single object may be accessed in more than one way. In worst-case aliasing. then optimizes as much as possible while still preserving the correctness of the program. Aliasing can disrupt optimization because any indirect reference could potentially refer to any other object. For example. use the –ma option in cl30 to force the compiler to assume worst-case aliasing. In cases where this assumption is invalid.Using the C Compiler Optimizer In this example. *ctrl is a loop-invariant expression. 2-42 . any indirect reference may refer to such a variable. so the loop will be optimized down to a single memory read. the function might change the local by writing through the pointer but will not make its address available for use elsewhere after returning. expansion will occur despite the presence of local statics. Functions defined as inline are expanded when the optimizer is invoked and the –x option is not equal to –x0.5 Function Inlining When an inline function is called and the optimizer is invoked. Inline expansion is performed one of three ways.) Definition controlled inline expansion is performed when two conditions exist: J J the inline keyword is encountered in source code and the optimizer is invoked (at any level) Functions with local static variables or a variable number of arguments will not be inlined. This happens whether or not the optimizer is used and whether or not any compiler or optimizer options are used. This is advantageous in short functions for two reasons: - It saves the overhead of a function call. It will be called by other modules unless they contain a compatible static inline declaration.) You can control this type of function inlining two ways: inline return-type function-name (parameter declarations) {function} J Method 1. with the exception of functions declared as static inline. In addition. A global symbol for the function is created. you can specify that the function is inlined within that module. In functions defined as static inline. The intrinsic operators of the target system (such as abs) are inlined by the compiler by default. a limit is placed on the depth of inlining for recursive or non–leaf functions. Setting the –x option to –x2 will automatically invoke the optimizer at the default level (level 2). the optimizer is free to optimize the function in context with the surrounding code. the code for the function is inserted at the point of the call. but the function will be inlined only within the module where it is defined as inline. By defining a function as inline within a module (with the inline keyword). Inlining should be used for small functions or functions that are called only a few times (though the compiler does not enforce this. C Compiler Description 2-43 . Once inlined. (You can defeat this automatic inlining by invoking the compiler with the –x0 option.Function Inlining 2. For more information. Declaring a function as static inline in a header file specifies that the function is inlined in any module that includes the header. Functions declared in this way may be placed in header files and included by all source modules of the program. but no code is generated for the function declaration itself. By default. it is recommended that you use the _INLINE preprocessor symbol to control its declaration. Functions declared as inline are expanded whenever the optimizer is invoked at any level. You can defeat all automatic inlining of small functions not declared as inline by setting the size to 0 (–oi0). the call to the function will be unresolved. By declaring a function as static inline. are expanded whenever the optimizer is invoked and the _INLINE preprocessor symbol is equal to 1. the size of each function is reported in the optimizer information file (–on1 option). If your code size seems too large. and that inlining a function that is called a great number of times can expand code size exponentially. The _INLINE Preprocessor Symbol. When you define an inline function. The optimizer measures the size of a function in arbitrary units. If you want to be certain that a function is always inlined. use the inline keyword (discussed above and in the next subsection). - Automatic inline expansion (functions not declared as inline) is done when the optimizer is invoked at level 3. If you fail to control the expansion using _INLINE.5. Function inlining is optimal for functions that are called only a small number of times. You can change the size of functions that are automatically inlined with the –oisize option. see subsection 2. Functions declared as inline and controlled by the _INLINE preprocessor symbol. try compiling with the –x0 keyword and note the difference in code size.Function Inlining static inline return-type function-name (parameter declarations) J Method 2. The –oi option specifies that functions whose size (times number of calls) is less than size units are inlined regardless of how they were declared. However. page 2-46. 2-44 . Note: Function Inlining May Greatly Increase Code Size It should be noted that expanding functions inline expands code size. such as the runtime library functions. or for small functions that are called more often.3. you can specify that the function is inlined in the present module. the optimizer will inline very small functions. This names the function and specifies that the function is to be expanded inline. and subsequently compile without the optimizer. Intrinsic operators are listed on page 2-54. This is true whether or not the optimizer is invoked. the optimizer will be invoked at the level specified by –o rather than at the level specified by –x. If you do not use the – oi option.3. –x1 or –x2 option is used together with the –o option at any level. The _INLINE preprocessor symbol has been used to control the expansion of the runtime library modules. Setting the –x option to –x2 automatically invokes the optimizer and thus causes the automatic expansion of functions defined or declared as inline. Other functions may be set up to use _INLINE in the same way. The – oi option can be used three ways: - If you set the size parameter to zero (– oi0).5.2 Automatic Inline Expansion Option (–oisize Option) The optimizer will automatically inline all small functions (not defined or declared with the inline keyword) when invoked at level 3. see subsection 2. and whether or not a –x option is specified (except –x0). the compiler treats intrinsic functions as regular function calls. See Section 2.5. as well as causing the other optimizations defined at level 2. is the default value. The intrinsic operators are inlined wherever they are called. and invokes the optimizer at level 2. it will be expanded inline whenever the optimizer is called and the –x option is not equal to –x0. which is the default level for the optimizer.Function Inlining 2. thereby enabling definition controlled inline expansion. If the –x0 shell option is specified.8 on page 2-54 for further information on intrinsics.1 Controlling Inline Expansion (–x Option) A command line switch controls the types of inline expansion performed. the optimizer inlines very small functions. For more information. assigns it the value 1. If the –x. C Compiler Description 2-45 . The _INLINE Preprocessor Symbol. They will be expanded if _INLINE is equal to 1. A command line option controls the size of functions inlined when the optimizer is invoked at level 3. If a function has been defined or declared as inline. –x1 : –x2/–x: creates the preprocessor symbol _INLINE. Defeats the default expansions listed below. 2. but will be called if _INLINE is not equal to 1. all size controlled inlining is disabled.5. –x0 : no inline expansion. h header is included. If the function is called more than once. The optimizer measures the size of a function in arbitrary units. 2-46 .h header file to declare the function correctly. It is used by standard header files included with the compiler to control the declaration of standard C runtime functions. all references to memcpy will be inlined and the linker will not have to use the memcpy in the runtime-support library to resolve any references. It allows you to write code so that it will run whether or not inlining is used. and will inline the function only if the resulting product is less than the size parameter. If the rest of the modules are compiled with inlining enabled and the string. will report the size of each function in the same units that the – oi option uses. The optimizer information file (created with the – on1 or – on2 option). The _INLINE symbol is turned off in the memcpy source before the header file is included. 2.5. You will want to use the _INLINE preprocessor symbol in the same way so that your programs will run regardless of whether inlining mode is selected for any or all of the modules in your program. because it is unknown whether the rest of the module is compiled with inlining. the runtime-support library code will be used to resolve the references to memcpy and function calls will be generated. regardless of whether inlining is used. however. Example 2–1 on page 2-47 illustrates how the runtime support library uses the _INLINE symbol. the optimizer will inline all functions whose size is less than the size parameter. The _INLINE symbol is used in the string. the optimizer multiplies the size of the function by the number of calls. Otherwise.3 _INLINE Preprocessor Symbol _INLINE is a preprocessor symbol that is defined (and set to 1) if the parser (or shell utility) is invoked with the –x2 (or –x) option.Function Inlining - If you set the size parameter to a nonzero integer. Since this is not an inline function. How the Runtime Support Library Uses the _INLINE Symbol /****************************************************************************/ /* STRING. const void *from. return (to). size_t n) { register char *rto = (char *) to. rn++) *rto++ =rfrom++. register char *rfrom = (char *) from.C (rtsxx. } #endif /* _INLINE */ #undef _ _INLINE /****************************************************************************/ */ /* MEMCPY.h so that the non-inline version of memcpy’s prototype is generated.c) is for the library so that the callable version of memcpy exists when inlining is disabled. const void *_s2. for (rn = 0. register size_t rn. register size_t rn. the _INLINE symbol is undefined (#undef) before including string. register char *rfrom = (char *) from. rn < n.h> void *memcpy (void *to. /* Declare the inlined function */ #if _INLINE static inline void *memcpy (void *to. The first. size_t _n). return (to). const void *from. Note how this definition is enabled and the prototype declared as static inline only if _INLINE is true: that is.Function Inlining Example 2–1.lib) /****************************************************************************/ #undef _INLINE /* Turn off so code will be generated */ #include <string. for (rn = 0.H HEADER FILE */ /****************************************************************************/ typedef unsigned size_t #if _INLINE #define _ _INLINE static inline #else #define _ _INLINE #endif _ _INLINE /* Declaration when inlining */ /*No declaration when not inlining */ void *memcpy (void *_s1. } There are two definitions of the memcpy function. size_t n) { register char *rto = (char *) to. C Compiler Description 2-47 . rn < n. rn++) *rto++ =rfrom++. the module including this header is compiled with the –x option. in the header file is an inline definition. The second definition (in memcpy. 2-48 .h header is included. all references to memcpy in the runtime support library will be inlined and the linker will not have to use the memcpy in the runtime support library to resolve any references.Function Inlining If the application is compiled with the –x option and the string. You will want to use the _INLINE preprocessor symbol in the same way so that your programs will run regardless of whether inlining mode is selected for any or all of the modules in your program. Any modules that call memcpy that are not compiled with inlining enabled will generate calls that the linker resolves by getting the memcpy code out if the library. enter: cl30 –ss function 2.R0 ADDI R0. It reads both the assembly and C source files. The output assembly file.R1 STI R1. *+FP(1) . function.6.––––––––––––––––––––––––––––––––––––––––––––––––––––– . 10 | i += j. An Interlisted Assembly Language File ******************************************* * FUNCTION NAME : _main * ******************************************* _main: . 8 | int i. The interlist utility enables you to inspect the assembly code generated for each C statement. . and writes the C statements into the assembly file as comments surrounded by dashes. Example 2–2 shows a typical interlisted assembly file.*+FP(1). . Example 2–2. The –ss option automatically prevents the cl30 shell from deleting the interlisted assembly language file (as if you had used –k). merges them.R1 STI R1. The easiest way to invoke the interlist utility is to use the –ss shell option. such as .––––––––––––––––––––––––––––––––––––––––––––––––––––– ADDI 123.––––––––––––––––––––––––––––––––––––––––––––––––––––– .––––––––––––––––––––––––––––––––––––––––––––––––––––– . 11 | j = i + 123.asm.––––––––––––––––––––––––––––––––––––––––––––––––––––– PUSH FP LDI SP.––––––––––––––––––––––––––––––––––––––––––––––––––––– .SP .– – – –.Using the Interlist Utility 2.––––––––––––––––––––––––––––––––––––––––––––––––––––– .c. is assembled normally.*+FP(2) C Compiler Description 2-49 .FP ADDI 2.––––––––––––––––––––––––––––––––––––––––––––––––––––– LDI *+FP(2).6 Using the Interlist Utility The compiler package includes a utility that interlists your original C source statements into the assembly language output of the compiler. 6 | main() . . j.1 Using the Interlist Utility Without the Optimizer The interlist utility runs as a separate pass between the code generator and the assembler. To compile and run the interlist utility on a program called function. 4. the option will be ignored and the following warning will be issued: Optimizer comments requested. Therefore. otherwise. optimization and instruction scheduling will take place on a line by line basis.Using the Interlist Utility 2. Instead.2 Using the Interlist Utility With the Optimizer If the –os option is used with the optimizer (–o).***. and the optimized source comments. To invoke the interlist utility outside of the shell. ignoring option –os If the –ss option is used with the optimizer (–o). the optimizer writes reconstructed C statements. the optimizer inserts comments into the code indicating how the optimizer has rearranged and optimized the code. If both the –ss and –os options are used. Note that occasionally the optimizer interlist comments may be misleading because of copy propagation or assignment of multiple or equivalent variables to the same register. the file generated contains the assembly code. refer to subsection 2. when you use the –os option. If the –os option is specified and the optimizer (–o) is not. the original C source comments. the original C source code is added to the assembly file by the interlist utility. optimization not run. roughly corresponding to the instructions between interlist comments. the interlist utility does not run as a separate pass. The –s option will interlist optimizer comments into the assembly file if the comments are available. it will use the interlist utility to interlist C source into the assembly file.9. In this case. 2-50 . to maintain a correspondence between the interlist comments and the code. Optimization makes normal source interlisting impractical because the optimizer extensively rearranges your program. These comments appear in the assembly language file as comments starting with .6. The comments also include a list of the allocated register variables. This is an example of a code-E error: ”file. The compiler cannot recover and therefore does not generate output for code-F errors. They result from a condition that violates the syntactic or semantic rules of the language. line n: [ECODE] error message “file. a 3-digit number uniquely identifies the error. is the text of the message. the compiler can recover and generate an output file if you use the –pe option. E. They result from a condition that is technically undefined according to the rules of the language. Although these are normally fatal errors.c”.7.1 for more information.7 How the Compiler Handles Errors One of the compiler’s primary functions is to detect and report errors in the source program. is a 4-character error code. They result from a condition that violates the semantic rules of the language. line 71: [F090] structure member ’a’ undefined C Compiler Description 2-51 . and code may not generate what you intended. When the compiler encounters an error in your program.c” line n: [ECODE] identifies the filename. A single upper-case letter identifies the error class. it displays a message in the following format: ”file. identifies the line number where the error occurs.How the Compiler Handles Errors 2. Code-W Error Messages Code-W errors are warnings. line 42: [W063] illegal type for register variable ’x’ Code-E Error Messages Code-E errors are recoverable.c”. line 66: [E056] illegal storage class for function ’f’ Code-F Error Messages Code-F errors are fatal.c”. This is an example of a code-W error: ”file.c”. This is an example of a code-F error: ”file. Refer to subsection 2. F. these classes are identified by the letters W. error message Errors are divided into 4 classes according to severity. and I (upper-case i). How the Compiler Handles Errors Code-I Error Messages Code-I errors are implementation errors. They occur when one of the compiler’s internal limits is exceeded. These errors are usually caused by extreme behavior in the source code rather than by explicit errors. In most cases, code-I errors cause the compiler to abort immediately. Most code-I messages contain the maximum value for the limit that was exceeded. (Those limits that are absolute are also listed in Section 3.11 on page 3-24.) This is an example of a code-I error: ”file.c”, line 99: [I015] block nesting too deep (max=20) Other Error Messages The compiler also reports other errors, such as incorrect command line syntax or inability to find specified files.These errors are usually fatal and are identified by the symbol >> preceding the message. This is an example of such an error: >> Cannot open source file ’mystery.c’ 2.7.1 Treating Code-E Errors as Warnings (–pe Option) A fatal error is an error that prevents the compiler from generating an output file. Normally, code-E, -F, and -I errors are fatal, while -W errors are not fatal. The –pe shell option causes the compiler to effectively treat code-E errors as warnings, so that the compiler will generate code for the file despite the error. Using –pe allows you to bend the rules of the language, so be careful. As with any warning, the compiler may not generate what you expect. Note that there is no way to specify recovery from code-F or -I errors; these are always fatal and prevent generation of a compiled output file. 2.7.2 Suppressing Warning Messages (–pw Option) The –pw options inform the compiler to quietly ignore or to generate certain code-W messages (warnings). You can suppress all warning messages with the –pw0 (or –pw) option. This can be useful when you are aware of the condition causing a warning and consider it innocuous. The –pw1 option causes the compiler to report serious warning messages. This is the default. 2-52 How the Compiler Handles Errors The –pw2 option causes the compiler to report all warning messages, including messages that report undeclared functions at their point of call. 2.7.3 An Example of How You Can Use Error Options The following example demonstrates how the –pe and –pw options can be used to suppress errors and error messages. The examples use this 2-line code segment: int *pi; char *pc; pi = pc; - If you invoke the code with the shell (and –q), this is the result: [err] ”err.c”, line3: [E104] operands of ’=’ point to different types In this case, because code-E errors are fatal, the compiler does not generate code. - If you invoke the code with the shell and the –pe option, this is the result: [err] ”err.c”, line3: [E104] operands of ’=’ point to different types In this case, the same message is generated, but because –pe is used, the compiler ignores the error and generates an output file. - If you invoke the code with the shell and –pe and –pw, this is the result: [err] As in the previous case, –pe causes the compiler to overlook the error and generate code. Because the –pw option is used, the message is suppressed. C Compiler Description 2-53 Intrinsics 2.8 Intrinsics The compiler supports nine intrinsic functions: “built–in” functions whose bodies are supplied by the code generator. The supported intrinsics provide access to certain conversion and math instructions, as described in Table 2–3. Table 2–3. Supported Intrinsic Functions Function abs(i) labs(l) fabs(f) toieee(f) frieee(f) Description Integer absolute value of i via ABSI instruction Long integer absolute value of l via ABSI instruction Processor(s) all all Floating-point absolute value of f via ABSF all instruction Conversion of floating-point variable f to IEEE format via TOIEEE instruction Conversion of IEEE formatted variable f to floating-point format via FRIEEE instruction Conversion of floating-point variable f to integer via FIX instruction Conversion of floating-point variable f to integer using ANSI compatible conversion sequence 24-bit integer multiplication of i and j using MPYI instruction (similar to specifying the –mm shell option) 16-bit floating-point inverse of f using RCPF instruction C4x C4x fast_ftoi(f) ansi_ftoi(f) all all fast_imult(i,j) C3x fast_invf(f) C4x When working with intrinsics, it is important to be aware of the following: - If the –x0 shell option is specified (disabling inline expansion), the compiler treats intrinsic functions as regular function calls. This means that, at link time, the linker will look for a function with the appropriate name and issue an error message if it has not been defined. It is your responsibility to provide such a function. Note, however, that the runtime-support library includes callable functions for the abs, labs, and fabs intrinsics. 2-54 Intrinsics - You should include the intrin.h file in any file that uses the intrinsics functions. The fast_ftoi intrinsic is similar to the –mc shell option in that both cause the compiler to perform fast floating-point to integer conversions via the FIX instruction. However, the intrinsic gives you expression-byexpression control over this effect. The intrinsic performs the fast conversion whether or not the shell option is specified. The ansi_ftoi intrinsic causes the compiler to perform an ANSI-compatible floating-point to integer conversion via a standard sequence of instructions. The intrinsic gives you expression-by-expression control over this effect. Note that the ansi_ftoi intrinsic overrides the –mc shell option; the compiler will perform the ANSI-compatible conversion even if the –mc shell option is specified. The fast_imult intrinsic is similar to the –mm shell option in that both cause the compiler to use 24-bit multiplication via the MPYI instruction. However, the intrinsic gives you expression-by-expression control over this effect. The intrinsic performs the 24-bit multiplication whether or not the shell option is specified. If the fast_invf instrinsic is used, the compiler will use the 16-bit RCPF instruction rather than a 32-bit call to the INV_F40 function. - - - C Compiler Description 2-55 Invoking the Tools Individually 2.9 Invoking the Tools Individually The TMS320C3x/C4x C compiler offers you the versatility of invoking all of the tools at once, using the shell, or invoking each of the tools individually. To satisfy a variety of applications, you can invoke the compiler (parser, optional optimizer, and code generator), the assembler, and the linker as individual programs. This section also describes how to invoke the interlist utility outside the shell. Compiler The compiler is made up of three distinct programs: the parser, optimizer, and code generator. Figure 2–3. Compiler Overview C Source File Parser Optimizer Code Generator .if file .opt file .asm file The input for the parser is a C source file. The parser reads the source file, checking for syntax and semantic errors, and writes out an internal representation of the program called an intermediate file. Subsection 2.9.1, page 2-57, describes how to run the parser, and also describes how to run the parser in two passes: the first pass preprocesses the code, and the second pass parses the code. The optimizer is an optional pass that runs between the parser and the code generator. The input is the intermediate file (.if) produced by the parser. When you run the optimizer, you choose the level of optimization. The optimizer performs the optimizations on the intermediate file and produces a highly efficient version of the file in the same intermediate file format. Section 2.4, page 2-38, describes the optimizer. The input for the code generator is the intermediate file produced by the parser (.if) or the .opt file from the optimizer. The code generator produces an assembly language source file. Subsection 2.9.3, page 2-62, describes how to run the code generator. 2-56 Invoking the Tools Individually Assembler The input for the assembler is the assembly language file produced by the code generator. The assembler produces a COFF object file. The assembler is described fully in the TMS320C3x/C4x Assembly Language Tools User’s Guide. Interlist Utility The inputs for the interlist utility are the assembly file produced by the compiler and the C source file. The utility produces an expanded assembly source file containing statements from the C file as assembly language comments. Section 2.6 on page 2-49 describes the interlisting file and subsection 2.9.4 on page 2-64 describes the use of the interlist utility. Linker The input for the linker is the COFF object file produced by the assembler. The linker produces an executable object file. Section 2.10 describes how to run the linker. The linker is described fully in the TMS320C3x/C4x Assembly Language Tools User’s Guide. 2.9.1 Invoking the Parser The first step in compiling a TMS320C3x/C4x C program is to invoke the C parser. The parser reads the source file, performs preprocessing functions, checks the syntax, and produces an intermediate file that can be used as input for the code generator. To invoke the parser, enter: ac30 input file [output file] [options] ac30 is the command that invokes the parser. names the C source file that the parser uses as input. If you don’t supply an extension, the parser assumes that the file’s extension is .c. names the intermediate file that the parser creates. If you don’t supply a filename for the output file, the parser uses the input filename with an extension of .if. affect parser operation. Each option available for the standalone parser has a corresponding shell option that performs the same function. Table 2–4 shows the shell options, the parser options, and the corresponding functions. input file output file options C Compiler Description 2-57 Invoking the Tools Individually Table 2–4. Parser Options and Shell Options ac30 Option –@name –? –dname [=def] –e –f –i dir –k –lname (lowercase L) –mb –mr –n –o –p –q –r –tf –tp –uname –vxx –w0 (or –w) –w1 –w2 –x0 Shell Option –@name –p? –dname [=def] –pe –pf –i dir –pk –plname –mb –mr –pn –po –pm –q –pr –tf –tp –uname –vxx –pw0 (or –pw) –pw1 –pw2 –x0 –x1 –x –x or –x2 Function causes the parser to read options from the specified file enable trigraph expansion predefine macro name treat code-E errors as warnings prototype declared functions define #include search path allow K&R compatibility generate .pp file use big memory model use register-argument runtime model suppress #line directives preprocess only compile all input modules into a single output module suppress progress messages (quiet) write parser error messages to file relax prototype checking relax pointer combination undefine macro name select CPU version suppress all warning messages enable serious warning messages (default) enable all warning messages disable inline expansion expand abs. and labs inline (default) #define _INLINE 2-58 . fabs. You may be able to work around such host memory limitations by running the parser as two separate passes: the first pass preprocesses the file. This pass produces a preprocessed output file called file.2 Optimizing Parser Output The second step in compiling a TMS320C3x/C4x C program — optimizing — is optional. The optimizer reads the intermediate file. 2. 2) Rerun the whole compiler on the preprocessed file to finish compiling it. The first pass performs only preprocessing. optimizes it according to the level you choose. cl30 –po file. After parsing a C source file. When you run the parser as one pass. In the second pass. but it enables the code generator to produce more efficient code. therefore memory is needed only for macro definitions. –v. and produces an intermediate file. For more information about the preprocessor. The intermediate file has the same format as the original intermediate file.pp You can use any other options on this final pass. C Compiler Description 2-59 . specifying preprocessing only. The following example illustrates how to run the parser as two passes: 1) Run the parser with the –po option. or –i options.9. –u. you can choose to process the intermediate file with the optimizer. refer to Section 2. it uses host memory to store both macro definitions and symbol definitions simultaneously.pp. there are no macro definitions. use them on this first pass. –x. and the second pass parses the file. these functions can be separated. therefore memory is needed only for the symbol table.c If you want to use the –d. cl30 file. But when you run the parser as two passes.2. –mr.Invoking the Tools Individually Parsing in Two Passes Compiling very large source programs on small host systems such as PCs can cause the compiler to run out of memory and fail. The optimizer improves the execution speed and reduces the size of C programs. the optimizer uses the input filename with an extension of . The options that you use in standalone optimization are the same as those used for the shell. names the intermediate file produced by the parser. The optimizer assumes that the extension is . enter: opt30 [input file [output file ]] [options] opt30 is the command that invokes the optimizer. Detailed explanations of each optimizer option may be found on page 2-26.if.opt. some other compiler options may be used with the optimizer.Invoking the Tools Individually To invoke the optimizer.4 provides a detailed list of the optimizations performed at each level. Those formats are shown in Table 2–5. affect the way the optimizer processes the input file. Besides the optimizer options. input file output file options 2-60 . Section 2. If you don’t supply a filename for the output file. names the intermediate file that the optimizer creates. level 2 + file optimization specify that callable functions and/or modifiable variables are used in this module specify that no callable functions are used in this module (default) specify that no modifiable variables or callable functions are used in this module specify that no modifiable variables are used in this module. register optimization level 1. Optimizer Options and Shell Options opt30 Option –a –f –h0 –h1 –h2 –isize –k –m –n0 –n1 –n2 –o0 –o1 –o2 –o3 –p0 Shell Option –ma –mf –ol0 –ol1 –ol2 –oisize –pk –mm –on0 –on1 –on2 –o0 –o1 –o2 –o3 –op0 Function assume variables are aliased force indirect access to externals specify that this file alters a standard library function (–o3 only) specify that this file defines a standard library function (–o3 only) specify that this file does not define or alter library functions (–o3 only) set automatic inlining size (–o3 only) allow K&R compatibility enable short multiply (’C3x only) do not produce information file produce information file produce verbose information file level 0. level 1 + global optimization level 3. 31. level 0 + local optimization level 2.Invoking the Tools Individually Table 2–5. then to improve speed –p1 –p2 –p3 –op1 –op2 –op3 –q –r –s –u –vxx –z –q –mr –os or –s –ou –vxx C Compiler Description 2-61 . or 44 (default is –v30) optimize primarily to reduce size. 32. xx = 30. 40. but modifiable functions may be used suppress progress messages (quiet) use register-argument runtime model interlist optimizer comments allow zero-overhead loop operations specify processor. after assembling and linking. The following table shows the shell options.asm.9. the code generator options. You can modify this output file or use it as input for the assembler. the code generator assumes that the extension is . affect the way the code generator processes the input file. and the corresponding functions. names a temporary file that the code generator creates and uses. enter: cg30 [input file [output file [tempfile]]] [options] cg30 is the command that invokes the code generator. As Figure 2–3 on page 2-56 shows. the code generator uses the input filename with the extension of .if. If you don’t specify an input file. To invoke the code generator as a standalone program. Each option available for the standalone code generator mode has a corresponding shell option that performs the same function. names the assembly language source file that the code generator creates. input file output file tempfile options 2-62 . the code generator will prompt you for one.3 Invoking the Code Generator The third step in compiling a TMS320C3x/C4x C program is to invoke the C code generator. If you don’t supply a filename for the output file. which.tmp. can be stored in ROM. The code generator produces re-entrant relocatable code.Invoking the Tools Individually 2. names the intermediate file that the code generator uses as input. If you don’t supply an extension. The code generator deletes this file after using it. The default filename for the temporary file is the input filename appended to an extension of . the code generator converts the intermediate file produced by the parser into an assembly language source file for input to the TMS320 floating-point assembler. the code generator deletes the input (intermediate) file. C Compiler Description 2-63 . or 44 (default is –v30) retain the input file † –z tells the code generator to retain the input file (the intermediate file created by the parser).Invoking the Tools Individually Table 2–6. you might want to use the same intermediate file to create one file that contains symbolic debugging directives (–o option) and one that doesn’t. This option is useful for creating several output files with different options. xx = 30. Note that if you do not specify the –z option. 32. 31. Code Generator Options and Shell Options cg30 Option –gb –gc –gi –gl –gm –gn –gp –gr0 –gr1 (or –gr) –gs –gsrev# –gt –gtc –n –o –q –vxx –z –mt –mtc –o –s –g –q –vxx –mr –ms Shell Option –mb –mc –mi –ml –mm –mn –mp Function enable the big memory model fast floating–point to integer conversions disables RPTS instructions for loops (uses RPTB) use far calls for runtime support assembly calls enable short multiply (’C3x only) re-enable optimizations disabled by symbolic debugging perform speed optimizations at the cost of code size use standard (stack) runtime model use register-argument runtime model assume all memory is accessible when optimizing specify silicon revision (see –msrev in shell) generate Ada compatible frame structure generate Tartan C function names perform optimizations while generating interlist information enable symbolic debugging suppress progress messages (quiet) specify processor. 40. for example. to associate assembly code with C source. enter clist –r function This interlists and removes debugging directives from the file. you can run the interlist utility.cl. After you have compiled a program. produced by the code generator. To produce an interlist file. is the filename of assembly language output from the compiler. asmfile outfile options The interlist utility uses . the syntax is: clist asmfile [outfile] [–options] clist is the command that invokes the interlist utility. The following example shows how to compile and interlist function.cl.Invoking the Tools Individually 2.9. The output from this example is function. To compile. If you do not want the debugging directives in the output. suppresses banner and status information. To run the interlist utility from the command line. removes symbolic debugging directives. and allows normal optimization. use the –r interlist option to remove them from the interlisted file. the file has the same name as the assembly file with an extension . If you omit this.line directives. keeps the assembly language file.c. control the operation of the utility as follows: –b –r –q removes blanks and useless lines (lines containing comments or lines containing only { or }). when you compile the program. names the interlisted output file. you must use the –g shell option to specify symbolic debugging if you want to interlist it. 2-64 .4 Invoking the Interlist Utility The fourth step in compiling a TMS320C3x/C4x C program is optional. For this reason. enter: cl30 –gk –mn function This compiles and produces symbolic debugging directives. 1 Invoking the Linker The TMS320C3x/C4x C compiler and assembly language tools support modular programming by allowing you to compile and assemble individual modules and then link them together. which can customize your memory to your specifications. options filenames Linker options can be specified on the command line or in a command file. linker command files.out. specifying the initialization model. any other extension must be explicitly specified. and allocating the program into memory. assemble. This is useful when you have a single source module.Linking C Code 2. The linker can determine whether the input file is an object file or an ASCII file that contains linker commands. Command files : Object files [. you can compile. or archive libraries. page 2-6. 2. can appear anywhere on the command line or in a linker command file. If you enter the lnk30 command with no options.10. It also discusses special requirements of linking C code: including the runtime-support libraries.obj] : Output files [ ] : Options : C Compiler Description 2-65 . filenamen lnk30 is the command that invokes the linker. The default output filename is a. This section describes how to invoke the linker with each method.) can be object files.10 Linking C Code The TMS320C3x/C4x C compiler and assembly language tools provide two methods for linking your programs: - you can link object files using the linker alone. The general syntax for invoking the linker is: lnk30 [–options] filename1 . The default extension for all input files is .obj . and link in one step by using the shell. The command file allows you to use the MEMORY and SECTIONS directives.. (Options are discussed in Table 2–1.. the linker will prompt for them. it automatically passes –c to the linker. You can use the MEMORY and SECTIONS linker directives to customize the allocation process. described in Table 2–1 on page 2-6.out): lnk30 –c prog1 prog2 prog3 –l rts30.out –l rts.out The linker uses a default allocation algorithm to allocate your program into memory. you must use a runtime-support library. assembles. However. the shell does not run the linker. identifies the appropriate archive library containing C runtime-support and floating-point math functions. and links in one step. and prog3 (the output file is named prog. By default.when you are linking with the shell. the options follow the –z shell option.lib library is included with the C compiler. the shell compiles.Linking C Code This is the usual syntax for linking compiler-based C programs as a separate step: lnk30 –c filenames or lnk30 –cr filenames lnk30 –c/–cr –o name.out –o name.lib Whenever you specify a library as linker input. are object files created by compiling and assembling C programs.10. When using –z to enable linking.lib –l rts. (The –l option tells the linker that a file is an object library. For example. are options that tell the linker to use special conventions defined by the C environment. filenames –o name.lib –o prog. you can link a C program consisting of modules prog1. if you use the –z option. Note that when you use the shell to link. the linker includes and links only those library members that resolve undefined references. the linker creates an output file with the default name of a. prog2.2 Using the Shell to Invoke the Linker (–z Option) The options and parameters discussed in this section apply to both methods of linking. 2. The rts.out –l rts. remember that: 2-66 –z must follow all source files and compiler options on the command line (or be specified with C_OPTION) . If you don’t use the –o option. names the output file. however.lib is the command that invokes the linker. and you can also use other linker options.out. These directives are also described in Chapter 8 of the TMS320C3x/C4x Assembly Language Tools User’s Guide.) If you’re linking C code. The –n option causes the shell to stop the process after compilation. linker options. In this way.out.c extension. C Compiler Description 2-67 . The arguments can be other linker command files. the runtime support library.lib The shell will call the compiler using the –s and –q options to compile all of the files in the current directory that end with a . object files. The order in which the linker processes arguments can be important. to compile and link all the . The cl30 shell passes arguments to the linker in the following order: 1) Object file names from the command line 2) Arguments following –z on the command line 3) Arguments following –z from the C_OPTION environment variable –c and –n Shell Options You can override the –z option by using the –c or –n shell options. The –c linker option has a different function than. The linker will link together all of the object files produced during compilation.Linking C Code - –z divides the command line into compiler options (before –z) and linker options (following –z) –c and –n suppress –z. The –c option is especially helpful when you have specified –z in the C_OPTION environment variable and want to selectively disable linking with –c on the command line. enter: cl30 –sq *. and is independent of. If you want to use –cr (RAM model of initialization) rather than –c. you are not limited by command line size restrictions. and any additional files specified in c. or libraries.c –z c. so do not use them if you want to link For all arguments that follow –z on the command line. the shell generates a linker command file containing the arguments. By default. For example. especially for command files and libraries.cmd –o prog. The resulting linked file will be named prog. The shell passes the command file to the linker. you can pass –cr as a linker option instead. Because –z is specified. the shell automatically uses the –c linker option that tells the linker to use C linking conventions (ROM model of initialization).out –l rts30.cmd. the shell will generate a command file containing all of the arguments following the –z option and then invoke the linker with this command file.c files in a directory. the –c shell option. .lib –l rts30. the libraries should be specified as the last filename on the command line because the linker searches libraries for unresolved references in the order that files are specified on the command line. When a program begins running. the linker includes and links only those library member that resolve undefined references. it executes boot.3 for further information on the included runtime support libraries. or Eight versions of the standard C runtime-support libraries are included with the compiler. Whenever you specify a library as linker input.obj.lib –l flib30. Chapter 5 describes additional runtime-support functions that are included in rts. Refer to section 2.10.lib . These functions include ANSI C standard runtime support. the linker automatically extracts boot. 2-68 . simply use the –l option on the command line: lnk30 –c filenames lnk30 –cr filenames –l –l rts30. flib30.Linking C Code 2. Generally. boot.lib in the link. references from those object files to that library will not be resolved.3 Controlling the Linking Process Regardless of the method you choose for invoking the linker.obj and links it when you use –c or –cr and include rts. Runtime-Support Libraries All C programs must be linked with a runtime-support library. You can use the –x option to force the linker to reread all libraries until references are resolved.lib . To link a library.lib.obj first.... All C programs must be linked with an object module called boot. refer to Chapter 8 of the TMS320C3x/C4x Assembly Language Tools User’s Guide.obj contains code and data for initializing the runtime environment. special requirements apply when linking C programs. If any object files follow a library. This archive library contains standard C library functions (such as malloc and strcpy) as well as functions used by the compiler to manage the C environment. For more information about how to operate the linker. You must: - include the compiler’s runtime-support library specify the initialization model determine how you want to allocate your program into memory This section discusses how these factors are controlled and provides an example of the standard default linker command file. cinit output section is padded with a termination record so that the loader (RAM model) or the boot routine (ROM model) knows when to stop reading the initialization tables.cinit. _c_int00 is automatically referenced. For more information about the ROM model. J The linker sets the symbol cinit to –1.obj is automatically linked in from the runtime-support library used. so no initialization is performed at runtime. Note that when you use the shell to link programs. This indicates that the initialization tables are not in memory. These options tell the linker to use special conventions required by the C environment. When you use –c or –cr. for example. refer to page 4-38.Linking C Code Initialization (RAM and ROM Models) The C compiler produces tables of data for autoinitializing global variables. The –c and –cr Linker Options Whenever you link a C program. The .obj. The following list outlines the linking conventions used with –c or –cr: - The symbol _c_int00 is defined as the program entry point. ROM Model (–c linker option) Global variables are initialized at runtime. Use the –cr linker option to select the RAM model. this ensures that boot. For more information about the RAM model. The initialization tables can be used in either of two ways: - RAM Model (–cr linker option) Global variables are initialized at load time. The format of these tables is discussed on page 4-37. they tell the linker to select the ROM or RAM model of autoinitialization. you must use either the –c or the –cr option. These tables are in a named section called . In the RAM model (–cr option). it identifies the beginning of the C boot routine in boot. refer to page 4-37. the –c option is the default. C Compiler Description 2-69 . Use the –c linker option to select the ROM model. Table 2–7 summarizes the sections. In the ROM model (–c option).text .sysmem Type Uninitialized Initialized Initialized Uninitialized Initialized Uninitialized Contents global and static variables initialization values for explicitly initialized global and static variables global and static constant variables that are explicitly initialized and string literals software stack executable code and floating-point constant memory for malloc functions When you link your program.stack .stack and .1. the linker defines the symbol cinit as the starting address of the .cinit . The compiler creates two basic kinds of sections: initialized and uninitialized. initialized sections can be linked into ROM or RAM. in the TMS320C3x/C4x Assembly Language Tools User’s Guide.bss . The C boot routine uses this symbol as the starting point for autoinitialization. you must specify where to locate the sections in memory. The linker does not allocate space in memory for the .Linking C Code J The STYP_COPY flag (010h) is set in the . In general.cinit section into memory. refer to Chapter 9. can be allocated into memory in a variety of ways to conform to a variety of system configurations. Refer to subsection 4. Sections Created by the Compiler The compiler produces five relocatable blocks of code and data.1 on page 4-2 for a complete description of how the compiler uses these sections. Sizing the Stack and Heap The linker provides four options that allow you to specify the size of the .cinit section. uninitialized sections must be linked into RAM. called sections. Table 2–7. These blocks.const .cinit section. The linker provides MEMORY and SECTIONS directives for performing this process.sysmem sections.cinit section header. - Note that a loader is not included as part of the C compiler package. STYP_COPY is the special attribute that tells the loader to perform autoinitialization directly and not to load the . For more information about allocating sections into memory. Sections Created by the Compiler Name . 2-70 . stack section to xxxx words.file –m map.files –o output. To link your program using the TMS320C4x command file.sysm16 sections only if you use memory allocation functions (such as malloc().cmd. Figure 2–5 shows the contents of c40. Allocating the .sysm8 and . . The value of xxxx must be constant.file c30.sysm8 section to xxxx words (for C32 8-bit memory support). and includes the .sysmem.cmd and c40. –heapxxxx sets the size of the .const Section When you use the small memory (default) model.const section must fit within a single 64K word long data page and must not cross any 64K address boundaries.bss and . Note. or .Linking C Code –stackxxxx sets the size of the . –heap16xxxx sets the size of the . that the . The value xxxx must be constant. The linker always includes the stack section.cmd C Compiler Description 2-71 . however.bss and .sysm16 sections are not created unless the 8-bit or 16-bit memory support functions are linked. enter the following command: lnk30 object. The default size for all sections is 1K (1024) words.file c40.sysm8.cmd.bss and . –heap8xxxx sets the size of the .sysmem section to xxxx words. or malloc16()). The value of xxxx must be constant.files –o output.sysm16 section to xxxx words (for C32 16-bit memory support). The value xxxx must be constant. To link your program using a command file. the sum of the entire .const. Use the linker’s block qualifier to help guarantee the correct allocation of . malloc8().cmd that can be used to link C programs.file –m map. Sample Linker Command File The compiler package includes two sample linker command files called c30.cmd Figure 2–4 shows the contents of c30. enter the following command: lnk30 object. CMD – v4. be sure */ /* that the ENTIRE .cinit: .> –o <out file> –m <map file> c30. or use the system environment variable C_DIR to */ /* specify a search path for libraries. */ /****************************************************************************/ –c /* LINK USING C CONVENTIONS */ –stack 0x400 /* 1K STACK */ –heap 0x400 /* 1K HEAP */ –lrts30. */ /* To satisfy this.lib is */ /* located. Sample Linker Command File for TMS320C3x C Programs /****************************************************************************/ /* C30. block 0x10000 /* /* /* /* /* /* CODE INITIALIZATION TABLES CONSTANTS SYSTEM STACK DYNAMIC MEMORY (HEAP) VARIABLES */ */ */ */ */ */ 2-72 .Linking C Code Figure 2–4.bss section fits within a single page.sysmem: . */ /* */ /* (3) When using the small (default) memory model. */ /* */ /* Notes: (1) Be sure to use the right library! Use a library that */ /* matches the runtime model you are using. you may want to change */ /* the allocation scheme according to the size of your */ /* program and the memory layout of your target system. */ /* */ /* (2) You must specify the directory in which rts.lib /* GET RUN–TIME SUPPORT */ /* SPECIFY THE SYSTEM MEMORY MAP */ MEMORY { ROM: EXT0: XBUS: IOBUS: RAM0: RAM1: EXT1: } org org org org org org org = = = = = = = 0x0 0x1000 0x800000 0x804000 0x809800 0x809c00 0x80a000 len len len len len len len = = = = = = = 0x1000 0x7ff000 0x2000 0x2000 0x400 0x400 0x7f6000 /* /* /* /* /* /* /* INTERNAL 4K ROM EXTERNAL MEMORY EXPANSION BUS I/O BUS RAM BLOCK 0 RAM BLOCK 1 EXTERNAL MEMORY */ */ */ */ */ */ */ /* SPECIFY THE SECTIONS ALLOCATION INTO MEMORY */ SECTIONS { .cmd */ /* */ /* Description: This file is a sample command file that can be used */ /* for linking programs built with the TMS320C30 C */ /* Compiler.bss must be smaller than 64K words and */ /* must not cross any 64K boundaries..const: .bss: } > > > > > > EXT0 EXT0 EXT0 RAM0 RAM1 EXT1. . Either add a ”–i<directory>” line to this */ /* file.text: .stack: .60 COMMAND FILE FOR LINKING C30 C PROGRAMS */ /* */ /* Usage: lnk30 <obj files.. Use it a guideline. > –o <out file> –m <map file> c40. Use it a guideline. */ /* To satisfy this. Sample Linker Command File for TMS320C4x C Programs /****************************************************************************/ /* C40. */ /* */ /* Notes: (1) Be sure to use the right library! Use a library that */ /* matches the runtime model you are using. block 0x10000 /* /* /* /* /* /* CODE INITIALIZATION TABLES CONSTANTS SYSTEM STACK DYNAMIC MEMORY (HEAP) VARIABLES */ */ */ */ */ */ C Compiler Description 2-73 ..const: .lib is */ /* located.CMD – v4. . you may want to change */ /* the allocation scheme according to the size of your */ /* program and the memory layout of your target system.stack: .bss: } > > > > > > LOCAL LOCAL LOCAL RAM0 RAM1 LOCAL.bss must be smaller than 64K words and */ /* must not cross any 64K boundaries. */ /* */ /* (3) When using the small (default) memory model.Linking C Code Figure 2–5. Either add a ”–i<directory>” line to this */ /* file. or use the system environment variable C_DIR to */ /* specify a search path for libraries.60 COMMAND FILE FOR LINKING C40 C PROGRAMS */ /* */ /* Usage: lnk30 <obj files.. be sure */ /* that the ENTIRE .bss section fits within a single page.sysmem: .lib /* GET RUN–TIME SUPPORT */ /* SPECIFY THE SYSTEM MEMORY MAP */ MEMORY { ROM: RAM0: RAM1: LOCAL: GLOBAL: } org org org org org = = = = = 0x000000 0x2FF800 0x2FFC00 0x300000 0x8000000 len len len len len = = = = = 0x1000 0x400 0x400 0x7D00000 0x8000000 /* /* /* /* /* INTERNAL ROM RAM BLOCK 0 RAM BLOCK 1 LOCAL BUS GLOBAL BUS */ */ */ */ */ /* SPECIFY THE SECTIONS ALLOCATION INTO MEMORY */ SECTIONS { .cmd */ /* */ /* Description: This file is a sample command file that can be used */ /* for linking programs built with the TMS320C40 C */ /* Compiler. */ /* */ /* (2) You must specify the directory in which rts. */ /****************************************************************************/ –c /* LINK USING C CONVENTIONS */ –stack 0x400 /* 1K STACK */ –heap 0x400 /* 1K HEAP */ –lrts40.text: .cinit: . lib (or any of the runtime support libraries) specifies that the linker search for the library named. libraries. change –c to –cr. If the library is not in the current directory. If you use the big memory model. If you use the RAM initialization model.bss section. and section allocations. memory configurations. For more information about operating the linker. 2-74 .Linking C Code In these command files. and the –l (lowercase “L”) option with rts30. you can customize the command file to use C_DIR or the –i option to define a path where the rts. refer to the linker chapter in the TMS320C3x/C4x Assembly Language Tools User’s Guide. the –c option specifies that the linker use the ROM initialization model. You will most likely have to customize the command file to fit a particular application by adding or modifying options.lib can be found. you can remove the 64K-word blocking on the . 7 3. . 3-4 Keywords . 3-24 TMS320C3x/C4x C Language 3-1 . . . 3-18 Far Call Support . . . . . . . . . . . . . . . . . . . . This chapter describes how these and other features are implemented for the TMS320C3x/C4x C compiler. which was described in the first edition of The C Programming Language and based on the UNIX System V C language. . . . .1 3. . . . . . . . . . . . . . . . . . . . . . . . and the host environment. . . . . . . This standard was developed by a committee chartered by ANSI to standardize the C programming language. 3-11 The asm Statement . . . . . . . . . . The ANSI standard is described in the American National Standard for Information Systems–Programming Language C X3. 3-7 Register Variables . . . . . . . . These are the topics covered in this chapter: Topic 3. . . . . . . . . . . . . . . . . . . . 3-17 Initializing Static and Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ANSI C supersedes the de facto C standard. . . .6 3. . . . . 3-10 Pragma Directives . . . . . . . . . . . . . . . . . . . . . . . by Kernighan and Ritchie. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The ANSI standard identifies certain implementation-defined features that may differ from compiler to compiler. . . . . . .8 3. . . . . . . . . . . . . . . . .9 Page Characteristics of TMS320C3x/C4x C . . . . . . . . . . . . . . . . . . . . . .4 3. 3-20 Delay Slot Filling for Branches . . . . . . . . . . .5 3. . . is based on the ANSI standard and is used here as a reference. . . . . . . . . .159-1989. . . . . . The second edition of The C Programming Language. . .11 Compiler Limits . . . . . . . . . . . . ANSI C encompasses many of the language extensions provided by recent C compilers and formalizes many previously unspecified characteristics of the language. . . . . . . . . . . .Chapter 3 TMS320C3x/C4x C Language The TMS320C3x/C4x C compiler supports the C language based on the ANSI (American National Standards Institute) C standard. The TMS320C3x/C4x C compiler strictly conforms to the ANSI C standard. . . . . . . . . . . . . . the runtime environment. . . . . . . . . . 3-21 3. . . . . depending on the type of processor. . . . . . . . 3-22 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10 Compatibility with K&R C (–pk Option) . . . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . 3-2 Data Types . . . . . . . 3.5.4.2.Characteristics of TMS320C3x/C4x C 3.2) Character constants with multiple characters are encoded as the last character in the sequence.1) Hex or octal escape sequences in character or string constants may have values up to 32 bits. Case is significant.2. K&R A7. For example.2) 3-2 For information about the representation of data types.3. which is assigned to the result of the sizeof operator.1.4. Each description also includes a reference to the formal ANSI standard and to the The C Programming Language by Kernighan and Ritchie (K&R).4. (ANSI 3. runtime environment. uppercase and lowercase characters are distinct for identifiers.7) . Although the compiler recognizes the syntax of multibyte characters.1.1.8) The type ptrdiff_t.1. in all TMS320C3x/C4x tools. K&R A7. (ANSI 3. which is assigned to the result of pointer subtraction. This section describes how these features are implemented for the TMS320C3x/C4x C compiler. K&R A4. (ANSI 2.1 Characteristics of TMS320C3x/C4x C The ANSI standard identifies some features of the C language that are affected by characteristics of the target processor. or host environment. K&R A2. refer to Section 3. (ANSI 3. is equivalent to unsigned int.1.6.5. internal and external. (ANSI 3. ’abc’ == ’c’ (ANSI 3. The following list identifies all such cases and describes the behavior of the TMS320C3x/C4x C compiler in each case. K&R A2.3.3) The source (host) and execution (target) character sets are assumed to be ASCII. (ANSI 3. These characteristics apply to all identifiers.4.2.2. is equivalent to int.3. K&R A2.2) The type size_t. this set of features may differ among standard compilers. K&R A12.5. there are no additional multibyte characters.3. Identifiers and constants Data types The first 100 characters of all identifiers are significant. For reasons of efficiency or practicality. Pragma Directives.1) Structure members are not packed into words (with the exception of bit fields). like #error.7) TMS320C3x/C4x C Language 3-3 . (ANSI 3. K&R A8. integer. The recognized pragma is: #pragma DATA_SECTION ( symbol . K&R A6. K&R A7. However.3) Pointers and integers can be freely converted. which. A signed modulus operation takes the sign of the dividend (the first operand).8) Declarations - The register storage class is effective for all character.1. (ANSI 3.3.3) A bit field of type integer is signed.1. K&R A7. see Section 3. For details.1. beginning at the low-order bits. and do not cross word boundaries. short. K&R A6.5. ” section name”) The standard #error preprocessor directive forces the compiler to issue a diagnostic message and halt compilation.3. K&R A8. Bit fields are packed into words.5.2. The TMS320C3x/C4x compiler extends the #error directive with a #warn directive.5. the sign is preserved. (ANSI 3. the value may be truncated when written to memory. and pointer types. Each member is aligned on a 32-bit word boundary.1. –10 / 3 = = –3 –10 % 3 = = –1 (ANSI 3.6) A right shift of a signed value is an arithmetic shift. The syntax of #warn is identical to #error. (K&R A12. 10 / –3 = = –3.3.Characteristics of TMS320C3x/C4x C Conversions - Int-to-float conversions use the TMS320C3x/C4x FLOAT instruction which produces an exact representation. all others are ignored.2. K&R A8.2. (ANSI 3.4. the quotient is negative. (ANSI 3.6) Expressions - When two signed integers are divided and either is negative. that is.3) Preprocessor - The preprocessor recognizes one #pragma directive. For example. 10 % –3 = = 1. forces a diagnostic message but does not halt compilation. resulting in a loss of precision towards negative infinity.3.5.7.5. (ANSI 3. See the TMS320C4x User’s Guide for more information on these instructions.2 Data Types - All integer types (char. support is provided for conversion to and from IEEE single and double-precision format for the TMS320C4x processors through the assembly language functions TOIEEE and FRIEEE. The type char is a signed type. TMS320C3x/C4x C Data Types Type Size Representation Range Maximum 2147483647 4294967295 2147483647 4294967295 2147483647 4294967295 2147483647 4294967295 2147483647 3.87747175e–39 3. and their unsigned counterparts) are equivalent types and are represented as 32-bit binary values.877472e–39 40 bits TMS320C3x/C4x 5. signed char 32 bits ASCII unsigned char short unsigned char int. short. in expressions. Although floating–point types are not directly supported.4028235e38 3. and range of each scalar data type are listed in the table below. representation. Objects of type enum are represented as 32-bit values.4028235e38 Minimum 0 char.877472e–39 32 bits TMS320C3x/C4x 5.Data Types 3. the type enum is equivalent to int. Signed types are represented in 2s-complement notation. long. Table 3–1. Floating–point type long double is represented in the TMS320C3x/C4x 40-bit extended-precision format. signed int unsigned int long. signed long unsigned long enum float double long double pointers 32 bits ASCII 32 bits 2s complement 32 bits binary 32 bits 2s complement 32 bits binary 32 bits 2s complement 32 bits binary 32 bits 2s complement –2147483648 –2147483648 0 –2147483648 0 –2147483648 0 –2147483648 32 bits TMS320C3x/C4x 5. The size.4028236684e38 32 bits binary 0 0xFFFFFFFF 3-4 . int. equivalent to int. Floating-point types float and double are equivalent and are represented in the TMS320C3x/C4x 32-bit single-precision floating-point format. Note: A TMS320C3x/C4x Byte Is 32 Bits The ANSI definition specifies that the sizeof operator yields the number of bytes required to store an object.1 The Long Double Data Type The long double data type is handled differently than the other floating–point data types. This yields results that you may not expect. Since the TMS320C3x/C4x char is 32 bits (to make it separately addressable). for example. No register variable can hold a 40-bit value. TMS320C3x/C4x C Language 3-5 . sizeof (int) == 1 (not 4). like floats and doubles.h. the first word contains the upper 24 bits and the second word contains the lower 24 bits. 3. It will be stored to memory before the call and then reloaded when needed. Two instructions are required to load and/or store long doubles.Data Types Many of the range values are available as standard macros in the header file limits. Long doubles require two memory words for storage. a byte is also 32 bits. TMS320C3x/C4x bytes and words are equivalent (32 bits). In float/double to long double conversion. can be passed as parameters in registers. ANSI further stipulates that when the sizeof operator is applied to type char. the value will be rounded to the nearest single-precision floating-point value using the RND instruction. but in extended–precision 40-bit format. the lower 8 bits of the 40-bit register will be filled with zeros. which is supplied with the compiler. The sizeof(long double) operator returns 2. The features of long doubles are described below: - Long doubles are not represented in the single–precision 32-bit format used for floats and doubles. In long double to float/double conversion. - Long doubles can be stored in one floating-point register and.2. a long double cannot be held in a register variable across a call. therefore. the result is one. - The 40-bit runtime-support assembly functions are linked into their own section called . ’C3x multiplication uses the runtime-support assembly function MPY_LD. and negation use assembly instructions when the instructions are able to accept extended-precision floating-point values as input.Data Types - Addition. Division uses the runtime-support assembly function DIV_LD. 3-6 . ’C4x multiplication uses the MPYF instruction.float40. subtraction. Inversion and reciprocals use the runtime-support assembly function INV_LD. can be modified by some external control). The cregister keyword is not allowed on objects of any floating-point type or on any structure or union object. you must declare each register (with or without volatile) as follows: extern cregsiter volatile unsigned int register. If the name does not match. you can use the register name directly.3 Keywords 3. It can only be used on objects of type integer or pointer. When you use the cregister keyword on an object. The cregister keyword is not allowed on any declaration within the boundaries of a function. the compiler generates the code to reference the control register. See TMS320C3x/C4x CPU and Instruction Set Reference Guide for detailed information on the control registers. TMS320C3x/C4x C Language 3-7 . The cregister keyword does not imply that the object is volatile.1 The cregister Keyword The TMS320C3x/C4x compiler extends the C language by adding the cregister keyword to allow high level language access to control registers. the compiler compares the name of the ojbect to a list of standard control registers for the ’C3x/C4x (see Table 3–2).3. If the name matches. Valid Control Registers Register IE IF IOF ST Description CPU/DMS interrupt enable register CPU interrupt flag register I/O flags Status register The cregister keyword can only be used in file scope. Once you have declared the register.Keywords 3. then the object should be declared with the volatile keyword also. To use a control register in Table 3–2. Table 3–2. the compiler issues an error. If the control register being referenced is volatile (that is. . 3-8 . } wait */.. while (ST & mask == 0) .... return IOF. IOF. @_var far keyword The compiler cannot access the data item via the dp.. Define and Use Control Registers extern extern extern extern cregisger cregister cregisger cregister volatile volatile volatile volatile unsigned unsigned unsigned unsigned int int int int IE. *aro where cl1 in the ..3....... after. 3. far int foo (). They can appear before.... or in between the storage class specifiers and types. This can be required if the total amount of program data is larger than the offset allowed (32K) from the DP.. ST. unsigned myfunc (unsigned int mask) { .. For example: far static int x. For example: sti ro.. /* Do nothing. static far int foo () Near and far data objects Global and static data objects can be accessed in the following two ways: near keyword The compiler assumes that the data item can be accessed relative to the data page pointer. aro sti ro.. For example: ldiu @cl1.bss holds the address of the variable. Two storage class modifiers cannot be used together in a single declaration.. static int far x.Keywords Example 3–1.. ... the near and far keywords are treated as storage class modifiers.. static near int x.2 The near and far Keywords The ’C3x/C4x C compiler extends the C language with the near and far keywords to specify how global and static variables are accessed and how functions are called. IF. Syntactically.. where constant cl1 in the . call _func far keyword The compiler is told by the user that the call is not within 224 bytes of the caller. when options –ml. the object is indicated as a far variable. the compiler uses the PC-relative call instruction. . on page 3-13. –mb. . since the variable might not be on the same data page as the . DP points to the beginning of the . Here. Large-memory model code. which is B14). This ensures access to the variable. it is normally loaded using relative offset addressing from the data page pointer (DP.Keywords By default. is then generated. TMS320C3x/C4x C Language 3-9 . which means that every data object is handled as if it were declared near. the compiler generates small-memory model code. and the compiler uses the register addressing mode of the call instruction. the default assumptions change.bss section. If the options –ml. If an object is declared near.2. The DATA_SECTION pragma. –mf. ro callu ro . unless it is actually declared far. however. is then generated.5. and –mb are used. and –mf are used. If you use the DATA_SECTION pragma. unless it is actually declared far. The default changes. By default. which means that every data object is handled as if it were declared far. Near and far function calls Function calls can be invoked in one of two ways: near keyword The compiler assumes that the destination of the call is within 224 bytes of the caller. ldiu @cl1. which means that every function call is handled as if it were declared near. Large-memory model code. which means that every data object is handled as if it were declared far. and this cannot be overridden. the compiler generates small-memory model code.bss section.bss holds the address of the function. See section 3. Any object with a scalar type (integer. are reserved for floating-point register variables in a function. refer to Section 4. or pointer) can be declared as a register variable. If a parameter is not declared as a register. depending on whether or not you use the optimizer.Register Variables 3. you can suggest variables as candidates for allocation into registers. Two registers.3 on page 4-11. If the stack–based calling convention is used. are reserved for pointer or integer register variables.4 Register Variables The TMS320C3x/C4x C compiler treats register variables (variables declared with the register keyword) differently. Eight (nine for the TMS320C4x) registers are available for register variables in each function: - Registers R4 and R5 (and R8 for the ’C4x) are reserved for integer register variables in a function. floating-point. Four registers. R6 and R7. AR4–AR7. a parameter declared as a register is passed on the stack normally but then moved into a register upon function entry. Compiling With the Optimizer The compiler ignores any register declarations and treats all variables as register variables while optimizing. For more information about register variables. it will be allocated local space in the function and stored there as the function begins execution. This improves access to the parameter within the function. 3-10 . Compiling Without the Optimizer If you use the register keyword. The register storage class is meaningful for parameters as well as local variables. The register designator is ignored for objects of other types. the compiler issues a warning.Pragma Directives 3. The TMS320C3x/C4x C compiler supports the following pragmas: - CODE_SECTION DATA_SECTION FUNC_CANNOT_INLINE FUNC_EXT_CALLED FUNC_IS_PURE FUNC_IS_SYSTEM FUNC_NEVER_RETURNS FUNC_NO_GLOBAL_ASG FUNC_NO_IND_ASG INTERRUPT The arguments func and symbol must have file scope. You must specify the pragma outside the body of a function. that is. If you do not follow these rules. definition. and it must occur before any declaration.5 Pragma Directives Pragma directives tell the compiler’s preprocessor how to treat functions. you cannot define or declare them inside the body of a function. TMS320C3x/C4x C Language 3-11 . or reference to the func or symbol argument. 1 The CODE_SECTION Pragma The CODE_SECTION pragma allocates space for the symbol in a section named section name.Pragma Directives 3.sect assembler directive. you must use COFF2.bss section. Example 3–2. If you use a section name longer than eight characters.sect ”my_sect” . ”my_sect”) int fn(int x) { return c.5. Example 3–2 demonstrates the use of the CODE_SECTION pragma. } (b) Assembly source file .global _fn 3-12 . “section name” ). Using the CODE_SECTION Pragma (a) C source file #pragma CODE_SECTION(fn. The CODE_SECTION pragma is useful if you have code objects that you want to link into an area separate from the . The section will be declared by the compiler with the . The syntax of the pragma is: #pragma CODE_SECTION (symbol. 512 _bufferB . The DATA_SECTION pragma is useful if you have data objects that you want to link into an area separate from the . The syntax of the pragma is: #pragma DATA_SECTION (symbol.3 The FUNC_CANNOT_INLINE Pragma The FUNC_CANNOT_INLINE pragma instructs the compiler that the named function cannot be expanded inline. Example 3–3.5. such as using the inline keyword. (b) Assembly source file . Function Inlining. The pragma must appear before any declaration or reference to the function that you want to keep. For more information. If you use a section name longer than eight characters.512. char bufferB[512]. Any function named with this pragma overrides any inlining you designate in any other way. Using the DATA_SECTION Pragma (a) C source file #pragma DATA_SECTION(bufferB.5. on page 2-43. The argument func is the name of the C function that cannot be inlined.usect ”my_sect”.1 3. you must use COFF2.bss section.bss .5. Example 3–3 demonstrates the use of the DATA_SECTION pragma. TMS320C3x/C4x C Language 3-13 .global _bufferB: _bufferA _bufferA. “section name” ). The syntax of the pragma is: #pragma FUNC_CANNOT_INLINE (func). see Section 2.2 The DATA_SECTION Pragma The DATA_SECTION pragma allocates space for the symbol in a section named section name.global . ”my_sect”) char bufferA[512].Pragma Directives 3. The FUNC_EXT_CALLED pragma specifies to the optimizer to keep these C functions or any other functions that these C functions call. The pragma must appear before any declaration or reference to the function that you want to keep. This allows the optimizer to do the following: - Delete the call to the function if the function’s value is not needed Delete duplicate functions The pragma must appear before any declaration or reference to the function. When you use this type of optimization. 3.5. The argument func is the name of a C function. These functions act as entry points into C. The argument func is the name of the C function that you do not want removed.5 The FUNC_IS_PURE Pragma The FUNC_IS_PURE pragma specifies to the optimizer that the named function has no side effects. the compiler removes any function that is not called. directly or indirectly. by main. The syntax of the pragma is: #pragma FUNC_IS_PURE (func). 3-14 . The syntax of the pragma is: #pragma FUNC_EXT_CALLED (func). You might have C functions that are called by hand-coded assembly instead of main. the compiler uses program-level optimization.4 The FUNC_EXT_CALLED Pragma When you use the –pm option.Pragma Directives 3.5. The syntax of the pragma is: #pragma FUNC_NEVER_RETURNS (func).Pragma Directives 3.8 The FUNC_NO_GLOBAL_ASG Pragma The FUNC_NO_GLOBAL_ASG pragma specifies to the optimizer that the function makes no assignments to named global variables and contains no asm statements. The pragma must appear before any declaration or reference to the function that you want to keep. The argument func is the name of the C function that makes no assignments.6 The FUNC_IS_SYSTEM Pragma The FUNC_IS_SYSTEM pragma specifies to the optimizer that the named function has the behavior defined by the ANSI standard for a function with that name.5. The argument func is the name of the C function to treat as an ANSI standard function. TMS320C3x/C4x C Language 3-15 . The argument func is the name of the C function that does not return.7 The FUNC_NEVER_RETURNS Pragma The FUNC_NEVER_RETURNS pragma specifies to the optimizer that the function never returns to its caller. The syntax of the pragma is: #pragma FUNC_NO_GLOBAL_ASG (func). The pragma must appear before any declaration or reference to the function that you want to keep.5. The pragma must appear before any declaration or reference to the function that you want to keep.5. The syntax of the pragma is: #pragma FUNC_IS_SYSTEM (func). 3. 3. 10 The INTERRUPT Pragma The INTERRUPT pragma enables you to handle interrupts directly with C code.Pragma Directives 3. which is the name reserved for the system reset interrupt for C programs. The pragma must appear before any declaration or reference to the function that you want to keep. The argument func is the name of the C function that makes no assignments. Except for _c_int00. The syntax of the pragma is: #pragma FUNC_NO_IND_ASG (func). the name of the interrupt (the func argument) does not need to conform to a naming convention.5. The argument func is the name of a function.9 The FUNC_NO_IND_ASG Pragma The FUNC_NO_IND_ASG pragma specifies to the optimizer that the function makes no assignments through pointers and contains no asm statements. 3. The pragma syntax is: #pragma INTERRUPT (func).5. 3-16 . The asm Statement 3. Directives that change sections or otherwise affect the assembly environment can also be troublesome.string \”abc\””).6 The asm Statement The TMS320C3x/C4x C compiler allows you to imbed TMS320C3x/C4x assembly language instructions or directives directly into the assembly language output of the compiler.string directive that contains quotes: asm(”STR: . Like all assembly language statements. with one string-constant argument: asm(”assembler text ”). a blank. Be especially careful when you use the optimizer with asm statements. The asm command is provided so that you can access features of the hardware. possibly causing undesired results. by definition. you can insert a . For example. Although the optimizer cannot remove asm statements (except where such statements are totally unreachable). a tab. The inserted code must be a legal assembly language statement. The compiler does not check the inserted instructions. The assembler text must be enclosed in double quotes. it can significantly rearrange the code order near asm statements. Note: Avoid Disrupting the C Environment With asm Statements Be extremely careful not to disrupt the C environment with asm statements. All the usual character string escape codes retain their definitions. This is particularly useful for inserting directives at the very beginning of a compiled module. Inserting jumps and labels into C code can cause unpredictable results in variables manipulated in or around the inserted code. if there is an error. which. The compiler performs no checking on the string. refer to the TMS320C3x/C4x Assembly Language Tools User’s Guide. The compiler copies the argument string directly into your output file. even outside blocks. The asm statement is syntactically like a call to a function named asm. the line must begin with a label. These asm statements do not follow the syntactic restrictions of normal C statements: they can appear as either a statement or a declaration. or a comment (asterisk or semicolon). TMS320C3x/C4x C Language 3-17 . For more information. This capability is provided through an extension to the C language: the asm statement. C is unable to access. it will be detected by the assembler. const section are not the same.bss: {} = 0x00. .7 Initializing Static and Global Variables The ANSI C standard specifies that static and global variables without explicit initializations must be specifically initialized to zero before the program begins running. Values initialized with the const qualifier are not placed in the . With the small memory model. In the linker command file. Initializing Static and Global Variables With the const Type Qualifier Static and global variables with the type qualifier const are initialized differently than other types of static and global variables. This task is typically done when the program is loaded.. . therefore. If your loader does not preinitialize variables. it would be necessary to require that the .bss and the .cinit section. for the same reasons discussed in Section 3.. const static and global variables without explicit initializations may or may not not be preinitialized to zero. For example: const int zero. it is up to your application to fulfill this requirement. All constants contained in expressions or that initialize local variables (with or without the const qualifier) will either be placed in the CONST table or will be loaded with immediate addressing. use a fill value of 0 in the . the TMS320C3x/C4x C compiler itself does not preinitialize variables.bss section: SECTIONS { ..const section. you can use the linker to preinitialize the variables to 0 in the object file..Initializing Static and Global Variables 3. The CONST table contains the following: 3-18 . } Because the linker writes a complete load image of the zeroed . /* may not be initialized to zero */ All constants that initialize global variables (with or without the const qualifier) will be placed in the .const sections be on the same data page if the values were placed in the .bss section into the output COFF file.const section because the values must be accessed with direct addressing.7. Because the loading process depends heavily on the specific environment of the target application system. this method may have the unwanted effect of significantly increasing the size of the output file. The CONST table and the . const section contains the following: Tables for switch statements String constants that do not initialize global variables The CONST table when using big model TMS320C3x/C4x C Language 3-19 .Initializing Static and Global Variables - Integer constant expressions wider than 16 bits Floating-point constant expressions with exponents larger than 4 bits or mantissas larger than 11 bits Integer local variable initializers wider than 16 bits Floating-point local variable initializers with exponents larger than 4 bits or mantissas larger than 11 bits Addresses of global variables Addresses of string constants The . The library-build utility described in Section 6.) The shell’s –ml option (page 2-21) can be used to cause the compiler to generate far calls to these functions. The resulting assembly code will load the address of the function into a register and then call unconditionally to that register. at the cost of one additional instruction (the address load). The compiler is required to make calls to certain runtime–support assembly functions to accomplish various initialization and arithmetic tasks. To make far calls to other runtime-support functions.src file. for example. (These functions are listed in Table 4–3 on page 4-19. It is important to add the far keyword to the function prototypes in the appropriate include files to ensure far call generation in the source files. 3-20 . functions that call the runtime-support functions are separated from them by offsets of greater than 16 bits. add the far keyword to the desired functions. Using far calls in this way may be appropriate if.8 Far Call Support A function can be declared with the keyword far to signify to the compiler that calls to that function should be made using a 32-bit far call (an indirect call through a register) instead of a label. The far call allows address offsets of greater than 16 bits to be used when calling that function. and then recompile the library.Far Call Support 3. you must extract the source files from the rts.1 allows you to extract source files and recompile the library. the compiler will try to copy instructions rather than moving them. If you know that all memory will return an appropriate value when accessed. The compiler handles unconditional branches by first trying to fill the delay slots with instructions located before the branch.9 Delay Slot Filling for Branches The compiler includes support for filling the three delay slots generated by the TMS320C3x/C4x for branches. but will leave branches even with only one slot filled in an attempt to take advantage of cycle savings. the compiler will not condense delayed branches in this manner. The compiler will try to fill delay slots with: - conditional load instructions that include known. instructions that will be executed if the condition is true) - If the shell option –mp is used. The compiler makes this change in an attempt to conserve code size by deleting the NOPs that would normally be placed in the empty delay slots. It will then try to move up instructions from the destination block.Delay Slot Filling for Branches 3. or at least a majority.. “safe” source operands (such as local auto variables..e. Any instructions found in the delay slots will be placed before the branch instruction. and constants). instructions located immediately following the delay slots of the conditional block (i. instructions that will be executed if the condition is false) instructions located at the destination block (i. Conditional branches are handled a little differently.e. it will condense the delayed branch into a non-delayed branch instruction (unless the –mp option has been specified). which can lead to significant increases in speed. If the –mp option has been specified. Almost any type of instruction can be moved. parameters. you can use the –ms shell option to inform the compiler that these constraints are not necessary when filling delay slots. TMS320C3x/C4x C Language 3-21 . If the compiler cannot fill any. of the delay slots. except for those that modify the PC. initializations. /* illegal unless –pk used */ .Compatibility With K&R C (–pk Option) 3.10 Compatibility With K&R C (–pk Option) The ANSI C language is a superset of the de facto C standard defined in the first edition of The C Programming Language (K&R). a violation of this rule is a code-E (recoverable) error. /* error without –pk. char *q = p. To simplify the process of compiling existing C programs with the TMS320C3x/C4x ANSI C compiler. However. This affects options that perform differently when applied to signed or unsigned operands. the result type was an unsigned version of the wider type. there are subtle changes in the language that may affect existing code. –pk simply liberalizes the ANSI rules without revoking any of the features. this situation is only a warning. division (and mod). Under K&R. In this example. the result type is a signed version of the wider type. and right shift. warning with –pk */ Even without –pk. 3-22 External declarations with no type or storage class (identifier only) are illegal in ANSI but legal in K&R: a. unless –pk used */ - ANSI prohibits two pointers to different types from being combined in an operation. signed type. An alternative to using –pk to work around this situation is to use –pe. Most programs written for earlier non-ANSI C versions of the TMS320C3x/C4x C compiler and other non-ANSI compilers should correctly compile and run without modification. under ANSI. Namely../* SIGNED comparison. the –pk option relaxes requirements that are stricter for ANSI C than for previous C standards.. Appendix C in K&R (second edition) summarizes the differences between ANSI C and the previous C standard. assume that short is narrower than int: unsigned short u int i. Instead. called K&R C. the compiler has a K&R option (–pk) that modifies some of the semantic rules of the language for compatibility with older code. Such cases are still diagnosed when –pk is used. or preprocessor constructs. enumerations. comparisons. but with less severity: int *p. The specific effects of –pk are include: - The integral promotion rules have changed regarding promoting an unsigned type to a wider. In general. if (u<i) . The –pk option does not disable any new features of the language such as function prototypes. In most K&R compilers. which converts code-E errors to warnings. the result of these two declarations is a single definition for the object a. c. resulting in multiple definitions of the same object (and usually an error). static int a. For example: int a. but K&R allows. OK if not */ Under ANSI.Compatibility With K&R C (–pk Option) - ANSI interprets file scope definitions that have no initializers as tentative definitions: in a single module. int a. multiple definitions of this form are fused together into a single definition. }. struct s { short f : 2. /* illegal unless –pk used */ - K&R syntax allows assignments to structures returned from a function: f(). /* same as ’q’ if –pk used. /* illegal unless –pk used */ Unrecognized escape sequences in string and character constants are explicitly illegal under ANSI but ignored under K&R: char c = ’\q’. this sequence is illegal because a is defined twice. bit fields can be legally declared with any integer type. objects with external linkage to be redeclared as static: extern int a. Under K&R.x = 123 /* illegal unless –pk used */ K&R syntax allows a trailing comma in enumerator lists: enum { a. With –pk. For example. For most K&R compilers. error if not */ ANSI specifies that bit fields must be of type integer or unsigned. /* illegal if –pk used. b. each definition is treated as a separate definition. }. /* illegal unless –pk used */ K&R syntax allows trailing tokens on preprocessor directives: #endif NAME /* illegal unless –pk used */ TMS320C3x/C4x C Language 3-23 . - ANSI prohibits. Table 3–3 specifies the limits that are absolute. Many compiler tables have no absolute limits but rather are limited only by the amount of memory available on the host system. The optimizer compiles one function at a time. This results in a file compiled with no optimization. usually the message also specifies the maximum value for whatever limit has been exceeded. Most of these conditions occur during the first compilation pass (parsing). To correct the problem. When two values are listed. The only way to avoid exceeding a compiler limit is to simplify the program or parse and preprocess in separate steps. When such a condition occurs. Use the protected-mode compiler 3-24 . The code generator also has compilation limits but fewer than the parser.Compiler Limits 3. All the absolute limits equal or exceed those required by the ANSI C standard. so the compiler aborts immediately after printing the error message. exceeding any compiler limit prevents continued compilation. and the second is for other hosts.11 Compiler Limits Due to the variety of host systems supported by the TMS320C3x/C4x C compiler and the limitations of some of these systems. On smaller host systems such as PCs. the optimizer may run out of memory. In general. the optimizer terminates and the shell continues compiling the file with the code generator. If this occurs. so the most likely cause of this is a large or extremely complex function in your source module. the parser issues a code-I diagnostic message indicating the condition that caused the failure. the compiler may not be able to successfully compile source files that are excessively large or complex. the first is for PCs (DOS or OS/2). your options are: - don’t optimize the module in question identify the function that caused the problem and break it down into smaller functions extract the function from the module and place it in a separate module that can be compiled without optimization so that the remaining functions can be optimized. 2) Before concatenation. function. or prototypes Global symbols Block scope symbols visible at any point Number of unique string constants Number of unique floating-point constants Notes: 32 parms 12 derivations 32 levels ≈ 1500 per initialization ≈ 150 per block 32 levels 2000 10000 500 1000 400 1000 400 2000 PCs All others PCs All others PCs All others PCs All others 1) After splicing of \ lines. TMS320C3x/C4x C Language 3-25 .Compiler Limits Table 3–3. or pointer derivations on a type Aggregate initialization nesting Static initializers Local initializers Nesting of declarations in structs. or prototype dec. 3) Includes argument substitutions. unions.20 levels larations Function parameters Array. All other character strings are unrestricted. Absolute Compiler Limits Description Filename length Source line length Length of strings built from # or ## Macro definitions Macros predefined with –d Macro parameters Macro nesting #include search paths #include file nesting Conditional inclusion (#if) nesting Limits 256 characters 16K characters 512 characters (see note 1) (see note 2) Allocated from available system memory 32 32 32 levels 32 paths 32 levels 32 levels (see note 3) (see note 4) Nesting of struct. This limit also applies to any single macro definition or invocation. 4) Includes –i and C_DIR directories. union. . . . . . . . . . . . . . . . . . . 4-2 Object Representation . . . . . . . . . . . . . . . . . follow the guidelines in this chapter. . . . . 4-7 Register Conventions . . . . . Topics in this chapter include: Topic 4. . . . .8 Page Memory Model . . . . . . .1 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 4. . . . . . . To ensure successful execution of C programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 4. . . . . . . . . . . . . . . 4-32 System Initialization . . . . .5 4. . . . . . . . . . . . . . . . . . If you write assembly language functions that interface to C code. . . . . . . . . . . . . . . . . . 4-36 Runtime Environment 4-1 . .Chapter 4 Runtime Environment This section describes the TMS320C3x/C4x C runtime environment.4 4. . . . .7 4. . . . . . . . . . . 4-15 Interfacing C with Assembly Language . . . . . . . . . . . . . . 4-22 Interrupt Handling . . . . . . . . . 4-11 Function Structure and Calling Conventions . it is critical that all runtime code maintain this environment. . .2 4. 4-30 Runtime-Support Arithmetic Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Uninitialized sections reserve space in memory (usually RAM).stack. Each block of code or data could be allocated individually into memory. Each block of code or data that a C program generates will be placed in its own contiguous space in memory. you can use the linker to allocate global variables into fast internal RAM or to allocate executable code into internal ROM. or about any locations reserved for I/O or control purposes. . called sections.1. not the compiler.text section is an initialized section that contains all the executable code as well as floating-point constants.bss. The . The compiler assumes that a full 32-bit address space is available in target memory. Note: The Linker Defines the Memory Map The linker. The . these blocks. and . The compiler produces relocatable code that allows the linker to allocate code and data into the appropriate memory spaces. but this is not a general practice.const section is an initialized section that contains floating-point constants and switch tables.text. .sysmem.const.cinit section is an initialized section that contains tables with the values for initializing variables and constants. . For more information about sections. to conform to a variety of system configurations. There are two basic types of sections: - Initialized sections contain data or executable code. The compiler creates three uninitialized sections: . and . although physical memory locations can be accessed with C pointer types. defines the memory map and allocates code and data into target memory. For example. A program can use this space at runtime for creating and storing variables. The C compiler creates three initialized sections: . (An exception to this is memory-mapped I/O.cinit. The compiler assumes nothing about the types of memory available. please read the Introduction to Common Object File Format in the TMS320C3x/C4x Assembly Language Tools User’s Guide.1 Sections The compiler produces six relocatable blocks of code and data. can be allocated into memory in a variety of ways. J J J 4-2 The . about any locations not available for code or data (holes).) 4.1 Memory Model The C compiler treats memory as a single linear block that is partitioned into subblocks of code and data.Memory Model 4. bss. as needed. . used by the dynamic memory functions. The linker takes the individual sections from different models and combines sections with the same name to create output sections. Note.2 C System Stack The C compiler uses a software stack to: - Save function return addresses Allocate local variables Pass arguments to functions Save temporary results Save registers Save the processor status Runtime Environment 4-3 . to meet system requirements. Note that the assembler creates three default sections (.cinit section (which may be in ROM) and stores it in the .data section. See Section 4. At program startup. see page 4-5.1.sysmem sections should be linked into some type of RAM. does not use the .data section.sysm16 section are used by special 8-bit and 16-bit versions of the dynamic memory management functions. For more information about allocating sections into memory.bss section reserves space for global and static variables. calloc. and .sysm8 section and .bss section. malloc.bss. and . in the small model.const sections must be allocated in the same 64K data page for a small model. .Memory Model J J J The . The complete program is made up of the compiler output sections. the C compiler.bss section also reserves space for the constant table. and realloc. For the TMS320C32 only.1.const. and .sysmem section.bss and . If a program does not link these functions. .stack. the linker does not create the . The . or heap.sysmem section is a memory pool. see TMS320C3x/C4x Assembly Language Tools User’s Guide. . the . that the . however. the 4.cinit.text. The . plus the assembler’s .stack section allocates memory for the system stack. however.data sections can be linked into either ROM or RAM. The . the .data). The .3 for more information. the C boot routine copies data out of the .text. You can place these output sections anywhere in the address space. The linker takes the individual sections from different modules and combines sections having the same name to create the output sections. This memory is used to pass arguments to functions and to allocate local variables. This size allows the stack to fit into one of the on-chip RAM blocks. 4. Dynamic allocation is not a standard part of the C language. the SP is set to a designated address for the bottomof-stack.sysmem section by using the 4-4 . and realloc) that allow you to dynamically allocate memory for variables at runtime.3. refer to the TMS320C3x/C4x Assembly Language Tools User’s Guide. causing your program to fail.) The stack size is set by the linker. A stack overflow will disrupt the runtime environment. the stack has unlimited space for growth (within the limits of system memory). If you write any assembly language routines that use the runtime stack. This address is the first location in the . see Section 4. that is defined in the . or heap. the actual position of the stack is determined at link time. Memory is allocated from a global pool. The linker also creates a global symbol. At system initialization. it is provided by standard runtime-support functions.stack section is allocated. The default stack size is 1K (400h) words.4. You can set the size of the . Each function invocation creates a new frame at the top of the stack.Memory Model The runtime stack grows up from low addresses to higher addresses. You can change the size of the stack at link time by using the –stack option on the linker command line and specifying the size of the stack as a constant immediately after the option. it points to the current top of the stack.1. and assigns it a value equal to the size of the stack in words. be sure to use these registers correctly. is the frame pointer (FP). Be sure to allow enough space for the stack to grow. see Section 4.sysmem section. page 4-15.3 Dynamic Memory Allocation The runtime-support library supplied with the compiler contains several functions (such as malloc. page 4-11. calloc. The C environment manipulates these registers automatically. The compiler uses two auxiliary registers to manage this stack: SP AR3 is the stack pointer (SP). from which local and temporary variables are allocated. for more information about the stack. _ _STACK_SIZE. For more information about the –stack option. (For more information about using these registers. it points to the beginning of the current frame. Note: Stack Overflow The compiler provides no means to check for stack overflow during compilation or at runtime. If you allocate the stack as the last section in memory (highest address). Since the position of the stack depends on where the .stack section. use a pointer and call the malloc function. realloc16 These functions allocate space from the .sysm16 sections are set by specifying the –heap8 and –heap16 linker options. This allows you to use the more efficient small memory model. The 8-bit or 16-bit memory functions cause the linker to set the constant heap size values for the _SYSMEM8_SIZE and _SYSMEM16_SIZE symbols. _ _SYSMEM_SIZE. the linker will allocate the default size of 1K 8-bit or 16-bit words. free16. you can allocate large arrays from the heap instead of declaring them as global or static. which is the default. To conserve space in the . The default size is 1K words. even if you declare large data objects.bss is allocated into memory. requires that the entire . Runtime Environment 4-5 . 4. bmalloc16. For example. Neither model restricts the size of the . and the memory pool is in a separate section. Specify the size of the memory pool as a constant after the –heap option on the linker command line. minit8. For more information on the heap option. realloc8 calloc16.Memory Model –heap option when you link your program. Both models restrict the size of a single function to 32K words of code or less.4 Big and Small Memory Models The compiler supports two memory models that affect how . instead of a declaration such as: struct big table[10000]. this allows the compiler to use relative conditional jumps over the entire range of the function. The sizes of the .cinit sections. malloc8.sysm16 uninitialized sections rather than the .text or . even in the small memory model. - The small memory model. struct big *table table = (struct big *)malloc(10000 * sizeof (struct big)). Dynamically allocated objects are not addressed directly (they are always accessed with pointers).sysm8 and .h header file should be included in any file that uses these functions. free8. The stdlib. For the TMS320C32. malloc16. The linker also creates a global symbol. respectively. the dynamic memory pool can have an unlimited size.1. therefore.sysm8 and .bss section fit within a single 64K-word memory data page (65536 words).bss. the runtime support library contains the following 8-bit and 16-bit versions of the dynamic memory management functions: calloc8. and assigns it a value equal to the size of the heap in words.sysmem section. If the 8-bit or 16-bit memory management functions are used but the –heap8 and –heap16 options are not specified. bmalloc8. refer to the TMS320C3x/C4x Assembly Language Tools User’s Guide. minit16. System Initialization. 1 cycle . it must first ensure that the DP correctly identifies the memory page where the object is stored.Memory Model This means that the total space for all static and global data in the program must be less than 64K and that the .bss.bss.3. 1 extra word. Using Runtime Models. However. refer to Section 2.5 RAM and ROM Models The C compiler produces code that is suitable for use as firmware in a ROM-based system.R0 . unlimited space is available for global and static data. when the compiler accesses any global or static object that is stored in the .cinit section occupy space in memory. the initialization tables in the . Then the compiler can access all objects in the . 4-6 .cinit section (used for initialization of globals and statics) are stored in ROM. invoke the compiler with the –mb option. This task produces one extra instruction word and several extra machine cycles (one cycle for the LDP instruction plus one or more pipeline delay cycles if the object is accessed by the next instruction). A user-defined loader can read the initialization tables directly from the object file (instead of from ROM) and perform the initialization directly at load time (instead of at runtime). You can specify this to the linker by using the –cr linker option. In such a system.1.bss (global and static variables and constant tables) with direct addressing (@) without modifying the DP. 4. refer to Section 4. At system initialization time. The compiler sets the data-page pointer register (DP) during runtime initialization to point to the beginning of the . - The big memory model does not restrict the size of the .bss. you can avoid having the . For more information. the compiler must set the DP by using an LDP or LDPK (load data-page pointer) instruction each time a static or global data item is accessed. In situations where a program is loaded directly from an object file into memory and then run.bss (RAM). To accomplish this. For example. on page 4-36. on page 2-35. This is a TMS320C3x example (the sequence is one cycle shorter for the ’C4x): *** _x is a global variable *** LDP LDI _x @_x. 3 cycles (2 pipeline delays) To use the big memory model.bss cannot cross any 64K address boundaries. For more information. the following compiler-generated assembly language uses the LDP instruction to set the DP to the correct page before accessing the global variable x.8. the C boot routine copies data from these tables from ROM to the initialized variables in . No object has any type of alignment requirement.2. as are their unsigned counterparts. The compiler occasionally needs to use constants that are too long to be immediate operands.1 Data Type Storage - All basic types are 32 bits wide and stored in individual words of memory. Bit fields are allocated from LSB (least significant bit) to MSB in the order in which they are declared. and long are all equivalent. with unsigned integers that have more than 16 significant bits.Object Representation 4. which are packed into words. any object can be stored on any 32-bit word boundary. both types specify objects represented in the TMS320C3x/C4x 32-bit floating-point format. Data Types.2.2. these addresses are treated like long constants. Subsection 4. and accessed. No packing is performed except on bit fields.3 Addressing Global Variables The compiler generates the addresses of global and static symbols for indexing arrays or manipulating pointers. or with floating-point constants that have more than 11 significant nonsign bits in the mantissa. Because these addresses may be up to 32 bits wide and immediate operands are limited to 16 bits. 4.2. int. Members are not packed into structures or arrays (unless the members are bit fields).2 Long Immediate Values The TMS320C3x/C4x instruction set has no immediate operands that are longer than 16 bits.5 on page 4-9 describes the structure of the constant table. short. This occurs with signed integer constants that have more than 15 significant nonsign bits. refer to Section 3. 4. Objects that are members of structures or arrays are stored just as they are individually. For more information on data types. Runtime Environment 4-7 . aligned. on page 3-4. The long double type is represented in the TMS320C3x/C4x 40-bit format.2.2 Object Representation This section explains how various data objects are sized. The integer types char. The float and double types are equivalent. 4. Objects of type enum are also represented as 32-bit words. - It can be used in an expression. The following code is an example of incorrect string use: char *a = ”abc” a[1] = ’x’. For more information about initialization. the compiler uses the following directive statement to store the string’s address in the constant table: . refer to Section 4.8. 0 String labels have the form SLn.4 Character String Constants In C. The compiler uses this label to reference the string in the expression. The label SLn represents the address of the string constant. All uses of an identical string constant share a single definition of the string. Thus. for example: strcpy (s. In the following example. it is simply treated as an initialized array.byte ”abc”.2. on page 4-36. All strings used in a source module are defined at the end of the compiled assembly language module. along with a unique label that points to the string (the terminating 0 byte is also included).byte assembler directive. this address must be stored in the constant table in order to be accessed. it is bad practice for a program to modify a string constant. each character is a separate initializer.word SLn If the same string is used more than once within a source module.const section (possibly in ROM) and shared. These numbers begin at 0 with an increase of 1 for each string defined. in addition to storing the string itself in the . a character string constant can be used in either of two ways: - It can initialize an array of characters.const . the label SL5 points to the string from the example above: SL5 . Like all addresses of static objects. When a string is used as an initializer. the string itself is defined in the . the string will not be duplicated in memory. When a string is used in an expression. /* Incorrect! */ 4-8 .const section with the . for example: char s[ ] = ”abc”. ”abc”). System Initialization. Because strings are stored in the . n being a number assigned by the compiler to make the label unique.const section.Object Representation 4. This requires an LDP instruction before each access of the constant table. The compiler must insure that the DP register is correctly loaded before accessing the object in the table. Such objects include: - integer constants that are wider than 16 bits floating-point constants that have exponents larger than 4 bits or mantissas larger than 11 bits integer local variable initializers wider than 16 bits floating–point local variable initializers with exponents larger than 4 bits or mantissas larger than 11 bits addresses of global variables addresses of string constants The constant table is simply a block of memory that contains all such objects. the constant table is built in the . In the big memory model. avoids the overhead of loading the DP by requiring that all directly addressable objects.Object Representation 4.word and . For the code to be ROM-able.word _globvar . For example: CONST: . including all global variables as well as the constant table. for example: LDI @const+offset. As with string constants. R0 In this example. identical constants used within a source module share a single entry in the table. . . however. global variables must be stored in RAM. are stored on the same memory page. Each entry in the table occupies one word. 32 bit constant floating–point address of global address of string Objects in the table are accessed with direct addressing.2. Of course.float assembler directives.const section (and is not copied into RAM). the constant table Runtime Environment 4-9 . .word SL23 . just as with accessing global variables. offset is the index into the constant table of the required object.14159265 .float 3. The compiler builds the constant table at the end of the source module by using the . The label CONST is the address of the beginning of the table. The small model.word 011223344h . but are too wide to be used as immediate operands.5 The Constant Table The constant table contains definitions of all the objects that the compiler must access. In order to get them on the same page. refer to Section 4.bss. you can avoid the extra use of memory required by the . 4-10 .Object Representation must be in ROM. The compiler accomplishes this by placing the data for the constant table in the .8 on page 4-36. Thus the table is automatically built into RAM through the autoinitialization process. Note that the small memory model restricts the total size of the global data page to 64K words. the boot routine must copy the constant table from permanent storage in ROM to the global page in RAM. As with all autoinitialization.cinit section and allocating space for the table itself . For more information about autoinitialization.cinit section by using the –cr linker option and a “smart” loader to perform the initialization directly from the object file. It is the called function’s responsibility to preserve save on entry register variables. and the calling function’s responsibility to preserve save on call register variables. The register conventions dictate both how the code generator uses registers and how values are preserved across function calls. RS. If you plan to interface an assembly language routine to a C program.3 Register Conventions Strict conventions associate specific registers with specific operations in the C environment. it is important that you understand these register conventions. RE ST SP DP Usage Integer and float expressions Scalar return values Integer and float expressions Integer and float expressions Integer register variables Float register variables Pointer expressions Pointer expressions Frame Pointer (FP) Pointer register variables Extended frame offsets Extended frame offsets Integer expressions Block (structure) copy Status register Stack pointer Accessing globals (big model only) Preserved by Call No No No Integer part preserved Floating part preserved No No Yes Yes No No No No No Yes Yes in small model No in big model Integer part preserved No TMS320C4x Only R8 Integer register variables R9–R11 Integer and float variables Runtime Environment 4-11 . The following table summarizes how the code generator uses the TMS320C3x/C4x registers and shows which registers are defined to be preserved across function calls. There are two types of register variable registers.Register Conventions 4. save on call and save on entry. Table 4–1. The distinction between these two types of register variable registers is the method by which they are preserved across calls. Register Use and Preservation Conventions Register R0 R1 R2–R3 R4–R5 R6–R7 AR0–AR1 AR2 AR3 AR4–AR7 IR0 IR1 BK RC. In general.3. R5 R6. The code generator tries to allocate these variables to the registers listed in Table 4–2 if the value needs to be preserved across calls. If a function declares more register variables than are available for that type. so they are used only for variables that do not overlap any calls. When you are using the optimizer.3. The code generator allocates as many variables to registers as possible. then restore the saved contents on exit.2 Expression Registers The compiler uses registers not being used for register variables to evaluate expressions and store temporary results. the excess variables are treated as automatic variables and are stored in memory on the local frame. When you are not using the optimizer (–o option). you can allocate register variables with the register keyword. if the –pm shell option is used to create a single assembly file. However. Registers Reserved for Register Variables Register R4. registers not listed in Table 4–2 are not preserved across function calls.Register Conventions 4. it must save the contents of each used register on entrance to the function. Storing local variables in registers allows significantly faster access. R7 R8 AR4–AR7 Description Integer register variables Floating-point register variables (’C4x only) Integer register variables Pointer register variables These registers are preserved across calls. based on the life of a variable and when it is used.1 Register Variables Register variables are local variables or compiler temporaries defined to reside in a register rather than in memory. Table 4–2 shows the registers that are reserved to store register variables. This ensures that a called function does not disrupt the register variables of the caller. which improves the efficiency of compiled code. When a function uses register variables. Table 4–2. the code generator can more accurately determine the register usage and thereby safely use additional registers not listed in Table 4–2. 4. the compiler ignores the register keyword and treats all variables as register variables. The code generator keeps track of 4-12 . When a function requires local storage.3. The local frame is allocated during the function’s entry sequence and deallocated during the return sequence. a register that is being used for temporary storage can be saved on the local frame and used for the expression analysis. Two registers. and to avoid unnecessary accesses of variables and constants. pointer. If the compiler needs another register for storing an expression evaluation. The contents of the expression registers are not preserved across function calls. The FP is preserved as a specific part of a function’s entry and exit sequence. The FP points to the beginning or bottom of the local frame for the current function.Register Conventions the current contents of the registers and attempts to allocate registers for expressions in a way that preserves the useful contents in the registers whenever possible. it creates its own working space (local frame) from the stack. This allows the compiler to reuse register data. 4. pointers are returned in AR0.4 Stack and Frame Pointers The TMS320C3x/C4x C compiler uses a conventional stack mechanism for allocating local (automatic) variables and passing arguments to functions. 4. However. For more information about stack and frame pointer use during function calls.3. refer to Section 4. Function Structure and Calling Connections. Both the FP and the SP must be preserved across function calls. and the stack pointer points to the top location (highest memory) on the stack. The SP is a TMS320C3x/C4x register dedicated to managing the stack.3 Return Values In general. in the register–argument calling convention used for runtime support assembly files. Register AR3 is dedicated as the frame pointer (FP). the value is placed in register R0 when the function returns. The compiler uses SP in the conventional way: the stack grows toward higher addresses. when a value of any scalar type (integer. Runtime Environment 4-13 . to take advantage of the TMS320C3x/C4x’s efficient register addressing modes. or floating-point) is returned from a function. page 4-15.4. The function calls automatically preserve the SP because everything pushed for the call is popped on return. All objects stored in the local frame are referenced indirectly through the FP. This prevents the called function from ever having to save and restore expression registers. manage the stack and the local frame. the stack pointer (SP) and the frame pointer (FP). Any register that is being used for temporary storage when a call occurs is saved to the local frame before the function is called. Index registers IR0 and IR1 are used for array indexing and when an offset of more than 8 bits ( 255 words) is required for indirect addressing. If the DP is modified by an assembly language function in the small model. the DP is set at program startup and never changed. In addition. Neither register is preserved across calls. In the small model. The repeat register values are not preserved across calls. 4-14 .Register Conventions 4. the compiler can use both for a general-purpose integer register variable if it is not needed for other purposes. The compiler uses block-repeat registers (RC. Its value is not preserved across calls. These registers can be used for integer register variables if not being used for block copy operations.5 Other Registers Other registers that have specific functions are discussed below.3. - The data-page pointer (DP) is used to access global and static variables. " - The BK register is used by the compiler as an integer register variable. the function must preserve the value. therefore. no calls can be made inside of a loop structured with RPTB or RPTS instructions. and RS) to generate efficient block copy operations for assigning large (>5 words) structures. RE. Failure to adhere to these rules can disrupt the C environment and cause a program to fail.4 Function Structure and Calling Conventions The C compiler imposes a strict set of rules on function calls. If you use the register-argument model (see Section 4. This example shows allocation of a local frame for the called function. any function that calls or is called by a C function must follow these rules.2). Runtime Environment 4-15 . and the function uses local variables. SP points to the last saved register. SP points to the last saved register. Except for special runtime-support functions. Functions that have no arguments passed on the stack and no local variables do not allocate a local frame.4. The “Push Arguments” stack displays the stack just before executing the first assembly instruction of the called function (after the last instruction of the calling function).Function Structure and Calling Conventions 4. Figure 4–1 illustrates a typical function call. and FP points to the previous FP. The “Allocate Local Frame” stack displays the stack after all frame allocation. On the “Before Call” stack. parameters are passed to the function. In this example. some or all of the arguments may be passed in registers rather than on the stack as shown. On this stack. the caller pops the arguments off the stack with the following instruction: SUBI n.Function Structure and Calling Conventions Figure 4–1.1 Function Call. 2) The caller calls the function.4. Call Function Allocate Local Frame High Return Address SP Argument 1    Argument n Caller’s Local Frame SP FP Caller’s Local Frame FP Low 4. 1) The caller pushes the arguments on the stack in reverse order (the rightmost declared argument is pushed first. This places the leftmost argument at the top of the stack when the function is called. Standard Runtlme Model In general. Stack Use During a Function Call Before CALL Push Arguments. and the leftmost is pushed last).SP (n is the number of argument words that were pushed) 4-16 ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ Saved Registers argumentn Local Frame argument1 Old FP Return Address Argument 1    Argument n ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ ÉÉÉÉÉ SP FP Caller’s Local Frame . a function performs the following tasks when it calls another function. 3) When the called function is complete. A seventh register. either because of type incompatibility or because all registers have been exhausted. RS. In Figure 4–2. int b. int h). are used to pass arguments as follows: J J J The first two (left-most) floating-point (float. Int f). or long double) arguments are passed in R2 and R3. Note that structures and unions can be passed by address as an integer argument. int *c. when the register argument model is in use. double.2 Function Call. Notice how R2 and R3 are allocated first to any floats in the argument list. int e.4. AR2. and RE. Runtime Environment 4-17 . int f. AR0. are pushed onto the stack in reverse order (right-to-left). int C. float e). Then. int d. int b. in order. int d. int g. Register Argument Runtime Model In general. struct A d. a second pass allocates remaining arguments to remaining registers. several function prototypes are shown with the location of each argument indicated to illustrate the conventions. R3. int *b. /* function call */ AR2 AR2 R2 AR2 R2 R2 AR2 R2 R3 RC R3 <–––where parameters are placed RS RC R3 RC R3 STACK RS RE <–––parameters int f2(int a. Figure 4–2. Register Argument Conventions int fl(int *a. float e. int c).Function Structure and Calling Conventions 4. a function performs the following tasks when it calls another function. float b. RC. R2. The remaining integer or pointer arguments are passed in the remaining registers in the above list. may be used to return structures and unions by address. 1) Six registers. float c. /* call */ <–––parameters RE STACK STACK int f4(struct x a. /* call */ int f3(float a. All arguments that are not assigned to registers. may be used to return structures and unions by address. For example: int vararg(int a.. AR0. The last explicitly declared argument is passed on the stack. All arguments that are not assigned to registers. in order. int b. are pushed onto the stack in reverse order (right-to-left). R1. 2) The caller calls the function. . the convention is modified slightly. AR0 may also be used to return pointers. Table 4–3 lists the functions contained in the runtime-support assembly files that conform to the modified calling convention. either because of type incompatibility or because all registers have been exhausted. Four registers. 3) The caller pops the arguments that were passed on the stack. and pointer arguments are passed in the registers in the above list. if any. Register Argument Model for Runtime-Support Functions The runtime-support assembly (.asm) files use a modified version of the register argument calling convention. R2. so that its stack address can act as a reference for accessing the undeclared arguments.Function Structure and Calling Conventions If a function is declared with an ellipsis.. AR2 STACK STACK STACK STACK. A fifth register. R3. are used to pass arguments as follows: J J Integer. floating-point. indicating that it can be called with varying numbers of arguments.). 4-18 . and R4... asm mpyld.3 Responsibilities of a Called Function A called function must perform certain tasks. MOD_I MOD_U. The local frame is allocated in the following way: a) The old frame pointer is saved on the stack.asm invld. Step 1 below helps to manage the local frame. c) The frame is allocated by adding its size to the SP.asm ldexp30. If the function has no local variables.asm divi. no stack arguments.asm 4.asm divu. b) The new frame pointer is set to the current SP. Steps 1) and 6) are not taken.asm Function MPY_I30 Assembly File mpyi.asm modf30.asm MOD_I30 MOD_I40 MOD_U30 MOD_U40 modi.asm sqrt30.asm divld.asm frexp30. Runtime-Support Functions Using Modified Calling Convention Function _c_int00 _main _exit _frexp _ldexp _longjmp _setjmp _modf _sqrt DIV_F.asm setjmp.asm MPY_K30 MPY_LD DIV_I30 DIV_I40 DIV_F30 DIV_F40 DIV_U30 DIV_U40 DIV_LD mpyk. MPY_I MPY_X INV_F30 INV_F40 INV_LD Assembly File boot.asm arith410.asm divf. 1) The called function sets up the local frame. Runtime Environment 4-19 . and no need for local temporary storage.4.asm modu.asm invf. DIV_I DIV_U.Function Structure and Calling Conventions Table 4–3. 5) The called function restores all saved registers. the caller can simply place the address of s in AR0 and call f. This directs the called function not to copy the return structure. 4-20 .Function Structure and Calling Conventions 2) If the called function modifies any of the following registers. the caller can be “smart” about telling the called function where to return the structure. in the statement s = f( ). it must save them on the stack. 6) It deallocates the local frame (if necessary) by subtracting its size from SP and restores the old FP by popping it. 7) It pops the return address and branches to it. 4) If the function returns an integer. In functions with no saved registers. In other functions. 3) The called function executes its code. pointer. If the caller does not use the return value. it places the return value in R0. The delay slots are used to restore registers and deallocate the local frame. where s is a structure and f is a function that returns a structure. this is performed by executing a RETS statement. Save as integers R4 AR4 AR6 FP R5 AR5 AR7 DP (small model only) R8 (‘C4x only) Save as floating-point R6 R7 The called function may modify any other registers without saving them. the compiler loads the return address into R1 and uses a delayed branch to return. In this way. the called function then copies the structure to the memory block that AR0 points to. performing the assignment automatically. the caller allocates space for the structure and then passes the address of the return space to the called function in register AR0. In the modified register-argument calling convention used for runtime support assembly files (page 4-18). Function f then copies the return structure directly into s. AR0 is set to 0. or float. If the function returns a structure. You must be careful to properly declare functions that return structures— both at the point where they are called (so the caller properly sets up AR0) and where they are defined (so the function knows to copy the result). To return a structure. For example. pointers are returned in AR0. they can be copied to the local frame or other registers at function entry. but with negative offsets from the FP. When you are using the optimizer.2. If registers containing arguments must be freed for expression evaluation. the sequence used to access these variables is: LDI . so the arguments are copied to a local frame at function entry. However. the compiler attempts to keep register arguments in their original registers... it is critically important that the caller and callee agree both in type and number of arguments so that the called function can find the arguments. Other local variables are addressed with increasing offsets. the first local variable is addressed as *+FP(1). When register arguments are used. . Arguments passed in registers can remain in those registers as long as the register is not needed for expression evaluation.4. Stack arguments are addressed in a similar way. Rules for argument passing are described in subsection 4. If you must use a larger local frame. up to a maximum of 255 words. Other arguments are addressed with increasing offsets. try to put the most frequently used variables within the first 255 words of the frame. so the first argument is addressed as *–FP(2). IRn *+FP(IRn).4 Accessing Arguments and Local Variables A function accesses its stack arguments and local nonregister variables indirectly through the FP. if you must use locals and/or arguments with large offsets. The IR registers are also used to access arguments with offsets larger than 255.. up to a maximum of 255. offset. When you are not using the optimizer. Note: Avoid Locals and Arguments With Large Offsets It is desirable to avoid using locals and arguments with offsets larger than 255 words. Local objects with offsets larger than 255 are accessed by first loading their offset into an index register (IRn) and addressing them as *+FP(IRn).Function Structure and Calling Conventions 4.. which always points to the bottom of the local frame. the compiler needs the argumentpassing registers for expression evaluation. This sequence incurs one additional instruction and three additional clock cycles each time it is used.4. The return address is stored at the location directly below the FP. Runtime Environment 4-21 . Because the FP actually points to the old FP. 3.3. (You must preserve the DP in the small model only. whether they are written in C or assembly language. Use inline assembly language.1 Assembly Language Modules Interfacing with assembly language functions is straightforward if you follow the calling conventions defined in Section 4.REGPARM is set to 1 when –mr is used and is set to 0 otherwise.5. page 4-11. Modify the assembly language code that the compiler produces. Follow these guidelines to interface assembly language and C: - All functions. The compiler symbol _REGPARM is defined to be 1 if –mr is used and is set to 0 otherwise. and assembly code can access C variables and call C functions. The assembler symbol .Interfacing C With Assembly Language 4. Example 4–1 on page 4-25 shows how to use these symbols to write code that will work with either runtime model. C code can access variables and call functions defined in assembly language. 4.4 and the register conventions defined in Section 4. The compiler and assembler provide support for the two runtime models in the form of two predefined symbols. Note: Assembler Support for Runtlme Models The two argument-passing runtime models use different function structure and calling conventions.1. Assembly language functions called by C need to retrieve arguments according to the runtime model that was used to compile the code.5. embedded directly in the C source (see subsection 4. page 4-22).5 Interfacing C With Assembly Language There are three ways to use assembly language in conjunction with C code: - Use separate modules of assembled code and link them with compiled C modules (see subsection 4.5. page 4-28). This is the most versatile method.) These are the dedicated registers: Save as integers Save as floating-point R4 AR4 AR6 FP SP RS AR5 AR7 R6 R7 DP (small model only) R8 (‘C4x only) 4-22 . must follow the conventions outlined in Section 4.3. You must preserve any dedicated registers modified by a function. you must use a prefix of _ for all objects that are to be accessible from C. The compiler appends an underscore (_) to the beginning of all identifiers. Access arguments from the stack or in the designated registers. In assembly language modules. If the SP is used normally. and floating-point values are returned in register R0. load the designated registers with arguments. When calling C functions. C functions can change the contents of any other register. refer to Section 4.4.asm assumes that the . index registers. Runtime Environment 4-23 - - - . remember that only the dedicated registers are preserved. When calling a C function from assembly language. Integers. No assembly module should use the . which are saved as floating-point values. it does not need to be explicitly preserved. For more information about interrupt handling. and block repeat registers) are not dedicated and can be used freely without first being saved. status registers. any name that does not begin with a leading underscore may be safely used without conflicting with a C identifier.cinit section consists entirely of initialization tables.1. In other words.cinit section for any purpose other than autoinitialization of global variables. and structures are returned as described in step 4 on page 4-20. follow the guidelines in subsection 4. depending on which argument-passing model is used.4. - Interrupt routines must save the registers they use.cinit can cause unpredictable results. push the arguments on the stack in reverse order. Disrupting the tables by putting other information in .Interfacing C With Assembly Language All registers are saved as integers except R6 and R7.2. on page 4-17. pointers. For example.6 on page 4-30. Functions must return values correctly according to their C declarations. a C object named x is called _x in assembly language. on page 4-16. The C startup routine in boot. Registers R0–R7 (R0–R11 on the TMS320C4x) must be saved as complete 40-bit values because they may contain either integers or floating–point values when the interrupt occurs. the assembly function is free to use the stack as long as anything that is pushed is popped back off before the function returns (thus preserving SP). When using the register-argument model. All other registers (such as expression registers. For identifiers that are to be used only in an assembly language module or modules. and push the remaining arguments on the stack as described in subsection 4. note the underscores on all the C symbol names. which calls an assembly language function called asmfunc.BIGMODEL to conditionally assemble the LDP statement. use the predefined symbol . adds it to the C global variable called gvar. You can conditionally assemble code corresponding to different models by using these symbols as control switches when you invoke the assembler with the appropriate options (this happens automatically when you use cl30): Symbols . to access a C function or object from assembly. This creates an undefined external reference that the linker will resolve. declare the C object with . To use this example with either the large or small model.TMS320C30 . 4-24 . and returns the result. This defines the symbol as external and allows the linker to resolve references to it. For the small model.BIGMODEL Value 1 or 0 1 or 0 1 or 0 1 or 0 Description 1 if –v30 option used 1 if –v40 option used 1 if –mr option used 1 if –mb option used An Example of an Assembly Language Function Example 4–1 illustrates a C function called main. Note also how the DP must be set only when accessing global variables in the big model. the LDP instruction can be omitted. Likewise. In the assembly language code in Example 4–1.TMS320C40 .REGPARM . The asmfunc function takes its single argument. Note that this example can be used with either of the argument-passing conventions. Predefined Symbols The assembler has several predefined symbols that allow you to write assembly code that is compatible with the different runtime models.Interfacing C With Assembly Language - Any object or function declared in assembly that is to be accessed or called from C must be declared with the global directive in the assembler.global. (BIG MODEL ONLY) . the extern declaration of asmfunc is optional because the function returns an int.2 Accessing Assembly Language Variables From C It is sometimes useful for a C program to access variables or constants defined in assembly language.set AR3 .BIGMODEL LDP _gvar . . .RO if .FP LDI *–FP(2). There are three different methods that you can use to accomplish this. or a constant. Like C functions. should have prototypes so that the arguments are passed correctly. An Assembly Language Function Called From C (a) C Program extern int asmfunc(). including assembly language functions. assembly functions need be declared only if they return noninteger values. Set DP to page of gvar .REGPARM = 0 PUSH FP LDI SP.AR2 . 4.if . Standard runtime model .Restore FP In the C program in Example 4–1.endif LDI @_gvar.global _asmfunc . . Runtime Environment 4-25 . RO = gvar + argument . a variable defined in the .bss section. FP is AR3 . If you are using the register-argument runtime model.bss section. RO ADDI AR2.global _gvar _asmfunc: . . main() { int i. all functions. Declare external variable .5. a variable not defined in the .endif .endif RETS . i = asmfunc(i). int gvar. Declare external function .REGPARM = 0 POP FP . } /* declare extern asm function*/ /* define global variable */ /* call function normally */ (b) Assembly Language Program FP . standard runtime model Save old FP Point to top of stack Load argument into AR2 Both runtime models .if . depending on where and how the item is defined.Interfacing C With Assembly Language Example 4–1. you must define a pointer to the object and access it indirectly from C. 4-26 . Initialize the pointer with the assembly language label declared for the object. or you can define it in an existing section. therefore. declare the variable as extern. Note that using the big memory model causes the compiler to load the data page pointer prior to each direct memory access to variables. Define the variable . In this case.bss section and you are using the small memory model and the variable is not allocated on the same data page as the . Example 4–2. In C.bss. - Example 4–2 shows an example that accesses a variable defined in . declare a global label that points to the beginning of the object. defined in assembly. The first step is to define the object.1 _var .bss sections generated by the compiler. var = 1. To access it in C. Use the . /* External variable /* Use the variable */ */ Accessing Variables Not Defined in the . After defining the object. it can easily be linked anywhere into the memory space (this task is a little more difficult if the object is sharing an existing section).bss section is straightforward: Use the .bss From C (a) Assembly Language Program * Note the use of underscores in the following lines . Accessing a Variable Defined in . Declare it as external (b) C Program extern int var. Consider a lookup table. and access it normally.bss .bss Section It is more difficult to access a variable from C when the variable is not defined in the . that you do not want to put in RAM.bss Section Accessing uninitialized variables from the . you must declare an additional C variable to point to the object.Interfacing C With Assembly Language Accessing Variables Defined in the . remember to remove the underscore.bss directive to define the variable. Remember to precede the name with an underscore. You can define the object in its own section (either initialized or uninitialized). If the object has its own section. the following method is not needed.global _var.global directive to make the definition external. bss.0 0.bss section generated by the assembler is not allocated (by the linker) on the same data page as the . As a result of this assumption.bss From C (a) Assembly Language Program . use the C method only if the . Example 4–3. f = sine_p[4].sect _sine: .bss and because a direct reference such as this generates incorrect code. /* This is the object float *sine_p = sine.bss _sine _sine.float .015987 0. by default.global . Make a separate section . Declare variable as external ”sine_tab” .bss output section generated by the compiler. /* Access sine as normal array */ */ */ A reference such as sine[4] will not work because the object is not in . Accessing a Variable Not Defined in .float . 4 or . Example 4–3 shows an example for accessing a variable that is not defined in . /* Declare pointer to it f = sine_p[4].float _sine . this assumption is invalid.022145 (b) C Program extern float sine[]. Runtime Environment 4-27 . the optimizer is free to change indirect memory accesses to direct ones if it is more efficient to do so. If you are accessing a variable that is not defined in . Alternatively.Interfacing C With Assembly Language Note: Use the –mf Option When Using the Optimizer The optimizer. The table starts here 0.global _sine .global .bss.usect _sine “sine_tab”.bss section. the following can be used in C: extern float sine. float * sine_p = &sine. assumes that all variables are defined in the . 4 In the last case. Use the –mf option to force the optimizer to preserve indirect memory access. or the following can be used in the assembly program: . you must use the & (address of) operator to get the value.Interfacing C With Assembly Language Accessing Assembly Language Constants You can define global constants in assembly language by using the . if _x is an assembly language constant. the symbol’s declared type is unimportant. as in Example 4–4. You can reference linker-defined symbols in a similar manner. In Example 4–4. For normal variables defined in C or assembly language.global _table_size . however. . These constants are accessible from C. If you try to access an assembler (or linker) constant by name. but it is not straightforward. ++i) /* use like normal symbol */ Because you are referencing only the symbol’s value as stored in the symbol table. . you can use the asm statement to inject a single line of assembly language into the assembly language file that the compiler creates. i<TABLE_SIZE.set 10000 . define the constant . the compiler attempts to fetch a value from the address represented in the symbol table.3 Inline Assembly Language Within a C program. Accessing an Assembly Language Constant From C (a) Assembly Language Program _table_size . The compiler cannot tell which items in the symbol table are values and which are addresses.5. You can use casts and #defines to ease the use of these symbols in your program. To prevent this unwanted fetch. the symbol table contains the value of the constant. make it global (b) C Program extern int table size. int is used. For assembler constants. its value in C is &x. In other words. 4.set and .global directives or in a linker command file using a linker assignment statement. the symbol table contains the address of the value of the variable. 4-28 . /* use cast to hide address–of */ */ for (i–0. /* external ref #define TABLE_SIZE ((int) (&table_size)) . Example 4–4. The asm command is provided so that you can access features of the hardware. interrupt enable. Runtime Environment 4-29 . simply start the assembly code string with an asterisk (*) as shown below: asm(”**** this is an assembly language comment”). you can modify the interrupt control registers to enable or disable interrupts. which. The compiler does not check the inserted instructions. The asm statement is also useful for inserting comments in the compiler output.Interfacing C With Assembly Language A series of asm statements places sequential lines of assembly language into the compiler output with no intervening code. Inserting jumps and labels into C code can cause unpredictable results in variables manipulated in or around the inserted code. Directives that change sections or otherwise affect the assembly environment can also be troublesome. by definition. Although the optimizer cannot remove asm statements. Note: Avoid Disrupting the C Environment With asm Statements Be extremely careful not to disrupt the C environment with asm statements. it can significantly rearrange the code order near asm statements. and interrupt flag registers. For example. C is unable to access. The asm statement is provided so that you can access features of the hardware that would be otherwise inaccessible from C. You can also access the status. Be especially careful when you use the optimizer with asm statements. possibly causing undesired results. 4. ST.6 Interrupt Handling Interrupts can be handled directly with C functions by using a special naming convention: c_intnn nn is a two-digit interrupt number between 00 and 99. SP. it should be declared with no arguments. Interrupt handling functions should not be called directly. . it generates code that allows the function to be activated from an interrupt trap. . Thus.SP ST R3 R3 R4 R4 AR4 . including the status registers. A problem arises with the extended-precision registers R0–R7 (R0–R11 on the ‘C4x): these registers can contain either integer or floating-point values. all registers must be preserved. This involves saving both the integer part (lower 32 bits) and the floating-point part (upper 32 bits). Note that c_int00 is the C boot routine and should not be used as an interrupt routine. R4. .1 Saving Registers During Interrupts When C code or assembly code is interrupted. R3. For example: c_int01 Using one of these function names defines an interrupt routine. and AR4: PUSH LDI ADDI PUSH PUSH PUSHF PUSH PUSHF PUSH FP SP. . however. . When the compiler encounters one of these function names. . See Section 4. . The following code illustrates the entry and exit sequences for an interrupt service routine that has two local variables and uses registers FP. A C interrupt routine is like any other C function in that it can have local variables and register variables. and an interrupt routine cannot determine the type of value in a register.Interrupt Handling 4. . save old FP set up new FP allocate local frame save ST save lower 32 bits of save upper 32 bits of save lower 32 bits of save upper 32 bits of save AR4 R3 R3 R4 R3 4-30 .8 on page 4-36 for further information on this routine.FP 2.6. an interrupt routine must preserve all 40 bits of any of these registers that it modifies. Interrupt Handling Exit POP POPF POP POPF POP SUBI POP POP reti AR4 R4 R4 R3 R3 2,SP FP ST ; ; ; ; ; ; ; ; restore AR4 restore upper 32 bits of restore lower 32 bits of restore upper 32 bits of restore lower 32 bits of deallocate local frame restore Frame Pointer restore STatus register R4 R4 R3 R3 Notice how the upper and lower bits of R3 and R4 are saved and restored separately. Any extended-precision register must be saved in two parts. All other registers can be saved as integers. 4.6.2 Assembly Language Interrupt Routines Interrupts can also be handled with assembly language code, as long as the register conventions are followed. Like all assembly functions, interrupt routines can use the stack, access global C variables, and call C functions normally. When calling C functions, be sure that all nondedicated registers are preserved because the C function can modify any of them. Of course, dedicated registers need not be saved because they are preserved by the C function. Interrupt handler functions, whether in C or assembly, must be installed by placing their address in the interrupt vector table. On the TMS320C3x, this table is located in the first 64 words of the address space. On the TMS320C4x, the table can be located anywhere on any 512 word boundary in the address space. The lVTP register points to the location of the interrupt vector table. Runtime Environment 4-31 Runtime-Support Arithmetic Routines 4.7 Runtime-Support Arithmetic Routines The runtime-support library contains a number of assembly language functions that provide arithmetic routines for C math operators that the TMS320C3x/C4x instruction set does not provide, such as division. There are as many as three different versions of each of these functions. The versions are distinguished from each other by the number appended to the function name. For example, DlV_F30 is the version of DlV_F that is called when the code is compiled for the TMS320C3x, DIV_F40 is for the ‘C4x, and DIV_F is the version called by code compiled by version 4.10 (and all earlier versions) of the compiler. The TMS320C3x MPYl (multiply integer) instruction does not perform full 32-bit multiplication (the TMS320C4x MPYl instruction does); it uses only the lower 24 bits of each operand. Because standard C requires full 32-bit multiplication, a runtime-support function, MPY_I30, is provided to implement 32-bit integer multiplication for the TMS320C3x. This function does not follow the standard C calling sequence; instead, operands are passed in registers R0 and R1. The 32-bit product is returned in R0. Note that using the shell option –mp causes the code generator to inline 32-bit by 32-bit and 32-bit by 16-bit integer multiplication, rather than call MPY_I30. Inlining this multiplication significantly reduces cycle time. In addition, the MPY_I30 function is not used for squares (such as i * i); an inline squaring function is used, which also reduces cycle time. The compiler uses the TMS320C3x MPYl instruction only in cases where address arithmetic is performed (such as during array indexing); because no address can have more than 24 bits, a 24 x 24 multiply is sufficient. You can use the –mm option to force the compiler to use MPYl instructions for all integer multiplies. Because the TMS320C4x MPYl instruction performs full 32-bit multiplication, there is no MPY_I40 function. Because the TMS320C3x/C4x has no division instructions, integer and floating-point division are performed via calls to additional runtime-support functions named DlV_I30 and DIV_F30 (or DIV_I40 and DlV_F40 for the TMS320C4x). Another function, MOD_I30, performs the integer modulo operation. Corresponding functions named DlV_U30 and MOD_U30 are used for unsigned integer division and modulo. Like MPY_I30, these functions take their arguments from R0 and R1 and return the result in R0. These functions differ for the TMS320C3x and the TMS320C4x because the ‘C4x division functions take advantage of the RCPF instruction (16-bit reciprocal). 4-32 Runtime-Support Arithmetic Routines There are three runtime-support arithmetic functions specifically for extendedprecision arithmetic: MPY_LD (multiply), DIV_LD (divide), and INV_LD (inverse/reciprocals). These functions support the 40-bit long double data type. The runtime-support arithmetic functions can use expression registers without saving them. Each function has individual register-use conventions, and the compiler respects these conventions. Register use is fully documented in the source to each of the functions. The arithmetic functions are written in assembly language. Because of the special calling conventions these functions use, you cannot access them from C. Object code for them is provided in any of the runtime object libraries provided (listed in Section 2.3 on page 2-35). Any of these functions that your program needs are linked in automatically if you name one of these libraries as input at link time. The source code for these functions is provided in the source library rts.src. The source code has comments that describe the operation and timing of the functions. You can extract, inspect, and modify any of the math functions; be sure you follow the special calling conventions and register-saving rules outlined in this section. Table 4–4 summarizes the runtime-support functions used for arithmetic. Runtime Environment 4-33 Runtime-Support Arithmetic Routines Table 4–4. Summary of Runtime-Support Arithmetic Functions Function MPY_l30 MPY_K30 MPY_LD DIV_l30 DIV_I40 DIV_U30 DIV_U40 DIV_F30 DIV_F40 DIV_LD INV_F30 INV_F40 INV_LD MOD_I30 MOD_I40 MOD_U30 MOD_U40 Description Integer multiply Integer multiply by constant 40–bit float multiply Integer divide Integer divide Unsigned integer divide Unsigned integer divide Floating-point divide Floating-point divide 40–bit float divide Floating-point reciprocal Floating-point reciprocal 40–bit float reciprocal Integer modulo Integer modulo Unsigned integer modulo Unsigned integer modulo Defined In mpyi.asm mpyk.asm mpyld.asm divi.asm divi.asm divu.asm divu.asm divf.asm divf.asm divld.asm invf.asm invf.asm invld.asm modi.asm modi.asm modu.asm modu.asm Registers Used R0, R1, AR0, AR1 R0, R1, AR0, AR1 R0, R1, R2, R3, BK RC, RS, RE RC, RS, RE R0, R1, AR0, AR1, RC, RS, RE R0, R1, AR0, AR1, RC, RS,RE R0, R1, AR0, AR1 R0, R1, AR0, AR1, R10 R0, R1, R2, R3, R5, RC, BK R0, R1, AR0, AR1 R0, R1, AR0, AR1 R0, R1, R2, R3, BK R0, R1, AR0, AR1 R0, R1, AR0, AR1 R0, R1, AR0, AR1, RC, RS, RE R0, R1, AR0, AR1, RC, RS,RE Functions Provided for Compatibility With Previous Compiler Versions MPY_I MPY_X DIV_l DIV_U DIV_F MOD_I MOD_U Integer multiply arith410.asm R0–R3 R0–R3 R0–R3, RC, RS, RE R0–R3, RC, RS, RE R0–R3 R0–R3, RC, RS, RE R0–R3, RC, RS, RE Integer multiply for early arith410.asm versions of ’C30 Integer divide Unsigned integer divide Floating-point divide Integer modulo Unsigned integer modulo arith410.asm arith410.asm arith410.asm arith410.asm arith410.asm 4-34 Runtime-Support Arithmetic Routines 4.7.1 Precision Considerations The compiler will replace costly mathematical operations with narrower precision equivalents if the containing expression does not require the use of high-precision functions. For example, on the ’C3x, if the outermost operation causes the precision of the entire expression to be limited to 24 bits or less, all multiplies within the expression will be performed with the MPYI instruction instead of with the MPY_I30 function. Bit masks and shift counts may be reduced to fit within an immediate value rather than requiring a space in the constant table. For example, consider the following code fragment: int offset, index, i,j,k,l,m,n,o; i j k l m n o = = = = = = = 0xFFF & (offset * index); (offset * index) << 12; (0x00FFFFFF & offset) << 24; array[0xFF & (offset * index)]; array[(offset * index) << 12]; array[(0xFFFFFF & offset) << 24]; (0xFFFFFFF & (offset * index)) << 24; In all of the cases above, the compiler recognizes that the interior multiplications will be precision-limited by the various masks and/or shifts specified. It will then avoid using the MPY_I30 runtime support function, even though the variables offset and index are 32-bit integers. The MPYI instruction or a series of shifts will be used instead. In the assignment of variable o, the precision requirements introduced by the shift left of 24 allow the compiler to convert the value 0xFFFFFFF into 0xFF, eliminating the need to store this value on the constant table. Runtime Environment 4-35 System Initialization 4.8 System Initialization Before you can run a C program, the C runtime environment must be created. This task is performed by the C boot routine, which is a function called c_int00. The c_int00 function can be branched to, called, or vectored by reset hardware to begin running the system. The function is in the runtime-support library and must be linked with the other C object modules. This occurs automatically when you use the –c or –cr option in the linker and include a runtime-support library created from rts.src as one of the linker input files. When C programs are linked, the linker sets the entry point value in the executable output module to the symbol c_int00. The c_int00 function performs the following tasks in order to initialize the C environment: - Defines a section called .stack for the system stack and sets up the initial stack and frame pointers Autoinitializes global variables by copying the data from the initialization tables in .cinit to the storage allocated for the variables in .bss. In the small model, the constant tables are also copied from .cinit to .bss. Note this does not refer to data in the .const section In the RAM initialization model, a loader performs this step before the program runs (it is not performed by the boot routine). For more information, refer to subsection 4.8.1. - Small memory model only –– sets up the page pointer DP to point to the global storage page in .bss Calls the function main to begin running the C program You can replace or modify the boot routine to meet your system requirements. However, the boot routine must perform the four operations listed above in order to correctly initialize the C environment. The runtime-support source library contains the source to this routine in a module named boot.asm. 4.8.1 Autoinitialization of Variables and Constants Some global variables must have initial values assigned to them before a C program starts running. The process of retrieving these variables’ data and initializing the variables with the data is called autoinitialization. The compiler builds tables in a special section called .cinit that contains data for initializing global and static variables. Each compiled module contains these initialization tables. The linker combines them into a single table (a single .cinit section). The boot routine uses this table to initialize all the variables that need values before the program starts running. 4-36 the ROM model of initialization is discussed on page 4-39. Format of Initialization Records in the .cinit Section Initialization Record 1 Initialization Record 2 Initialization Record 3 Initialization Record Size in Bytes Pointer to Variable in . There are two methods for copying the initialization data into memory: RAM and ROM.cinit Section .bss. through n) contains the data that is copied into the variable to initialize it.cinit section consist of initialization records with varying sizes. record 3.bss section into which the initialization data must be copied. record 2) is the starting address of the area in the . global and static variables that are not explicitly initialized are set to 0 before program execution. Initialization Tables The tables in the . Each initialization record has the following format: Figure 4–3. any tables of long constant values or constant addresses must also be copied into the global data page at this time. (This field points to a variable’s space in . An alternative is to have a loader or boot.obj clear the .System Initialization Note: Initializing Variables In standard C. The TMS320C3x/C4x C compiler does not perform any preinitialization of uninitialized variables. record 1) is the size (in words) of the initialization data for the variable.bss section before the program starts running. Any variable that must have an initial value of 0 must be explicitly initialized. The RAM model of initialization is discussed on page 4-38. The second field (word 1.bss Initialization Data • • • Initialization Record n - The first field (word 0. Runtime Environment 4-37 .cinit and thus is automatically copied at initialization time. In the small memory model. Data for these tables is incorporated into the initialization tables in .) The third field (word 2. suppose two initialized variables are defined in C as follows: int int i = 23. a[5] = { 1. 5 }. Length of data (5 words) . If you are interfacing assembly language modules to your C program. the loader must detect the presence of the . Data to initialize i variable a . accordingly. when the program is loaded into memory.sect ”. the linker marks the . the loader must understand the format of the initialization tables so that it can use them. Instead.word 1.cinit” * Initialization record for . The RAM option requires the use of a smart loader to perform the initialization as it copies the program from the object file into memory.3.cinit section contains only initialization tables in this format. To use the RAM model.cinit section for any other purpose.cinit section and its special attribute. In the RAM model. 3.bss.cinit sections from all the C modules and appends a null word to the end of the entire section. The linker also sets the symbol cinit to –1 to indicate to the C boot routine that the initialization tables are not present in memory.System Initialization The . Initialization section variable i . specified with the –cr linker option. Data to initialize a The . 4-38 .cinit section contains an initialization record for each variable that must be initialized.4. For example.2.word 5 .cinit section with a special attribute (STYP_CPY equals 1).word _a . The initialization tables would appear as follows: . This means that the section is not loaded into memory and does not occupy space in the memory map. This can enhance performance by reducing boot time and by saving the memory used by the initialization tables.bss . Address in .5 . This appears as a record with a size field of 0 and marks the end of the initialization tables. the linker links together the . do not use the . Instead of loading the section into memory. Length of data (1 word) . the loader uses the initialization tables directly from the object file to initialize the variables in .word _i . 2. Initializing Variables in the RAM Model The RAM model. Address in .word 23 * Initialization record for .bss . When you link a program with the –c or –cr option. allows variables to be initialized at load time instead of at runtime. 4. no runtime initialization is performed at boot time.word 1 . cinit Section Loader . RAM Model of Autoinitialization Object File Memory . The linker defines a special symbol called cinit that points to the beginning of the initialization tables in memory. invoke the linker with the –c option.System Initialization A loader is not part of the compiler package. Figure 4–4. Runtime Environment 4-39 . the . To use the ROM model. Under this method.bss section Initializing Variables in the ROM Model The ROM model is the default model for autoinitialization. The loader used in TI emulator and simulator products is a smart loader. the C boot routine copies data from the tables (pointed to by cinit) into the specified variables in .cinit section is loaded into memory (possibly ROM) along with all the other sections.bss. and global variables are initialized at runtime. This allows initialization data to be stored in ROM and then copied to RAM each time the program is started. When the program begins running. bss Section (RAM) 4-40 .System Initialization Figure 4–5. ROM Model of Autoinitialization Object File Memory .cinit Section Loader Initialization Tables (ROM) Boot Routine . . . . . . . . . . . . . . . . . . . . . . . . . . .1 5. . . .Chapter 5 Runtime-Support Functions Some of the tasks that a C program must perform (such as I/O. rts. . . . . .src. . . . . . . . . . . . . . . . . contains the source for these functions. which are included with the C compiler. . . . . . These are the topics covered in this chapter: Topic 5. . . . . . . .4 Page Runtime-Support Libraries . . . . . . . . . . . . 5-13 Functions Reference . . . . . . The runtime-support library. . as well as for other functions and routines. string operations. . 5-21 Runtime-Support Functions 5-1 . . . . . . . dynamic memory allocation. floating-point arithmetic. . . . . . . . . . . . then include that library as linker input when you link your C program. . . 5-4 Summary of Runtime-Support Functions and Macros . . . . . . are standard ANSI functions that perform these tasks. The runtime-support functions. .2 5. . 5-2 Header Files . . . . .3 5. according to the desired runtime model. . . . . . . . and trigonometric functions) are not part of the C language itself. . . . . using the library-build utility. . . . . . . . . . . . be sure to build the appropriate library. . If you use any of the runtime-support functions. . . Runtime-Support Libraries 5. _c_int00. The object libraries are built from the C and assembly source contained in rts. All object libraries built from rts.lib rts40.lib rts40g. the linker includes only those library members required to resolve undefined references. refer to Section 2. When you link your program.7 on page 4-32.src. you must specify an object library as one of the linker input files so that references to runtime-support functions can be resolved. and the system startup routine.src is the source library.lib rts30g. Runtime Library rts30.lib rts30r.src include the standard C runtime-support functions described in this chapter. you can create your own runtimesupport library from rts.10 on page 2-65.lib rts40r. For more information about linking. the intrinsic arithmetic routines described in Section 4. When a library is linked.1 Runtime-Support Libraries Nine runtime-support libraries are included with the TMS320C3x/C4x C compiler: eight object libraries containing object code for the runtime-support and a source library containing source code for the functions in the object libraries.lib Processor TMS320C3x TMS320C3x TMS320C3x TMS320C3x TMS320C4x TMS320C4x TMS320C4x TMS320C4x Option(s) Used –mf –mi –o2 –x –mf –mi –o2 –x –g –mf –mi –o2 –x –mr –mf –mi –o2 –x –g –mr –v40 –mf –mi –o2 –x –v40 –mf –mi –o2 –x –g –v40 –mf –mi –o2 –x –mr –v40 –mf –mi –o2 –x –g –mr rts. If necessary.lib rts30gr. You can also use the –x linker option to force repeated searches of each library until it can resolve no more references.src by using the library-build utility (mk30) described in Chapter 6.lib rts40gr. 5-2 . You should usually specify libraries last on the linker command line because the assembler searches for unresolved references when it encounters a library on the command line. lib The –u option tells the mk30 utility to use the header files in the current directory.c ar30 r rts. extract the source as in the previous example.1 Modifying a Library Function You can inspect or modify library functions by using the archiver to extract the appropriate source file or files from rts.src atoi.obj strcpy. and then reinstall the new object file or files into the library: cl30 –options atoi. the following command extracts two source files: ar30 x rts. The use of the optimizer (– o2) and inline function expansion (– x) options does not affect compatibility with code compiled without these options. refer to Chapter 8 of the TMS320C3x/C4x Assembly Language Tools User’s Guide. For example. 5.rebuild library You can also build a new library this way. rather than extracting them from the source archive. use this command to build an optimized runtime-support library for the TMS320C4x using the big memory model and the register-argument runtime model: mk30 – –u –mr –v40 –mb –o2 –x rts.src –1 rts40rb.src.1.c To modify a function. For example. Make the required changes to the code.c strcpy. For more information about the archiver. Runtime-Support Functions 5-3 . The new library is compatible with any code compiled for the ’C4x (– v40) using the big memory model (– mb) and the register-argument runtime model (– mr).Runtime-Support Libraries 5.lib atoi.lib.src by using the library-build utility.c strcpy. recompile.1.recompile . mk30. rather than rebuilding back into rts.2 Building a Library With Different Options You can create a new library from rts.obj . h: #include <ctype.h header refers to another macro named NDEBUG (assert.h header. .h math. Before you can use the isdigit function. the program continues running.h> .h errno. assert is enabled.h stdarg. and the line number of the statement that contains the expression. If you have defined NDEBUG as a macro name when you include assert.2 Header Files Each runtime-support function is declared in a header file.2.h In order to use a runtime-support function.2. If NDEBUG is not defined. you must first use the #include preprocessor directive to include the header file that declares the function. the source file name. 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 runtime-support functions: assert.h string. then assert is turned off and does nothing.h stddef. val = isdigit(num). the macro outputs a message that contains the expression. The assert. you must first include ctype. 5. - If the expression is true (nonzero). the isdigit function is declared by the ctype. 5-4 .h does not define NDEBUG). If the expression is false. which inserts diagnostic failure messages into programs at runtime. the program terminates (via the abort function).h setjmp.h file.h header defines the assert macro.3.h stdio.1 through 5. You must include a header before you reference any of the functions or objects that it declares.h time.h.1 Diagnostic Messages (assert.h limits. then. Subsections 5. You can include headers in any order.h float. The assert macro tests a runtime expression. page 5-13. For example. Section 5.h ctype.h) The assert. .Header Files 5.7 describe the header files that are included with the TMS320C3x/C4x C compiler. lists the functions that these headers declare.2.h stdlib. h and defined in errno. For detailed information on using the low–level I/O functions. Runtime-Support Functions 5-5 .2.h) The file.2.c. 5.h header also contains macro definitions that perform these same operations. the macros run faster than the corresponding functions. When this happens. For example. see Appendix B. printf statements executed in a program appear in the debugger command window. isdigit). The errno variable is declared in errno. the capability to perform I/O on the host gives you more options when debugging and testing code. a character-typing function may test a character to determine whether it is a letter. The typing macros expand to a lookup operation in an array of flags (this array is defined in ctype. a variable named errno is set to the value of one of the following macros: - EDOM. etc. These functions return a value of true (a nonzero value) or false (0).c). For example. 5.h) The ctype. for range errors (invalid result) C code that calls a math function can read the value of errno to check for error conditions.h) Errors can occur in a math function if the invalid parameter values are passed to the function or if the function returns a result that is outside the defined range for the type of the result.h header declares the low-level I/O functions used to implement input and output operations.2.Header Files 5. for domain errors (invalid parameter) ERANGE. The C I/O functions make it possible to access the host’s operating system to perform I/O (using the debugger). The macros have the same name as the corresponding functions.h header declares functions that test and convert characters. toupper). The ctype. When used in conjunction with the debugging tools. or ASCII and return the converted character. _isdigit). Character-conversion functions have names in the form toxxx (for example.3 Error Reporting (errno.4 Low-Level I/O Functions (file. but each macro is prefixed with an underscore (for example. The character-conversion functions convert characters to lower case. Character-typing functions have names in the form isxxx (for example. a printing character. upper case.2 Character-Typing and Conversion (ctype. a hexadecimal digit. 5-6 . Macros That Supply Integer Type Range Limits (limits.5 Limits (float. Table 5–1 and Table 5–2 list these macros and the limits with which they are associated.2. Table 5–1.h and limits.h) The float.h headers define macros that expand to useful limits and parameters of the TMS320C3x/C4x numeric representations.h and limits.Header Files 5.h) Macro CHAR_BIT SCHAR_MIN SCHAR_MAX UCHAR_MAX CHAR_MIN CHAR_MAX SHRT_MIN SHRT_MAX USHRT_MAX INT_MIN INT_MAX UINT_MAX LONG_MIN LONG_MAX ULONG_MAX Note: Value 32 –2147483648 2147483647 4294967295 SCHAR_MIN SCHAR_MAX –2147483648 2147483647 4294967295 –2147483648 2147483647 4294967295 –2147483648 2147483647 4294967295 Description Number of bits in type char Minimum value for a signed char Maximum value for a signed char Maximum value for an unsigned char Minimum value for a char Maximum value for a char Minimum value for a short int Maximum value for a short int Maximum value for an unsigned short int Minimum value for an int Maximum value for an int Maximum value for an unsigned int Minimum value for a long int Maximum value for a long int Maximum value for an unsigned long int Negative values in this table are defined as expressions in the actual header file so that their type is correct. double. Macros That Supply Floating-Point Range Limits (float. or long doubles Maximum positive integers such that 10 raised to that power is in the range of representable finite floats.1920929E–07 1. double.Header Files Table 5–2. or long double Minimum negative integer such that FLT_RADIX raised to that power minus 1 is a normalized float. double. or long double Maximum float.8774817E–39 5.4028235E+38 3. doubles.19209287E–07 5.4028235E+38 3.40282367E+38 –39 Minimum negative integers such that 10 raised to that power is in the range of normalized floats.8774817E–39 5. double.h) Macro FLT_RADIX FLT_ROUNDS FLT_DIG DBL_DIG LDBL_DIG FLT_MANT_DIG DBL_MANT_DIG LDBL_MANT_DIG FLT_MIN_EXP DBL_MIN_EXP LDBL_MIN_EXP FLT_MAX_EXP DBL_MAX_EXP LDBL_MAX_EXP FLT_EPSILON DBL_EPSILON LDBL_EPSILON FLT_MIN DBL_MIN LDBL_MIN FLT_MAX DBL_MAX LDBL_MAX FLT_MIN_10_EXP DBL_MIN_10_EXP LDBL_MIN_10_EXP FLT_MAX_10_EXP DBL_MAX_10_EXP LDBL_MAX_10_EXP Value 2 –1 6 6 8 24 24 32 –126 Description Base or radix of exponent representation Rounding addition mode for floating-point Number of decimal digits of precision for a float. double.87747175E–39 3. doubles. double.0 Minimum positive float. or long double Maximum negative integer such that FLT_RADIX raised to that power minus 1 is a representable finite float. or long double number x such that 1. or long double Number of base-FLT_RADIX digits in the mantissa of a float. or long double 128 1.0 + x ≠ 1. double. or long double Minimum positive float. or long doubles 38 Key to prefixes: FLT_ applies to type float DBL_ applies to type double LDBL_ applies to type long double Runtime-Support Functions 5-7 .1920929E–07 1. it returns HUGE_VAL instead.h) The setjmp. va_list. Variable Arguments (stdarg. the math functions use this macro to represent out-or-range values. A variable-argument function can use the macros declared by stdarg. va_end. The math.h) The math. longjmp. Except where indicated.h header defines one type. and va_end.h header defines several trigonometric. These macros are used when the number and type of arguments may vary each time a function is called.7 Nonlocal Jumps (setjmp. The stdarg. all trigonometric functions use angles expressed in radians. when it knows the number and types of arguments actually passed to it. and one function for bypassing the normal function call and return discipline.6 Floating-Point Math (math.2. setjmp. va_arg. exponential.h to step through its argument list at runtime. and va_arg. These math functions expect double precision floating point arguments and return double precision floating point values. Note: Variable–Argument Functions Must Have Prototypes A variable-argument function must have a prototype to ensure that the arguments are passed correctly. When a function produces a floating-point return value that is too large to be represented. a function that uses its jmp_buf argument to restore the program environment. 5-8 . and hyperbolic math functions. a macro that saves its calling environment in its jmp_buf argument for later use by the longjmp function. 5.8 jmpbuf.h) Some functions can have a variable number of arguments whose types can differ. such functions are called variable-argument functions. These include: 5. The type.h header also defines one macro named HUGE_VAL.h header declares three macros and a type that help you to use variableargument functions: - The three macros are va_start. is a pointer type that can hold information for va_start. an array type suitable for holding the information needed to restore a calling environment.2.Header Files 5.2. one macro. 9 Standard Definitions (stddef. a signed integer type that is the resul from the subtraction of two pointers size_t.2.h: Type size_t fpos_t FILE Description An unsigned integer type that is the data type of the sizeof operator An unsigned long type that can uniquely specify every position within a file A structure type to record all the information necessary to control a stream Runtime-Support Functions 5-9 . an unsigned integer type that is the data type of the sizeof operator The macros include: The NULL macro. The types include: - ptrdiff_t.10 stdio. The result is the value of an offset in bytes to a structure member (identifier) from the beginning of its structure (type) These types and macros are used by several of the runtime-support functions. Type Declarations The following table lists the types defined in stdio. which expands to a null pointer constant(0) The offsetof(type.h—I/O Functions The stdio. which expands to an integer that has type size_t.h header defines types and macros and declares functions.h) The stddef.h header defines two types and two macros. 5.2.Header Files 5. identifier) macro. a structure type that is the type of the value returned by the div function ldiv_t.h header declares several functions. or end-of-file. respectively) in a file Expands to the maximum number of unique filenames that tmpnam() can generate Pointers to the standard error. one macro.h.11 General Utilities (stdlib. and two types.h) The stdlib. input. respectively 5.h: Macro NULL BUFSIZ EOF FOPEN_MAX FILENAME_MAX L_tmpnam SEEK_CUR SEEK_SET SEEK_END TMP_MAX stderr stdin stdout Description Expands to a null pointer constant(0).2. Originally defined in stddef. and output files. It is not redefined if it was already defined.h header also declares many of the common library functions: String conversion representations functions that convert strings to numeric Searching and sorting functions that allow you to search and sort arrays Sequence-generation functions that allow you to generate a pseudorandom sequence and allow you to choose a starting point for a sequence . start-of-file. Expands to the size of the buffer that setbuf() uses The end-of-file marker Expands to the largest number of files that can be open at one time Expands to the length of the longest file name in characters Expands to the longest filename string that tmpnam() can generate Expand to indicate the position (current.Header Files Macro Declarations The following table lists the macros defined in stdio. a structure type that is the type of the value returned by the ldiv function The stdlib. The macro is named RAND_MAX. The types include: 5-10 div_t. 12 String Functions (string.13 Time Functions (time. /* /* /* /* /* /* /* /* /* seconds after the minute (0–59) */ minutes after the hour (0–59) */ hours after midnight (0–23) */ day of the month (1–31) */ months since January (0–11) */ years since 1900 (0–99) */ days since Saturday (0–6) */ days since January 1 (0–365) */ Daylight Savings Time flag */ Runtime-Support Functions 5-11 . This structure contains members for expressing time as a combination of years. The time_t is a synonym for the type unsigned long. Times are represented in two different ways: - As an arithmetic value of type time_t. days. where a 0 value does not terminate the object. tm_min. These functions have names such as memxxx. and seconds. tm_isdst. The string functions named strxxx all operate according to this convention. 5. tm_mday. several types.h) The time header declares one macro. tm_hour. Additional functions that are also declared in string. tm_yday.Header Files - 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 5. minutes. hours.h) The string. all character strings are terminated with a 0 (null) character. 1900. months. A time represented like this is called broken-down time.2.h header declares standard functions that allow you to perform the following tasks with character arrays (strings): - Move or copy entire strings or portions of strings Concatenate strings Compare strings Search strings for characters or other strings Find the length of a string In C. As a structure of type struct_tm. When you use functions that move or copy strings. be sure that the destination is large enough to contain the result.h allow you to perform corresponding operations on arbitrary sequences of bytes (data objects). and functions that manipulate dates and times. tm_year.2. tm_wday. a time is represented as a number of seconds since 12:00 AM January 1. When expressed in this way. tm_mon. int int int int int int int int int tm_sec. The structure has the following members. To use the other time functions. whether represented as a time_t or a struct tm. either at runtime or by editing tmzone. can be expressed from different points of reference. you must supply custom versions of these functions. The basis for all the functions in time. Since these functions and the CLOCKS_PER_SEC macro are system specific.h header declares a structure type called tmzone and a variable of this type called _tz.S. central standard time. local time depends on the time zone.c and changing the initialization.h are two system functions: clock and time. 5-12 . and clock provides the system time (in arbitrary units). Time provides the current time (in time_t format). The value returned by clock can be divided by the macro CLOCKS_PER_SEC to convert it to seconds. The default time zone is U. Obviously. You can change the time zone by modifying this structure. - Calendar time represents the current Gregorian date and time. only stubs are provided in the library. The time. Local time may be adjusted for daylight savings time. Local time is the calendar time expressed for a specific time zone.Header Files A time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Summary of Runtime-Support Functions and Macros Refer to the following pages for information about functions and macros: Function or Macro Page Error Message Macro . . . . . . . . . . . . 5-19 Setjmp Function and Longjmp Macro . . . 5-14 Character-Typing Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . 5-14 Floating-Point Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15 General Utilities . . . . . 5-14 Variable-Argument Functions and Macros . . . . .Summary of Runtime-Support Functions and Macros 5. . . . . . 5-17 String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20 Time Functions . . . . . . . . . 5-19 Runtime-Support Functions 5-13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . formfeed.† double fmod(double x.h) void assert(int expression). double exp(double x).† Description Inserts diagnostic messages into programs Description Tests c to see if it’s an alphanumeric ASCII character Tests c to see if it’s an alphabetic ASCII character Tests c to see if it’s an ASCII character Tests c to see if it’s a control character Tests c to see if it’s a numeric character Tests c to see if it’s any printing character except a space Tests c to see if it’s a lowercase alphabetic ASCII character Tests c to see if it’s a printable ASCII character (including spaces) Tests c to see if it’s an ASCII punctuation character Tests c to see if it’s an ASCII spacebar.† † ‡ § 5-14 Expands inline if –x is used Macro Expands inline unless –x0 is used .† isupper(char c).† isxdigit(char c).† ispunct(char c). double y).† iscntrl(char c).‡ Character-Typing Conversion Functions (ctype. † isprint(char c). double atan(double x). double x).Summary of Runtime-Support Functions and Macros Error Message Macro (assert.† isascii(char c). double cosh(double x).† tolower(int char c).† isalpha(char c).† isgraph(char c). double atan2(double y.† isspace(char c). carriage return.h) double acos(double x). double ceil(double x).§ double floor(double x). tab (horizontal or vertical).† isdigit(char c).† toascii(char c). double asin(double x). † islower(char c). or newline character Tests c to see if it’s an uppercase ASCII alphabetic character Tests c to see if it’s a hexadecimal digit Masks c into a legal ASCII value Converts c to lowercase if it’s uppercase Converts c to uppercase if it’s lowercase Description Returns the arccosine of x Returns the arcsine of x Returns the arctangent of x Returns the arctangent of y/x Returns the smallest integer greater than or equal to x Returns the cosine of x Returns the hyperbolic cosine of x Returns the exponential function of x Returns the absolute value of x Returns the largest integer less than or equal to x Returns the floating-point remainder of x/y Floating-Point Math Functions (math.† double cos(double x).h) int int int int int int int int int int int int char char char isalnum(char c).† toupper(int char c). double fabs(double x). register FILE *iop).Summary of Runtime-Support Functions and Macros Floating-Point Math Functions (continued) double frexp(double value. mode points to a string describing how to open the file I/O Functions (stdio. Variable-Argument Functions and Macros (stdarg. double tan(double x). const char *mode). double y). int fclose(FILE *iop). double log(double x).h) void clearerr(FILE *p). register int size. int *iptr). double sin(double x).‡ va_end(va_list ap). int fgetpos(FILE *iop. double pow(double x. FILE *fopen(const char *file. int exp). int feof(FILE *p). double sinh(double x). char *fgets(char *ptr. double tanh(double x). int fgetc(register FILE *fp).h) type void void va_arg(va_list ap).‡ va_start(va_list ap). int fflush(register FILE *iop). fpos_t *pos). double ldexp(double x. † ‡ § Expands inline if –x is used Macro Expands inline unless –x0 is used Runtime-Support Functions 5-15 . int *exp). double modf(double value. double sqrt(double x).‡ Description Breaks value into a normalized fraction and an integer power of 2 Multiplies x by an integer power of 2 Returns the natural logarithm of x Returns the base-10 logarithm of x Breaks value into a signed integer and a signed fraction Returns x raised to the power y Returns the sine of x Returns the hyperbolic sine of x Returns the nonnegative square root of x Returns the tangent of x Returns the hyperbolic tangent of x Description Accesses the next argument of type type in a variable-argument list Resets the calling mechanism after using va_arg Initializes ap to point to the first operand in the variable-argument list Description Clears the EOF and error indicators for the stream that p points to Flushes the stream that iop points to and closes the file associated with that stream Tests the EOF indicator for the stream that p points to Tests the error indicator for the stream that p points to Flushes the I/O buffer for the stream that iop points to Reads the next character in the stream that fp points to Stores the object that pos points to to the current value of the file position indicator for the stream that iop points to Reads the next size minus 1 character from the stream that iop points to into array ptr Opens the file that file points to. double log10(double x). int ferror(FILE *p). register FILE *iop).). .Summary of Runtime-Support Functions and Macros I/O Functions (continued) int fprintf(FILE *iop. void setbuf(register FILE *iop. int getchar(void).). const fpos_t *pos).. points to the stream pointed to by iop Reads from the stream pointed to by iop and stores the input to the array pointed to by ptr Opens the file that file points to using the stream that iop points to. register FILE *iop). char *buf). c. size_t size. register int type. const char *new).. const char *format. const char *fmt. int fseek(register FILE *iop. FILE *p). to the stream that fp points to Writes the string pointed to by ptr. . int remove(const char *file). FILE *freopen(const char *file.. int rename(const char *old. int putc(int x. Defines and associates a buffer with a stream register char *buf.). size_t size. size_t count. . long offset.. Description Writes to the stream that iop points to Writes a single character. FILE *iop). size_t fwrite(const void *ptr. register size t_size). int puts(const char *ptr). 5-16 . int getc(FILE *p). void perror(const char *s).. int fsetpos(FILE *iop. mode points to a string describing how to open the file Reads from the stream pointed to by iop Sets the file position indicator for the stream pointed to by iop Sets the file position indicator for the stream that iop points to pos. the pointer pos must be a value from fgetpos() on the same stream Obtains the current value of the file position indicator for the stream that iop points to Writes a block of data from the memory pointed to by ptr to the stream that iop points to A macro that calls fgetc() A macro that calls fgetc() and supplies stdin as the argument Maps the error number in s to a string and prints the error message Performs the same function as fprintf but uses stdout as its output stream A macro that performs like fputc() Writes a character to the standard output device Writes a string (pointed to by ptr) to the standard output device Makes the file pointed to by file no longer available by that name Renames the file pointed to by old to the name pointed to by new Sets the file position indicator for a stream to the beginning of the file pointed to by iop Reads the stream from the standard input device Specifies the buffer used by the stream pointed to by iop int setvbuf(register FILE *iop. int scanf(const char *format.. void rewind(register FILE *iop). size_t count. int fputs(const char *ptr. int fscanf(FILE *iop. const char *mode. register FILE *fp). int ptrname).. int putchar(int x). int printf(const char *format. long ftell(FILE *iop). .). size_t fread(void *ptr. register FILE *iop).. int fputc(int c. *calloc8(size_t _num. int ungetc(int c. *bmalloc8(size_t _size). int vfprintf(FILE *iop. size_t n. *calloc16(size_t _num.). const char *format. size_t size). FILE *tmpfile(void). va_list ap). *bmalloc16(size_t _size). Expands inline if –x is used Macro Expands inline unless –x0 is used void void void div_t † ‡ § Runtime-Support Functions 5-17 . size_t size.. const char *format. – 8-bit version (TMS320C32 only) – 16-bit version (TMS320C32 only) Divides numer by denom producing a quotient and a remainder double atof(char *nptr). to be called without arguments at normal program termination Converts a string to a floating-point value Converts a string to an integer value Converts a string to a long integer value Allocate memory on a boundary – 8-bit version (TMS320C32 only) – 16-bit version (TMS32C32 only) Searches through an array of n objects for the object that key points to Allocates and clears memory for n objects. int (*compar) (void)). const char *format. Description Writes to the array pointed to by string Reads from the string pointed to by str Creates a temporary file Generates a string that is a valid filename Writes the character c to a stream pointed to by p Writes to the stream pointed to by iop.§ abort(void) atexit(void (*fun)(void)). FILE *p). *bmalloc(size_t _size). char *tmpnam(char *s). void *base. Writes to the array pointed to by string va_list ap).. General Utilities( stdlib.Summary of Runtime-Support Functions and Macros I/O Functions (continued) int sprintf(char *string. size_t _size).). div(int numer. int sscanf(const char *str.. size_t _size). Description Returns the absolute value of j Terminates a program abnormally Registers the function pointed to by fun. each of size bytes.h) int void void abs(int j). atol(char *nptr).. Writes to the standard output device int vsprintf(char *string. const char *format. int denom). va_list ap). . int vprintf(const char *format. int long void void void void atoi(char *nptr). *calloc (size_t n. . *bsearch(void *key. int † ‡ § ti_sprintf(char *s. *malloc8(size_t _size). calloc. or realloc – 8-bit version (TMS320C32 only) – 16-bit version (TMS320C32 only) Sorts an array of n members. and size specifies the size of members Returns a sequence of pseudorandom integers in the range 0 to RAND_MAX Changes the size of memory pointed to by ptr to size bytes – 8-bit version (TMS320C32 only) –16-bit version (TMS320C32 only) Resets the random number generator Converts a string to a floating-point value double strtod(char *nptr. const char *format).Summary of Runtime-Support Functions and Macros General Utilities (continued) void void void void long ldiv_t int void void void void void void void int void void void void exit(int status). minit16(void). Converts a string to an unsigned long integer value int base). Expands inline if –x is used Macro Expands inline unless –x0 is used Supports conversion functions required by time() 5-18 . Description Terminates a program normally Deallocates memory space allocated by malloc. ltoa(long n. free(void *ptr). *realloc(void *ptr. long denom). free16(void *_prt). free8(void *_prt). qsort(void *base. size_t n. *realloc16(void *_ptr. long base). or realloc – 8-bit version (TMS320C32 only) – 16-bit version (TMS320C32 only) Returns the absolute value of j Divides numer by denom producing a quotient and a remainder Converts n to the equivalent digit string Allocates memory for an object of size bytes – 8-bit version (TMS320C32 only) – 16-bit version (TMS320C32 only) Resets all the memory previously allocated by malloc. srand(unsigned seed). labs(long j). int (*_compar) (void)). minit(void). calloc. char **endptr. size_t _size). size_t _size. int Converts a string to a long integer value unsigned long strtoul(char *nptr. *malloc(size_t size). base points to the first member of the unsorted array. *malloc16(size_t _size). strtol(char *nptr. *realloc8(void *_ptr. char *buffer). minit8(void). char **endptr. char **endptr). rand(void). size_t size). size_t _size).§ ldiv (long numer. † *strpbrk(char *s1. size_t n). *strncpy(char *s1. which is entirely made up of characters from s2 Finds the first occurrence of s2 in s1 Breaks s1 into a series of tokens.† *memcpy(void *s1. size_t n). char *s2. *strstr(char *s1. char *s2). char *s2). size_t n). size_t n).† *memmove(void *s1.† strcmp(char *s1. char *s2). char *s2. strlen(char *s). depending on the locale: <0 if s1 is less than s2.† memcmp(void *s1.† *strncat(char *s1. Description Finds the first occurrence of c in the first n characters of s Compares the first n characters of s1 to s2 Copies n characters from s1 to s2 Moves n characters from s1 to s2 Copies the value of c into the first n characters of s Appends s2 to the end of s1 Finds the first occurrence of character c in s Compares strings and returns one of the following values: <0 if s1 is less than s2.† *strchr(char *s. each delimited by a character from s2 char size_t char size_t char int char char char size_t char char † ‡ § *strcpy(char *s1. Expands inline if –x is used Macro Expands inline unless –x0 is used Runtime-Support Functions 5-19 .† *strcat(char *s1. size_t n). void *s2. size_t n).† strcspn(char *s1. void *s2. strncmp(char *s1.void *s2. char *s2). =0 if s1 is equal to s2. char *s2).Summary of Runtime-Support Functions and Macros String Functions( string. char *s2).h) void int void void void char char int int *memchr(void *s. char *s2).† *strcoll(char *s1. char *s2. >0 if s1 is > s2 Compares strings and returns one of the following values. char *s2). int c. =0 if s1 is equal to s2. size_t n). int c). strspn(char *s1. >0 if s1 is greater than s2 Copies string s2 into s1 Returns the length of the initial segment of s1 that is made up entirely of characters that are not in s2 Maps the error number in errnum to an error message string Returns the length of a string Appends up to n characters from s1 to s2 Compares up to n characters in two strings Copies up to n characters of a s2 to s1 Finds the last occurrence of character c in s Locates the first occurrence in s1 of any character from s2 Returns the length of the initial segment of s1. *strtok(char *s1. char *s2). *strrchr(char *s. size_t n). char c). *strerror(int errnum). int c. *memset(void *s. Description Saves calling environment for later use by longjmp function Uses jmp_buf argument to restore a previously saved environment Converts a time to a string Description Determines the processor time used Converts time to a string Time Functions (time. struct tm *timeptr). Converts local time to Greenwich Mean Time Converts time_t value to broken down time Converts broken down time to a time_t value strftime(char *s. mktime(struct tm *timeptr). *asctime(struct tm *timeptr).h) clock_t char double time0). *ctime(struct time *timeptr). struct tm struct tm time_t size_t time_t † ‡ § clock(void). time(time_t *timer).h) int void char setjmp(jmp_buf env). *localtime(time_t *timer).Summary of Runtime-Support Functions and Macros Nonlocal Jumps (setjmp. Expands inline if –x is used Macro Expands inline unless –x0 is used Returns the current calendar time 5-20 . int returnval). size_t Formats a time into a character string maxsize. difftime(time_t time1. time_t Returns the difference between two calendar times *gmtime(time_t *timer).*format.‡ longjmp(jmp_buf env. . . . . fgetpos . . . . . . . . memcpy . . . . . . . . . . isxxx . . fputc . add_device . realloc . . . . . . . . . . . . memset . . modf . . . . . . . . . . . log10 . fwrite . . . . . . . . . . . . . . . . . . . . . . . . . . strstr . . . . . . . tmpfile . . . . strtok . fgetc . . . . . clock . . . . . . . . . . . cos . . . . . . . strlen . . . . . . . . . . . . malloc . . . . fflush . . . . . . . . . . . . . . . . . . . . . . atexit . . fsetpos . . . . . . . . . . . getc . . . . . . . . . . . . . . itoa . . . . . . . . . . . . . . Function or Macro floor . . pow . . . . . . . . . . . . . . . . printf . . . . putc . ferror . . . . . . . . . tmpnam . sprintf . . strtol/strtoul . . . ftell . . . . . . . qsort . . . strncmp . . . time . . . . . rename . . . . . . . . . . . . . . . . . .Functions Reference 5. fseek . . . . . . . . strxfrm . . . . . . . . . . . . . strncpy . . . . . . . . strrchr . . . . fputs . strerror . . . . . . . . . . . . . . . atan2 . . . . . . . . . . . . . . . . . . . . . . vsprintf . . . . . . . . . . . . . asctime . . . . . . . . . . . strncat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . getchar . . . . . . . . . . . . . . fopen . scanf . . . . . . . . . . . . . fprintf . . . labs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . strcat . . . . . . . sinh . . . . . . . . . . . . . . . . . . . . . . . cosh . . . bsearch . . . . . . . . . . . . . . asin . . . . . . . . feof . . . . . . . . . . . . . . . . . . . . The following table lists the functions and macros and directs you to the detailed description of the function or macro: Function or Macro abort . .4 Functions Reference This section contains an alphabetical list of the functions and macros declared in the header files. . . . . . printf . . . . fmod . . . strcmp/strcoll . . . va_arg/va_end/ va_start . . . . . . exit . . . localtime . . . strspn . . . . . . . vfprintf . . . . . . . ctime . . . . . . . . tolower/toupper ungetc . tan . . . . . . . calloc . . . . . . . rand . . . . . . . . . strcpy . . . . . . . . . . . . . . . . . . assert . . . . clearerr . . . . . . . . sin . . div . sqrt . . atof/atoi/atol . . fscanf . . . . puts . . . . . toascii . . . . srand . . . . . . . . . . Page 5-22 5-22 5-22 5-23 5-25 5-25 5-26 5-27 5-27 5-27 5-28 5-30 5-31 5-32 5-32 5-33 5-33 5-34 5-34 5-34 5-35 5-36 5-36 5-36 5-37 5-37 5-37 5-37 5-38 5-38 5-38 Page 5-39 5-39 5-39 5-40 5-40 5-40 5-40 5-41 5-41 5-42 5-42 5-42 5-43 5-43 5-43 5-43 5-44 5-44 5-44 5-44 5-45 5-22 5-46 5-35 5-46 5-46 5-47 5-60 5-47 5-48 5-49 Page 5-49 5-49 5-50 5-50 5-51 5-52 5-53 5-53 5-54 5-54 5-54 5-55 5-55 5-54 5-56 5-57 5-57 5-58 5-58 5-59 5-59 5-59 5-60 5-61 5-61 5-62 5-62 5-62 5-57 5-63 5-63 Page 5-64 5-64 5-65 5-65 5-66 5-66 5-67 5-68 5-69 5-70 5-71 5-64 5-72 5-72 5-73 5-74 5-73 5-74 5-75 5-75 5-76 5-76 5-76 5-76 5-77 5-77 5-78 5-79 5-79 5-79 Runtime-Support Functions 5-21 . . . . difftime . . . . . . ldexp . . . . ceil . . . . . . . . . . . . . . . . . . . . . . setvbuf . perror . memmove . . . . . freopen . getenv . . . . . . fclose . . . . . . . atan . . memchr . . . . . . . . . . tanh . . . strcspn . . . . acos . . . . . . . . . . . . . remove . . . . . . . putchar . . . . . . . . abs . rewind . ldiv . . . . fread . . . . . . . . . . . . . log . . . vprintf . Function or Macro memcmp . . . . . . setjmp . . . . . . . . . . . . . . . . . . . . sscanf . . . . . . . frexp . . fgets . . . . . . . . . . exp . . . . . . . . . . strtod . . . . . . . . . . . . . gmtime . . . . . . . . . . . . strpbrk . . . . . . . . . setbuf . mktime . . . . . minit . lonjmp . fabs . . . . . . free . . . . gets . . . . . . . . . . . . . Function or Macro strchr . . . . . . . . . strftime . . . . . . . . . . . . . . h> void abort(void). } This makes the abort function equivalent to the exit function. radians. realval = 0. radians = acos(realval).c in rts. Defined in Description Example acos. The labs function returns the absolute value of a long integer k. /* abs returns 5 */ acos Syntax Arc Cosine #include <math. The TMS320C3x/C4x implementation of the abort function calls the exit function with a value of 0.h> int abs(int j).0. abs/labs Syntax Absolute Value #include <stdlib. abs/labs. The abs and labs functions are expanded inline unless the –x0 option is used. The return value is an angle in the range [0. Defined in Description abs. the abs and labs functions are also functionally equivalent. /* acos return return (radians). and is defined as follows: void abort () { exit(0). exit.c in rts.c in rts.π] radians. double realval.src The abort function usually terminates a program with an error code.h> double acos(double x). Example int x = –5. 5-22 π/2 */ . x must be in the range [–1.src The C compiler supports two functions that return the absolute value of an integer: The abs function returns the absolute value of an integer j.1].abort. int y = abs (x). - Since int and long int are functionally equivalent types in TMS320C3x/C4x C. long int labs(long int k).src The acos function returns the arc cosine of a floating-point argument x. acos Alphabetical Summary of Runtime-Support Functions abort Syntax Defined in Description Abort #include <stdlib. int (*dwrite)(). drename Function pointers to the device drivers are called by the low-level functions to perform I/O on the specified device. Defined in Description lowlev. The function. use fopen() with a string of the format devicename:filename as the first argument. int (*dclose)(). allowing that device to be used for input/output from C. You must declare these functions with the interface specified in subsection B. To open a stream on a newly-added device. The device drivers for the host that the ’C3x/’C4x debugger is run on are included in the C I/O library. int (*dread)(). The flags denote the following: _SSA _MSA The device supports only one open stream at a time The device supports multiple open streams More flags can be added by defining them in stdio. dunlink. unsigned flags. int (*drename)()). Return Value 0 if successful –1 if it fails Runtime-Support Functions 5-23 .2. dlseek. dwrite. dopen.h> int add_device(char *name.c in rts.h. finds the first empty position in the device table and initializes the fields of the structure that represent a device. int (*dlseek)(). Parameters name flags Character string denoting the device name Device characteristics. add_device(). dclose. int (*dunlink)(). int (*dopen)(). Overview of Low-Level I/O Implementation.Alphabetical Summary of Runtime-Support Functions add_device add_device Syntax Add Device to Device Table #include <stdio. on page B-3.src Adds a device record to the device table. dread. The first entry in the device table is predefined to be the host device on which the debugger is running. world\n”). my_lseek. _MSA. } 5-24 . unsigned count). fprintf(fid. long offset. extern int my_unlink(char *path).”w”). main() { FILE *fid. add_device(”mydevice”. char *buffer. extern int my_rename(char *old_name. my_close. my_unlink. int fno). my_read. char *new_name).add_device Example Alphabetical Summary of Runtime-Support Functions This example does the following: #include <stdio. char *buffer. extern int my_lseek(int fno. my_write. extern int my_close(int fno). world into the file Closes the file /****************************************************************************/ /* Declarations of the user–defined device drivers */ /****************************************************************************/ extern int my_open(char *path.h> Adds the device mydevice to the device table Opens a file named test on that device and associate it with the file *fid Writes the string Hello. fclose(fid). unsigned count). fid = fopen(”mydevice:test”. unsigned flags. int origin).”Hello. extern int my_write(int fno. my_open. extern int my_read(int fno. my_rename). page 5-11.h header declares.h> double asin(double x). Defined in Description asin.h> char *asctime(struct tm *timeptr).0. asin Syntax Arc Sine #include <math. realval = 1. asin asctime Syntax Internal Time to String #include <time.src The asctime function converts a broken-down time into a string with the following form: Mon Jan 11 11:18:36 1988 \n\0 The function returns a pointer to the converted string. For more information about the functions and types that the time. radians = asin(realval).π/2] radians.2. refer to subsection 5.13. double realval.Alphabetical Summary of Runtime-Support Functions asctime. Defined in Description asctime. radians. The return value is an angle in the range [–π/2. x must be in the range [–1.c in rts.1].c in rts.src The asin function returns the arc sine of a floating-point argument x. Example /* asin returns π/2 */ Runtime-Support Functions 5-25 . then the assert macro is defined to have no effect. The assert macro is defined with the printf function.h is included. Defined in Description assert. line number.h as a macro The assert macro tests an expression. int i. an integer i is divided by another integer j. and then aborts execution. NDEBUG. the assert macro writes information about the particular call that failed to the standard output. If j = = 0 when this code runs. If you have defined NDEBUG as a macro name when the assert. depending upon the value of the expression. If expression is true.c.h header is included in the source file. you must either: Example Provide your own version of printf. the assert macro is defined to test the expression and. j. - If expression is false. and test of expression. line 123 is sent to standard output. if false. q = i/j. This macro is useful for debugging. file foo. which is not included in the library. The header file that declares the assert macro refers to another macro. assert(j). If NDEBUG is not defined when assert. the assert macro does nothing. Since dividing by 0 is an illegal operation. To use assert. the example uses the assert macro to test j before the division. assert either aborts execution and issues a message or continues execution.h> void assert(int expression). a message such as: Assertion failed (j). 5-26 .assert Alphabetical Summary of Runtime-Support Functions assert Syntax Insert Diagnostic Information Macro #include <assert. write a diagnostic message including the source filename. or Modify assert to output the message by other means In this example. 1.src The atan2 function returns the arc tangent of y/x.h> double atan2(double y.0.c in rts.h> double atan(double x). the functions that were registered are called. a call to abort. x). atexit atan Syntax Polar Arc Tangent #include <math. in reverse order of their registration. 1.src The atexit function registers the function that is pointed to by fun.0. Defined in Description Example atan. –1.h> void atexit(void (*fun)(void)).Alphabetical Summary of Runtime-Support Functions atan. atan2. realval = 1.0) /* /* /* /* returns π/4 */ returns 3π/4 */ returns ±π/4 */ returns –3π/4 */ Example atexit Syntax Exit Without Arguments #include <stdlib. or a return from the main function.c in rts.src The atan function returns the arc tangent of a floating-point argument x. /* return value = π/4*/ atan2 Syntax Cartesian Arc Tangent #include <math.0) (–1. radians = atan(realval). radians. to be called without arguments at normal program termination.π/2] radians. without arguments. The return value is an angle in the range [–π. Both arguments cannot be 0. The return value is an angle in the range [–π/2. Up to 32 functions can be registered. atan2 atan2 atan2 atan2 (1.c in rts. Defined in Description atan.0. –1.0.π] radians. Defined in Description exit.0) (1. The function uses the signs of the arguments to determine the quadrant of the return value.0) (–1. When the program exits through a call to the exit function. double realval.0. Runtime-Support Functions 5-27 . atof/atoi/atol Alphabetical Summary of Runtime-Support Functions atof/atoi/atol Syntax Convert ASCII to Number #include <stdlib. Argument nptr points to the string.src Three functions convert strings to numeric representations: - The atof function converts a string into a floating-point value. /* d = . Since int and long are functionally equivalent in TMS320C3x/C4x C. Following the space is an optional sign.c in rts.digits] [e|E [sign] integer] The atoi function converts a string into an integer. Argument nptr points to the string. a form feed.23e–2). a carriage return. the string must have the following format: [space] [sign] digits The space is indicated by one or more of the following characters: a space (character). or a newline. the atoi and atol functions are also functionally equivalent. including an optional sign. i = atoi (“–3291”). The functions do not handle any overflow resulting from the conversion. The fractional part of the number follows. long int atol(char *nptr). the string must have the following format: [space] [sign] digits The atol function converts a string into a long integer. /* i = –3291 */ d = atof (“1. Defined in Description atof. int atoi(char *nptr).c and atoi. Example int i.h> double atof(char *nptr). double d. Argument nptr points to the string. and then digits that represent the integer portion of the number. The first character that cannot be part of the number terminates the string. the string must have the following format: [space] [sign] digits [. a horizontal or vertical tab.0123 */ 5-28 . then the exponent. Runtime-Support Functions 5-29 . Default heap size is 1K words. however. The memory that bmalloc uses is in a special memory pool or heap.c in rts.sysm8 and .1. memory is allocated from the uninitialized sections . void *bmalloc8(size_t _size).sysmem in memory.Alphabetical Summary of Runtime-Support Functions bmalloc bmalloc Syntax Allocate Memory on a Boundary #include <stdlib. respectively.h> void *bmalloc(size_t _size). Dynamic Memory Allocation.sysm8 or .src The bmalloc function allocates space for an object of size bytes and returns a pointer to the space.sysm16 section when a size is specified using the –heap8 or –heap16 option. It will create a section of the default size (1K of 8-bit or 16-bit words) when the bmalloc8 and bmalloc16 functions are used and the –heap8 and –heap16 options are not. See the TMS320C3x User’s Guide for information on circular buffers and bit–reversed addressing. on page 4-4. The linker creates a . defined in an uninitialized named section called . For the TMS320C32 processor. refer to subsection 4.sysm16. 8-bit and 16-bit versions of the bmalloc function are provided.3. For more information. Defined in Description memory.c. The packet of the given size is aligned on a boundary suitable for TMS320C3x and TMS320C4x circular buffers and bit–reversed address buffers. void *bmalloc16(size_t _size). The linker sets the size of this section from the value specified by the –heap option. The functions bmalloc8 and bmalloc16 are analogous to bmalloc. void *base. If a match is found. const void *ptr2). 0 if *ptr1 is equal to *ptr2. int p = bsearch (&key. Example #include <stdlib. 3. the comparison must return <0. the function returns a null pointer (0). The contents of the array must be in ascending. The comparison function should be declared as: int cmp(const void *ptr1. 6. if no match is found. } 5-30 . the function returns a pointer to the matching member of the array. 4.h> int list [ ] = {1. const void *0. Argument base points to the first member in the array. main( ) { int key = 8. Argument compar points to a user-defined function that compares key to the array elements. const void *i2) { return *(int *) i1 – *(int *) i2. 0. 1.bsearch Alphabetical Summary of Runtime-Support Functions bsearch Syntax Array Search #include <stdlib.h> #include <stdio.c in rts. size_t size. int diff (const void *. 6. 9}. sorted order. In order for the search to work properly. The cmp function compares the objects that ptr1 and ptr2 point to and returns one of the following values: < 0 if *ptr1 is less than *ptr2. /* p points to list[4] */ } int idiff (const void *il. list. > 0 if *ptr1 is greater than *ptr2. size specifies the size (in bytes) of each member. idiff). 8. >0.src The bsearch function searches through an array of nmemb objects for a member that matches the object that key points to.h> void *bsearch(void *key. size_t nmemb. Defined in Description bsearch. int (*compar)(void)). The memory that calloc uses is in a special memory pool or heap. For the TMS320C32 processor. Default heap size is 1K words.c in rts. Defined in Description memory. size_t _size). however.2). The functions calloc8 and calloc16 are analogous to calloc. respectively. /*Allocate and clear 20 bytes */ Runtime-Support Functions 5-31 .sysm8 or . size_t _size). The function initializes the allocated memory to all 0s.sysm8 and . void *calloc16(size_t _num. size_t size). refer to subsection 4. defined in an uninitialized named section called . If it cannot allocate the memory (that is.sysm16 section when a size is specified using the –heap8 or –heap16 option. Dynamic Memory Allocation. Example This example uses the calloc routine to allocate and clear 10 bytes.sysmem in memory.Alphabetical Summary of Runtime-Support Functions calloc calloc Syntax Allocate and Clear Memory #include <stdlib. it returns a null pointer (0). if it runs out of memory).3.1. on page 4-4. memory is allocated from the uninitialized sections . It will create a section of the default size (1K of 8-bit or 16-bit words) when the calloc8 and calloc16 functions are used and the –heap8 and –heap16 options are not. ptr = calloc (10. For more information. 8-bit and 16-bit versions of the calloc function are provided.c.src The calloc function allocates size bytes for each of nmemb objects and returns a pointer to the space.sysm16. The linker sets the size of this section from the value specified by the –heap option. void *calloc8(size_t _num. The linker creates a .h> void *calloc(size_t nmemb. c in rts. Example /* answer = 4.ceil.h> double ceil(double x).0 */ clearerr Syntax Clear EOF and Error Indicators #include <stdio. answer = ceil(–3. 5-32 .5). Defined in Description ceil.src The ceil function returns a floating-point number that represents the smallest integer greater than or equal to x.h> void clearerr(FILE *p). Defined in Description clearerr.c in rts. The ceil function is inlined if the –x2 option is used. clearerr Alphabetical Summary of Runtime-Support Functions ceil Syntax Ceiling #include <math. double answer.src Clears the EOF and error indicators for the stream that p points to.0 */ /* answer = –3.1415). answer = ceil(3. /* return value = –1. cos clock Syntax Processor Time #include <time.Alphabetical Summary of Runtime-Support Functions clock. The return value can be converted to seconds by dividing by the value of the macro CLOCKS_PER_SEC. It returns an approximation of the processor time used by a program since the program began running. the clock function returns the value of –1.src The cos function returns the cosine of a floating-point number x.c in rts.2. The angle x is expressed in radians. An argument with a large magnitude may produce a result with little or no significance. For more information about the functions and types that the time. page 5-11.h header declares.13.h> double cos(double x). Defined in Description clock.c in rts. Defined in Description cos. cval.h> clock_t clock(void). /* cos returns cval */ radians = 3. Note: Writing Your Own Clock Function The clock function is target-system specific. cos Syntax Cosine #include <math. cval = cos(radians). refer to subsection 5. double radians.1415927. so you must write your own clock function. If the processor time is not available or cannot be represented. You must also define the CLOCKS_PER_SEC macro according to the granularity of your clock so that the value returned by clock( ) (number of clock ticks) can be divided by CLOCKS_PER_SEC to produce a value in seconds.0 */ Example Runtime-Support Functions 5-33 .src The clock function determines the amount of processor time used. src The cosh function returns the hyperbolic cosine of a floating-point number x.cosh. difftime Syntax Time Difference #include <time. time1 minus time0. page 5-11. time_t time0). 5-34 . x = 0. /* return value = 1. page 5-11. Defined in Description difftime. This is equivalent to: asctime(localtime(timer)) The function returns the pointer returned by the asctime function.h> double difftime(time_t time1. y. y = cosh(x).c in rts. refer to subsection 5. A range error occurs if the magnitude of the argument is too large. The return value is expressed in seconds. Defined in Description Example cosh.2. double x.0. For more information about the functions and types that the time.src The difftime function calculates the difference between two calendar times.h> double cosh(double x). refer to subsection 5. ctime.h header declares. Defined in Description ctime.src The ctime function converts the calendar time (pointed to by timer and represented as a value of type time_t) to a string.0 */ ctime Syntax Calendar Time #include <time.2.h header declares.13.h> char *ctime(time_t *timer).13. For more information about the functions and types that the time.c in rts.c in rts. difftime Alphabetical Summary of Runtime-Support Functions cosh Syntax Hyperbolic Cosine #include <math. The sign of the remainder is the same as the sign of numer. long int rem. div_t result = div (i. long denom). the function returns the quotient and the remainder in a structure of type div_t.h> div_t div(int numer. - /* quotient /* remainder */ */ - The ldiv function performs long integer division.c in rts. } div_t. and the magnitude of the resulting quotient is the largest integer less than the magnitude of the algebraic quotient.src Two functions support integer division by returning numer divided by denom. /* quotient /* remainder */ */ If the division produces a remainder. Because ints and longs are equivalent types in TMS320C3x/C4x C. /* result. ldiv_t ldiv(long numer. Defined in Description div. j). The input arguments are long integers. int rem. You can use these functions to get both the quotient and the remainder in a single operation. The structure is defined as follows: typedef struct { long int quot. The div function performs integer division.rem == –1 */ Runtime-Support Functions 5-35 . The structure is defined as follows: typedef struct { int quot. } ldiv_t. Example int i = –10 int j = 3. these functions are also equivalent.Alphabetical Summary of Runtime-Support Functions div/ldiv div/ldiv Syntax Division #include <stdlib. long denom). the sign of the quotient is the same as the algebraic quotient. The input arguments are integers.quot == –3 */ /* result. the function returns the quotient and the remainder in a structure of type ldiv_t. Defined in Description exp. fabs Alphabetical Summary of Runtime-Support Functions exit Syntax Normal Termination #include <stdlib. /* y = 7. /* return value = +57.5. y = exp(x).src The exit function terminates a program normally.h> void exit(int status). which is e**2 */ fabs Syntax Absolute Value #include <math.h> double exp(double x).5 */ 5-36 . Example x = 2. A range error occurs if the magnitude of x is too large.c in rts. All functions registered by the atexit function are called in reverse order of their registration.src The fabs function returns the absolute value of a floating-point number x. Defined in Description exit.c in rts. double x.h> double fabs(double x). Defined in Description Example fabs. 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. Note that the exit function cannot return to its caller. The return value is the number e raised to the power x.38905. double x.0.src The exp function returns the exponential function of x. exp. exp Syntax Exponential #include <math. y. x = –57. y = fabs(x). The fabs function is expanded inline unless the –x0 option is used.exit.c in rts. y. fflush Syntax Flush I/O Buffer #include <stdio. feof Syntax Test EOF Indicator #include <stdio. Defined in Description feof.src Flushes the I/O buffer for a stream. The stream is pointed to by p. Runtime-Support Functions 5-37 .h> int ferror(FILE *p). The stream is pointed to by p.Alphabetical Summary of Runtime-Support Functions fclose.src Tests the EOF indicator for a stream.c in rts. When the stream is flushed. feof.src Flushes the stream that iop points to.c in rts.h> int fflush(register FILE *iop).h> int fclose(FILE *iop). Defined in Description fflush.c in rts. the function closes the file associated with the stream.c in rts.h> int feof(FILE *p). The stream is pointed to by iop. ferror. fflush fclose Syntax Close File #include <stdio. Defined in Description ferror. Defined in Description fclose.src Tests the error indicator for a stream. ferror Syntax Test Error Indicator #include <stdio. Defined in Description fgetpos.c in rts.src Stores the object pointed to by pos. The object is stored to the current value of the file position indicator for the stream pointed to by iop. Defined in Description fgetc. the stream is pointed to by fp.h> int fgetpos(FILE *iop.h> int fgetc(register FILE *fp).src Reads the next character in a stream. 5-38 . fgetpos Syntax Store Object #include <stdio. fgets Syntax Read Next Characters #include <stdio. register FILE *iop).c in rts. register int size.src Reads the specified number of characters from the stream pointed to by iop. fgets Alphabetical Summary of Runtime-Support Functions fgetc Syntax Read Next Character #include <stdio. The number of characters read is size –1. fpos_t *pos). The characters are placed in the array named by ptr.h> char *fgets(char *ptr. fgetpos.c in rts. Defined in Description fgets.fgetc. Runtime-Support Functions 5-39 .0 */ /* answer = –4.0 */ fmod Syntax Floating-Point Remainder #include <math.c in rts.5). r. /* fmod returns 1. y = 5.c in rts. fopen floor Syntax Floor #include <math. Defined in Description fopen.Alphabetical Summary of Runtime-Support Functions floor.h> double floor(double x). /* answer = 3.0. The floor function is expanded inline if the –x option is used. const char *mode). Example answer = floor(3.1415). How to open the file is described by a string pointed to by mode.0. Example x = 11.src The floor function returns a floating-point number that represents the largest integer less than or equal to x. Defined in Description fmod.h> FILE *fopen(const char *file. the function returns 0. double answer. answer = floor(–3.src The fmod function returns the remainder after dividing x by y an integral number of times.c in rts.h> double fmod(double x.src Opens the file that file points to. y). Defined in Description floor. double y). y. If y==0. fmod. r = fmod(x.0 */ fopen Syntax Open File #include <stdio. double x. fprintf.src Writes a character to a stream. . FILE *iop). The stream is pointed to by iop. The size of the objects is size. fputs..c in rts. Defined in Description fputc. Defined in Description fprintf. Defined in Description fputs.. size_t count. size_t size.src Reads from the stream pointed to by iop. 5-40 .h> int fprintf(FILE *iop.c in rts. const char *format. How to write the stream is described by a string pointed to by format.c in rts. fread Syntax Read Stream #include <stdio.src Writes to the stream pointed to by iop. The number of objects read is count.src Writes the string pointed to by ptr to a stream.).h> int fputs(const char *ptr. Stores the input in the array pointed to by ptr.h> int fputc(int c. fputs Syntax Write String #include <stdio. register FILE *iop). fputc Syntax Write Character #include <stdio. Defined in Description fread. fread Alphabetical Summary of Runtime-Support Functions fprintf Syntax Write Stream #include <stdio. fputc.h> size_t fread(void *ptr. register FILE *fp).c in rts. The stream is pointed to by fp. Runtime-Support Functions 5-41 .src The free function deallocates memory space (pointed to by ptr) that was previously allocated by a malloc. Defined in Description fopen. /* /* allocate 10 bytes free 10 bytes */ */ freopen Syntax Open File #include <stdio.h> void free(void *ptr). Example This example allocates 10 bytes and then frees them.Alphabetical Summary of Runtime-Support Functions free. the function takes no action and returns. char *x. on page 4-4.c in rts. calloc.h> FILE *freopen(const char *file. If you attempt to free unallocated space. The functions free8 and free16 are analogous to the 32-bit version. free(x). For more information. This makes the memory space available again. How to open the file is described by a string pointed to by mode. For the TMS320C32 processor. register FILE *iop).1. x = malloc(10). Defined in Description memory. and associates with it the stream pointed to by iop. 8-bit and 16-bit versions of the free function are provided.c in rts. void free16(void *_ptr). Dynamic Memory Allocation.src Opens the file pointed to by file. freopen free Syntax Deallocate Memory #include <stdlib. or realloc call.3. const char *mode. void free8(void *_ptr). refer to subsection 4. int exp. fscanf.frexp.c in rts. Defined in Description fseek.75 and exp is 2 */ fscanf Syntax Read Stream #include <stdio. For a binary file. fseek Alphabetical Summary of Runtime-Support Functions frexp Syntax Fraction and Exponent #include <math. If value is 0. The position is specified by ptr. Example fraction = frexp(3.).. How to read the stream is described by a string pointed to by format. use offset to position the indicator from ptr.h> int fscanf(FILE *iop. For a text file. Defined in Description fscanf. fseek Syntax Set File Position Indicator #include <stdio. int *exp). offset must be 0. int ptr). The frexp function stores the power in the int pointed to by exp. &exp). fraction is .src The frexp function breaks a floating-point number into a normalized fraction and an integer power of 2.c in rts. with a magnitude in the range [1/2.src Reads from the stream pointed to by iop..src Sets the file position indicator for the stream pointed to by iop. long offset. The function returns a number x.asm in rts. so that value == x × 2exp. 5-42 .0.h> int fseek(register FILE *iop. double fraction.1) or 0. Defined in Description frexp30. /* after execution. const char *format.h> double frexp(double value. . both parts of the result are 0. Alphabetical Summary of Runtime-Support Functions fsetpos. Defined in Description ftell. fwrite. The stream is pointed to by iop.h> int getc(FILE *p).src Writes a block of data from the memory pointed to by ptr to a stream. Runtime-Support Functions 5-43 . getc fsetpos Syntax Set File Position Indicator #include <stdio. size_t size.c in rts. fwrite Syntax Write Block of Data #include <stdio. The stream is pointed to by iop.src Sets the file position indicator for the stream pointed to by iop to pos. ftell Syntax Get Current File Position Indicator #include <stdio.src Reads the next character in a file. The pointer pos must be a value from fgetpos() on the same stream.c in rts.h> long ftell(FILE *iop). ftell. The file is pointed to by p.src Gets the current value of the file position indicator for a stream.c in rts.h> size_t fwrite(const void *ptr. getc Syntax Read Next Character #include <stdio. Defined in Description fgetc. register FILE *iop). Defined in Description fsetpos. const fpos_t *pos).h> int fsetpos(FILE *iop.c in rts. size_t count. Defined in Description fwrite. Defined in Description fgetc. The adjustment from local time to GMT is dependent on the local time zone.h> struct tm *gmtime(time_t *timer).h> int getchar(void). The current time zone is represented by a structure called _tz.src Reads the next character from the standard input device. Change this structure for the appropriate time zone. getenv Syntax Get Environment Information #include <stdlib. getenv.src The gmtime function converts a local time pointed to by timer into Greenwich Mean Time (represented as a broken-down time). gmtime Alphabetical Summary of Runtime-Support Functions getchar Syntax Read Next Character From Standard Input #include <stdio.getchar.h header declares.src Returns the environment information associated with name. gets Syntax Read Next From Standard Input #include <stdio. gmtime Syntax Greenwich Mean Time #include <time. defined in tmzone. page 5-11.h> char *getenv(const char *name).c.h> char *gets(char *ptr). refer to subsection 5.2. Defined in Description lddrv. gets.c in rts. Defined in Description gmtime. The characters are placed in the array named by ptr.c in rts.src Reads an input line from the standard input device. 5-44 . Defined in Description fgets.13.c in rts. For more information about the functions and types that the time.c in rts. of type struct tmzone. numeric. identifies numeric characters between 0 and 9 (inclusive). All of the charactertyping functions are expanded inline if the –x option is used. int islower(char c). carriage return.c in rts. the macros execute more efficiently than the functions.h as macros These functions test a single argument c to see if it is a particular type of character —alphabetic. int isxdigit(char c). identifies ASCII spacebar. identifies ASCII characters (any character from 0–127). and new line characters. identifies lowercase alphabetic ASCII characters. If the test is true (the character is the type of character that it was tested to be). int isprint(char c). alphanumeric. In general. The charactertyping functions include: isalnum isalpha isascii iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit identifies alphanumeric ASCII characters (tests for any character for which isalpha or isdigit is true). tab (horizontal or vertical). int iscntrl(char c). identifies uppercase ASCII alphabetic characters. a–f. A–F). identifies control characters (ASCII characters 0–31 and 127). etc. Runtime-Support Functions 5-45 . including spaces (ASCII characters 32–126). int ispunct(char c).c and ctype. int isupper(char c). int isascii(char c). int isspace(char c). ASCII. Defined in isxxx. identifies any non-space character.Alphabetical Summary of Runtime-Support Functions isxxx isxxx Syntax Character Typing #include <ctype. The macros have the same names as the functions but are prefixed with an underscore. identifies printable ASCII characters. if the test is false.src Also defined in ctype. for example. _isascii is the macro equivalent of the isascii function. the function returns a nonzero value. int isdigit(char c). int isgraph(char c). identifies ASCII punctuation characters. identifies alphabetic ASCII characters (tests for any character for which islower or isupper is true). int isalpha(char c). form feed. Description The C compiler also supports a set of macros that perform these same functions. the function returns 0.h> int isalnum(char c). identifies hexadecimal digits (0–9. h header declares.0 */ . The function returns a pointer to the structure representing the converted time.718282. result = ldexp(6.ldexp.c in rts. float x.src The ldexp function multiplies a floating-point number x by a power of 2 given by exp and returns x × 2exp. 5-46 /* Return value = 1. A range error may occur if the result is too large. Defined in Description localtime.75 */ localtime Syntax Local Time #include <time. The exponent (exp) can be a negative or a positive value.0 */ /* result is 0.asm in rts. int exp). 5).c in rts. log Syntax Natural Logarithm #include <math. –3).0. y. /* result is 48. x = 2. localtime.h> struct tm *localtime(time_t *timer). log Alphabetical Summary of Runtime-Support Functions ldexp Syntax Multiply by a Power of Two #include <math.h> double log(double x). double result.13.h> double ldexp(double x. Defined in Description Example log.src The localtime function converts a calendar time represented as a value of type time_t into a broken-down time in a structure.src The log function returns the natural logarithm of a real number x. For more information about the functions and types that the time. A domain error occurs if x is negative. refer to subsection 5.5.2. page 5-11. a range error occurs if x is 0. Example result = ldexp(1. Defined in Description ldexp30. y = log(x). src The ltoa function converts a long integer n to the equivalent ASCII string and writes it into buffer with a null terminator. a range error occurs if x is 0.Alphabetical Summary of Runtime-Support Functions log10. A domain error occurs if x is negative. char *buffer). s = ”–92993”*/ Example Runtime-Support Functions 5-47 . i = ltoa (–92993L. /* i = 6. a leading minus sign is output.h> double log10(double x). not including the terminator. /* Return value = 1. int i. ltoa log10 Syntax Common Logarithm #include <math. y = log(x). Defined in Description ltoa.h> int ltoa(long n. float x. The ltoa function returns the number of characters placed in the buffer. char s[10].c in rts. y. Defined in Description log10.src The log10 function returns the base-10 logarithm (or common logarithm) of a real number x. If the input number n is negative.0.0 */ ltoa Syntax Convert Long Integer to ASCII #include <stdlib.c in rts. s). Example x = 10. defined in an uninitialized named section called . respectively. Defined in Description memory. For more information. 5-48 . however. p = malloc (sizeof (struct xyz)). It will create a section of the default size (1K of 8-bit or 16-bit words) when the malloc8 and malloc16 functions are used and the –heap8 and –heap16 options are not.c in rts. struct xyz *p.sysmem in memory. if it runs out of memory).malloc Alphabetical Summary of Runtime-Support Functions malloc Syntax Allocate Memory #include <stdlib. memory is allocated from the uninitialized sections .sysm8 and . void *malloc8(size_t _size).sysm8 or . This function does not modify the memory it allocates. void *malloc16(size_t _size). Dynamic Memory Allocation.h> void *malloc(size_t size).1. The functions malloc8 and malloc16 are analogous to malloc. Default heap size is 1K words. on page 4-4. If malloc cannot allocate the packet (that is. it returns a null pointer (0). The linker creates a .3. The linker sets the size of this section from the value specified by the –heap option.sysm16 section when a size is specified using the –heap8 or –heap16 option.src The malloc function allocates space for an object of size bytes and returns a pointer to the space. refer to subsection 4.sysm16. 8-bit and 16-bit versions of the malloc function are provided. Example This example allocates free space for a structure. For the TMS320C32 processor.c. The memory that malloc uses is in a special memory pool or heap. memcpy Syntax Memory Block Copy — Nonoverlapping #include <string.Alphabetical Summary of Runtime-Support Functions memchr. The memchr function is similar to strchr.c in rts. size_t n).c in rts.h> int memcmp(void *s1. if *s1 is greater than *s2. except that the objects that memcmp compares can contain values of 0. memcmp. void *s2.h> void *memchr(void *s. The function returns one of the following values: < > 0 0 0 if *s1 is less than *s2. Runtime-Support Functions 5-49 . size_t n). Defined in Description memcpy.c in rts. The function returns the value of s1. Defined in Description memchr. size_t n). char c.src The memcmp function compares the first n characters of the object that s2 points to with the object that s1 points to. memchr returns a pointer to the located character. and c can be 0. The memcpy function is expanded inline when the –x option is used. it returns a null pointer (0). memcmp Syntax Memory Compare #include <string. if *s1 is equal to *s2. The memcpy function is similar to strncpy. except that the object that memchr searches can contain values of 0. void *s2. except that the objects that memcpy copies can contain values of 0. memcpy memchr Syntax Find First Occurrence of Byte #include <string.src The memcpy function copies n characters from the object that s2 points to into the object that s1 points to. The memcmp function is similar to strncmp. Defined in Description memcmp. The memcmp function is expanded inline when the –x option is used. the function’s behavior is undefined.src The memchr function finds the first occurrence of c in the first n characters of the object that s points to. If the character is found. otherwise. If you attempt to copy characters of overlapping objects.h> void *memcpy(void *s1. The memchr function is expanded inline when the –x option is used. void *s2. memset Alphabetical Summary of Runtime-Support Functions memmove Syntax Memory Block Copy — Overlapping #include <string. The function returns the value of s. int c. The memmove function correctly copies characters between overlapping objects. Defined in Description memset. memset Syntax Duplicate Value in Memory #include <string. size_t n). the function returns the value of s1.memmove.src The memset function copies the value of c into the first n characters of the object that s points to.c in rts.c in rts. 5-50 . The memset function is expanded inline when the –x option is used.h> void *memmove(void *s1. size_t n). Defined in Description memmove.src The memmove function moves n characters from the object that s2 points to into the object that s1 points to.h> void *memset(void *s. For more information.src The minit function resets all the space that was previously allocated by calls to the malloc. 8-bit and 16-bit versions of the minit function are provided.c in rts.sysm16 section when a size is specified using the –heap8 or –heap16 option. Dynamic Memory Allocation. Runtime-Support Functions 5-51 . The linker sets the size of this section from the value specified by the –heap option. Default heap size is 1K words. refer to subsection 4. defined in an uninitialized named section called . Any objects that you allocated previously will be lost.c.1.Alphabetical Summary of Runtime-Support Functions minit minit Syntax Reset Dynamic Memory Pool #include <stdlib. Defined in Description memory. respectively.3.sysm8 and .h> void minit(void). Note: Accessing Objects After Calling the minit Function Calling the minit function makes all the memory space in the heap available again. memory is allocated from the uninitialized sections . void minit16(void). The linker creates a . For the TMS320C32 processor.sysm16. or realloc functions. however. calloc. The functions minit8 and minit16 are analogous to the 32-bit version. do not try to access them.sysm8 or . on page 4-4. The memory that minit uses is in a special memory pool or heap.sysmem in memory. void minit8(void). h> static const char *const wday[] = { ”Sunday”.tm_year time_str.tm_isdst mktime(&time_str). 1. struct tm time_str. into a time value of type time_t. The return value is encoded as a value of type time_t. 0. ”Wednesday”.tm_min time_str. 5-52 .c in rts.tm_sec time_str. ”Thursday”.13. 7. 0. on page 5-11. the function returns the value –1. ”Friday”. 1.tm_hour time_str. 2001 falls on.2.src The mktime function converts a broken-down time. expressed as local time. After successful completion of time conversions.tm_mon time_str. The function ignores the original values of tm_wday and tm_yday and does not restrict the other values in the structure. tm_wday and tm_yday are set appropriately. ”Monday”.mktime Alphabetical Summary of Runtime-Support Functions mktime Syntax Convert to Calendar Time #include <time. 4. For more information about the functions and types that the time.h header declares. Example This example determines the day of the week that July 4. wday[time_str. time_str. ”Tuesday”. and the other components in the structure have values within the restricted ranges. = = = = = = = 2001 – 1900. #include <time. /* After calling this function.h> time_t *mktime(struct tm *timeptr). ”Saturday” }. refer to subsection 5. If the calendar time cannot be represented.tm_wday contains the day of the week for July 4. 2001 */ printf (”result is %s\n”. The timeptr argument points to a structure that holds the broken-down time.tm_mday time_str. time_str. Defined in Description mktime. The final value of tm_mday is not sent until tm_mon and tm_year are determined.tm_wday]). 0.src Maps the error number in s to a string.asm in rts. */ perror Syntax Map Error Number #include <stdio. perror modf Syntax Signed Integer and Fraction #include <math.1415. Each of the two parts has the same sign as the input argument.1415.h> void perror(const char *s).Alphabetical Summary of Runtime-Support Functions modf. &ipart). double *iptr). fpart = modf(value. Defined in Description modf30. The function then prints the error message. ipart. fpart. /* After execution.c in rts. Example value = –3. ipart contains –3. The function returns the fractional part of value and stores the integer part as a double at the object pointed to by iptr.h> double modf(double value. Defined in Description perror. Runtime-Support Functions 5-53 .src The modf function breaks a value into a signed integer and a signed fraction. */ /* and fpart contains –0. double value. h> double pow(double x. Defined in Description printf.src Writes a character to a stream.). putc Syntax Write Character #include <stdio. y. . z = pow(x. y = 3. Example x = 2. double x.c in rts.src Writes to the standard output device. 5-54 . A range error may occur if the result is too large to represent.0 */ printf Syntax Write to Standard Output #include <stdio. printf.src The pow function returns x raised to the power y.h> int putc(int x. Defined in Description fputc.c in rts.. The stream is pointed to by p.0. FILE *p).0..c in rts.h> int printf(const char *format. putc Alphabetical Summary of Runtime-Support Functions pow Syntax Raise to a Power #include <math. double y). or if x is negative and y is not an integer. /* return value = 8. A domain error occurs if x = 0 and y ≤ 0. How to write the stream is described by a string pointed to by format. z. Defined in Description pow.pow. y). Runtime-Support Functions 5-55 .Alphabetical Summary of Runtime-Support Functions putchar. The string is pointed to by ptr. puts putchar Syntax Write Character to Standard Output #include <stdlib. puts Syntax Write to Standard Output #include <stdlib.src Writes a character to the standard output device. Defined in Description fputs. Defined in Description fputc.src Writes a string to the standard output device.h> int putchar(int x).h> int puts(const char *ptr).c in rts.c in rts. argument size specifies the size of each member. 1. The comparison function should be declared as: int cmp(void *ptr1. Example In the following example. Argument compar points to a function that compares key to the array elements. const void *i2) { return *(int *)i1 – *(int *)i2. 1. Defined in Description qsort. void *ptr2). list[ ]= ={ 1. int (*compar) (void)).h> int list[ ] = {3. The array sort will not work correctly if the CMP function fails to return the correct values for all three conditions.src The qsort function sorts an array of n members. /* after sorting. int idiff (const void *.qsort Alphabetical Summary of Runtime-Support Functions qsort Syntax Array Sort #include <stdlib. main( ) { qsort (list. 8. 1. 9} */ } int idiff (const void *i1. } 5-56 . 9. 2. Argument base points to the first member of the unsorted array. size_t n. 6. if *ptr1 is equal to *ptr2. 1. idiff).h> void qsort(void *base.c in rts. The cmp function compares the objects that ptr1 and ptr2 point to and returns one of the following values: < > 0 0 0 if *ptr1 is less than *ptr2. This function sorts the array in ascending order. 4. size_t size. 3. if *ptr1 is greater than *ptr2. 6}. 5. 5. a short list of integers is sorted with qsort. #include <stdlib. const void *). 2. 4. realloc behaves like malloc. void *realloc16(void *_ptr. The srand function sets the value of the random number generator seed so that a subsequent call to the rand function produces a new sequence of pseudorandom numbers. If you call rand before calling srand. size_t size). and realloc returns 0.Alphabetical Summary of Runtime-Support Functions rand/srand. the original memory space is not changed. realloc rand/srand Syntax Random Integer #include <stdlib. to the size specified in bytes by size.src The realloc function changes the size of the allocated memory pointed to by ptr. void srand(unsigned int seed). For the TMS320C3x/C4x C compiler. - If ptr is 0.c in rts. rand generates the same sequence it would produce if you first called srand with a seed value of 1. If size = 0 and ptr is not null.c in rts. Defined in Description memory. rand generates the same sequence of numbers.h> void *realloc(void *ptr. The contents of the memory space (up to the lesser of the old and new sizes) is not changed. Defined in Description rand. The srand function does not return a value. Runtime-Support Functions 5-57 . size_t _size). If ptr points to unallocated space. void *realloc8(void *_ptr. realloc Syntax Change Heap Size #include <stdlib.src Two functions work together to provide pseudorandom sequence generation: - The rand function returns pseudorandom integers in the range 0—RAND_MAX.h> int rand(void). the value of RAND_MAX is 2147483646 (231 –2). If you call srand with the same seed value. the function takes no action and returns. If the space cannot be allocated. size_t _size). realloc frees the space that ptr points to. c. on page 4-4. refer to subsection 4. respectively. in order to allocate more space. It will create a section of the default size (1K of 8-bit or 16-bit words) when the realloc8 and realloc16 functions are used and the –heap8 and –heap16 options are not. The functions realloc8 and realloc16 are analogous to realloc. Defined in Description lowlev. memory is allocated from the uninitialized sections . rename Alphabetical Summary of Runtime-Support Functions If.c in rts. Default heap size is 1K words. The memory that realloc uses is in a special memory pool or heap. the function returns a null pointer (0).src Renames the file pointed to by old.sysm8 and .3. The linker sets the size of this section from the value specified by the –heap option. defined in an uninitialized named section called .sysmem in memory.remove. remove Syntax Remove File #include <stdio.src Makes the file pointed to no longer available by that name.c in rts. The new name is pointed to by new. 8-bit and 16-bit versions of the realloc function are provided. realloc returns a pointer to the new space. 5-58 .sysm16.sysm8 or . Any memory freed by this operation is deallocated.1.h> int rename(const char *old. Dynamic Memory Allocation. For the TMS320C32 processor. If an error occurs. the entire object must be moved. const char *new). however.h> int remove(const char *file). For more information. The file is pointed to by file. Defined in Description remove. rename Syntax Rename File #include <stdio. The linker creates a .sysm16 section when a size is specified using the –heap8 or –heap16 option. The file is pointed to by iop.Alphabetical Summary of Runtime-Support Functions rewind.. How to read the stream is described by a string pointed to by format.). setbuf rewind Syntax Position File Position Indicator to Beginning of File #include <stdio. Defined in Description fscanf.src Specifies the buffer used by the stream pointed to by iop.h> int scanf(const char *format. char *buf). Runtime-Support Functions 5-59 .c in rts.c in rts.h> void rewind(register FILE *iop)..c in rts.h> void setbuf(register FILE *iop. Defined in Description rewind. No value is returned.src Sets the file position indicator for a stream to the beginning of the file. Defined in Description setbuf. If buf is set to null. .src Reads from the stream from the standard input device. scanf Syntax Read Stream From Standard Input #include <stdio. setbuf Syntax Specify Buffer for Stream #include <stdio. buffering is turned off. scanf. .h header defines one type. The setjmp macro saves its calling environment in the jmp_buf argument for later use by the longjmp function. the setjmp macro returns the value zero. or if it terminated execution irregularly. nest42() { if (input() == ERRCODE42) /* return to setjmp call in main */ longjmp (env. Defined in Description setjmp. . } . If the return is from a call to the longjmp function. the setjmp macro returns the value 1. If returnval is zero. } 5-60 . If the setjmp macro was not invoked. After longjmp is completed. The longjmp function will not cause setjmp to return a value of zero even if returnval is zero. the setjmp macro returns a nonzero value.h> jmp_buf env. one macro. int returnval). The longjmp function restores the environment that was saved in the jmp_buf argument by the most recent invocation of the setjmp macro. . . if ((errcode = setjmp(env)) == 0) nest1(). and one 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.asm in rts. the behavior of longjmp is undefined. void longjmp(jmp_buf env. . else switch (errcode) . main() { int errcode. Example These functions are typically used to effect an immediate return from a deeply nested function call: #include <setjmp.h> int setjmp(jmp_buf env).src The setjmp. . ERRCODE42). .setjmp/longjmp Alphabetical Summary of Runtime-Support Functions setjmp/longjmp Syntax Nonlocal Jumps #include <setjmp. the program execution continues as if the corresponding invocation of setjmp had just returned returnval. If the return is from a direct invocation. h> int setvbuf(register FILE *iop. If buf is set to null. register int type. The type parameter specifies the type of buffering as follows: _IOFBF _IOLBF _IONBF Full buffering occurs Line buffering occurs No buffering occurs sin Syntax Sine #include <math. radian = 3.h> double sin(double x). register size t_size). Defined in Description setbuf. An argument with a large magnitude may produce a result with little or no significance.0 */ Runtime-Support Functions 5-61 . The t_size parameter specifies the size of the buffer. If buf names a buffer. a buffer is allocated. x is an angle expressed in radians.1415927. double radian. /* sval is returned by sin */ Example /* sin returns –1.src The sin function returns the sine of a floating-point number x.src Defines and associates the buffer used by the stream pointed to by iop. Defined in Description sin.c in rts. sval. register char *buf. sval = sin(radian).c in rts. sin setvbuf Syntax Define and Associate Buffer With Stream #include <stdio. that buffer is used for the stream.Alphabetical Summary of Runtime-Support Functions setvbuf. src The sqrt function returns the non-negative square root of a real number x. double x. Defined in Description sinh.. sqrt Alphabetical Summary of Runtime-Support Functions sinh Syntax Hyperbolic Sine #include <math. A domain error occurs if the argument is negative. A range error occurs if the magnitude of the argument is too large.h> int sprintf(char *string.sinh. Example x = 100.h> double sqrt(double x). Defined in Description sprintf. const char *format.c in rts. Defined in Description sqrt30. Example x = 0.).h> double sinh(double x). double x. y.src The sinh function returns the hyperbolic sine of a floating-point number x.. y = sinh(x). How to write the stream is described by a string pointed to by format. sqrt Syntax Square Root #include <math. /* return value = 0.0.c in rts.src Writes to the array pointed to by string. y = sqrt(x).0 */ sprintf Syntax Write Stream #include <stdio. .0. /* return value = 10.0 */ 5-62 . sprintf. y.asm in rts. /* a ––> ”The quick black fox jumps over the lazy dog. the notation “\0” represents the null character: char *a. . How to read the stream is described by a string pointed to by format.h> char *strcat(char *s1. In the comments.).. strcat Syntax Concatenate Strings #include <string..c in rts. The strcat function is expanded inline if the –x option is used.Alphabetical Summary of Runtime-Support Functions sscanf. . *c.c). the character strings pointed to by a. In the following example. Defined in Description strcat.c in rts. /* a ––> ”The quick black fox\0” /* b ––> ” jumps over \0” /* c ––> ”the lazy dog. and c were assigned to point to the strings shown in the comments. .src The strcat function appends a copy of s2 (including the terminating null character) to the end of s1. b. .src Reads from the string pointed to by str. strcat sscanf Syntax Read Stream #include <stdio. /* a ––> ”The quick black fox jumps over \0” strcat (a.b). *b. const char *format.h> int sscanf(const char *str.\0” strcat (a.\0”*/ */ */ */ */ Example Runtime-Support Functions 5-63 . The initial character of s2 overwrites the null character that originally terminated s1. char *s2). The function returns the value of s1. Defined in Description sscanf. b points to the first z in zz. it returns a pointer to the character. strcmp/strcoll Syntax String Compare #include <string. Defined in Description strcmp. char *strc = ”why ask why”. char *a = ”When zz comes home. The functions are equivalent. both functions are supported to provide compatibility with ANSI C. the search is on for z’s. The functions return one of the following values: < > 0 0 0 if *s1 is less than *s2. if *s1 is greater than *s2. if (strcmp(stra. strb) > 0) { /* statements here will be executed */ } if (strcoll(stra. it returns a null pointer (0).src The strchr function finds the first occurrence of c in s. char *b.strchr. int strcoll( char *s1. The strcmp function is expanded inline if the –x option is used. otherwise. char *strb = ”just do it”. Defined in Description strchr. char *s2). char the_z = ’z’. After this example. if *s1 is equal to *s2.”. char *s2).the_z). char c). Example char *stra = ”why ask why”. strc) == 0) { /* statements here will be executed also */ } 5-64 . strcmp/strcoll Alphabetical Summary of Runtime-Support Functions strchr Syntax Find First Occurrence of a Character #include <string.c in rts. The strchr function is expanded inline if the –x option is used.c in rts. If strchr finds the character. Example b = strchr(a.h> char *strchr(char *s.src The strcmp and strcoll functions compare s2 with s1.h> int strcmp(char *s1. /* length = 0 */ /* length = 9 */ Runtime-Support Functions 5-65 . length = strcspn(stra. the notation “\0” represents the null character: char *a = ”The quick black fox”. char *strc = ”abcdefg”. If you attempt to copy strings that overlap. size_t length. char *b = ” jumps over ”. In the following example. which is made up entirely of characters that are not in s2. the strings pointed to by a and b are two separate and distinct memory locations. Example length = strcspn(stra.h> char *strcpy(char *s1.h> size_t strcspn(char *s1.strb).c in rts. char *s2). Defined in Description strcspn. If the first character in s1 is in s2.Alphabetical Summary of Runtime-Support Functions strcpy. the function’s behavior is undefined.b). /* a ––> ”The quick black fox\0” /* b ––> ” jumps over \0” strcpy(a. In the comments.src The strcpy function copies s2 (including the terminating null character) into s1. char *strb = ”abcdefghijklmnopqrstuvwxyz”.c in rts. strcspn strcpy Syntax String Copy #include <string. The strcpy function is expanded inline if the –x option is used.src The strcspn function returns the length of the initial segment of s1.strc). The function returns a pointer to s1. /* a ––> ” jumps over \0” /* b ––> ” jumps over \0” */ */ */ */ Example strcspn Syntax Find Number of Unmatching Characters #include <string. char *stra = ”who is there?”. Defined in Description strcpy. the function returns 0. char *s2). . Feb.M. size_t maxsize. or P. the abbreviated month name (Jan. . The format parameter is a string of characters that tells the strftime function how to format the time. %a %A %b %B %c %d %H %I %j %m %M %p %S %U the abbreviated weekday name (Mon.. Tue.src The strerror function returns the string error.h> size_t *strftime(char *s. . ) the locale’s full month name the date and time representation the day of the month as a decimal number (0–31) the hour (24-hour clock) as a decimal number (00–23) the hour (12-hour clock) as a decimal number (01–12) the day of the year as a decimal number (001–366) the month as a decimal number (01–12) the minute as a decimal number (00–59) the locale’s equivalent of either A. . Character is replaced by . Up to maxsize characters can be written to s. ) the full weekday name. Defined in Description strftime. . strftime Alphabetical Summary of Runtime-Support Functions strerror Syntax String Error #include <string. Defined in Description strerror. strftime Syntax Format Time #include <time. .src The strftime function formats a time (pointed to by timeptr) according to a format string and returns the formatted result in the string s. struct tm *timeptr). The following list shows the valid characters and describes what each character expands to.strerror. This function is supplied to provide ANSI compatibility.M.c in rts. char *format. .c in rts.h> char *strerror(int errnum). the second as a decimal number (00–50) the week number of the year (Sunday is the first day of the week) as a decimal number (00–52) 5-66 . or by no characters if no time zone exists For more information about the functions and types that the time. length = strlen(strb). In C.h header declares. The strlen function is expanded inline if the –x option is used. page 5-11.Alphabetical Summary of Runtime-Support Functions strlen %x %X %y %Y %Z 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. char *strc = ”abcdefg”. size_t length. length = strlen(strc).h> size_t strlen(char *s). refer to subsection 5. The returned result does not include the terminating null character. Example length = strlen(stra).c in rts. a character string is terminated by the first byte with a value of 0 (a null character).13. strlen Syntax Find String Length #include <string.2.src The strlen function returns the length of s. char *strb = ”abcdefghijklmnopqrstuvwxyz”. char *stra = ”who is there?”. /* length = 13 */ /* length = 26 */ /* length = 7 */ Runtime-Support Functions 5-67 . Defined in Description strlen. b. */. The function returns the value of s1. /* a––> ”I do not like them. the character strings pointed to by a.c in rts. char *s2. . the notation “\0” represents the null character: char *a.size). strncat. Sam I am. The initial character of s2 overwrites the null character that originally terminated s1.src The strncat function appends up to n characters of s2 (including the terminating null character) to the end of s1. *b. and c were assigned the values shown in the comments. b. size_t size = 13. strncat appends a null character to the result. Sam I am.\0” */. /* c––> ”I do not like green eggs and ham\0” */.h> char *strncat(char *s1. strncat (a. *c. . \0” strncat (a. .strncat Alphabetical Summary of Runtime-Support Functions strncat Syntax Defined in Description Concatenate Strings #include <string.c. /* a––> ”I do not like them. \0” */. I do not like\0” */. In the comments. size_t n). /* b––> ” Sam I am.size). In the following example. Example 5-68 . /* a––> ”I do not like them. h> int strncmp(char *s1. Defined in Description strncmp. strb. char *strb = ”just do it”. Example char *stra = ”why ask why”.c in rts. size_t n).Alphabetical Summary of Runtime-Support Functions strncmp strncmp Syntax Compare Strings #include <string. if (strcmp(stra. if *s1 is equal to *s2. size) > 0) { /* statements here will get executed */ } if (strcmp(stra. The function returns one of the following values: < > 0 0 0 if *s1 is less than *s2. char *s2. size_t size = 4. strc. char *strc = ”why not?”.src The strncmp function compares up to n characters of s2 with s1. if *s1 is greater than *s2. size) == 0) { /* statements here will get executed also */ } Runtime-Support Functions 5-69 . */. */.src The strncpy function copies up to n characters from s2 into s1. the function’s behavior is undefined. If s2 is shorter than n characters. If you attempt to copy characters from overlapping strings. strncpy (stra. Note that strb contains a leading space to make it five characters long. */. In the comments.h> char *strncpy(char *s1. size_t length = 5. a space. */.strb. and another space. The function returns the value of s1. */. /* /* /* /* stra––> strb––> strc––> strd––> ”oops\0” ” he’s\0” ”I am the one father warned you of\0” ”oops\0” */. Also note that the first five characters of strc are an “I“. */. */. Defined in Description strncpy. stra begins with the phrase “I am” followed by two spaces. /* /* /* /* stra––> strb––> strc––> strd––> ” he’s the one mother warned you of\0” ” he’s\0” ”I am the one father warned you of\0” ”oops\0” */. */. If s2 is n characters long or longer. 5-70 . the notation “\0” represents the null character.length).length). /* /* /* /* stra––> strb––> strc––> strd––> ”I am the one mother warned you of\0” ” he’s\0” ”I am the one father warned you of\0” ”oops\0” */. char *stra = ”she’s the one mother warned you of”. size_t n). char *s2. char *strd = ”oops”. */. char *strc = ”I am the one father warned you of”.strd. strncpy (stra. strncpy appends null characters to s1 so that s1 contains n characters. so that after the second execution of strncpy.strc.c in rts.strncpy Alphabetical Summary of Runtime-Support Functions strncpy Syntax String Copy #include <string. char *strb = ” he’s”. the word “am”. the null character that terminates s2 is not copied.length). Example strncpy (stra. If strrchr finds the character.c in rts.h> char *strrchr(char *s. b points to the z in zs near the end of the string. strrchr Syntax Find Last Occurrence of a Character #include <string. Runtime-Support Functions 5-71 .the_Z). The strrchr function is expanded inline if the –x option is used. char *stra = ”it wasn’t me”. If strpbrk finds a matching character. otherwise. it returns a null pointer (0). Example a = strpbrk (stra. Example After this example. char *strb = ”wave”. otherwise. char *a = ”When zz comes home. After this example. int c). Defined in Description strrchr.src The strpbrk function locates the first occurrence in s1 of any character in s2. strrchr strpbrk Syntax Find Any Matching Character #include <string.src The strrchr function finds the last occurrence of c in s. the search is on for z’s”.strb).Alphabetical Summary of Runtime-Support Functions strpbrk.h> char *strpbrk(char *s1. Defined in Description strpbrk.c in rts. char *s2). b = strrchr(a. it returns a null pointer (0). it returns a pointer to the character. a points to the “w” in wasn’t. char *b. char *a. char the_z = ’z’. it returns a pointer to that character. strstr returns s1. it returns a null pointer. If strstr finds the matching string.c in rts. If s2 points to a string with length 0. If the first character of s1 is not in s2.c in rts.strspn. char *s2). Defined in Description strspn. the strspn function returns 0. char *strc = ”abcdefg”. char *strb = ”what”.h> char *strstr(char *s1. char *ptr. /* length = 3 */ /* length = 0 */ strstr Syntax Find Matching String #include <string. 5-72 . if it doesn’t find the string. Example length = strcspn(stra.src The strspn function returns the length of the initial segment of s1.strc).h> size_t *strspn(int *s1. it returns a pointer to the located string. strstr Alphabetical Summary of Runtime-Support Functions strspn Syntax Find Number of Matching Characters #include <string. The pointer ptr now points to the “w” in “what” in the first string. char *strb = ”abcdefghijklmnopqrstuvwxyz”.strb). size_t length.strb). length = strcspn(stra.src The strstr function finds the first occurrence of s2 in s1 (excluding the terminating null character). which is entirely made up of characters in s2. Example ptr = strstr(stra. Defined in Description strstr. int *s2). char *stra = ”who is there?”. char *stra = ”so what do you want for nothing?”. the function returns 0. char **endptr. including an optional sign. The first unrecognized character terminates the string. If the converted string causes an overflow or an underflow.src and strtoul. The string must have the following format: [space] [sign] digits [. char **endptr.digits] [e|E [sign] integer] - The function returns the converted string. the function returns +HUGE_VAL. Following the space is an optional sign. Defined in Description strtod.h> double strtod(char *nptr. strtol. unsigned long int strtoul(char *nptr.digits] [e|E [sign] integer] The strtoul function converts a string to an unsigned long integer. the function returns a 0. int base). if the original string is empty or does not have the correct format. If the converted string would cause an overflow. The fractional part of the number follows. then the exponent.c in rts. horizontal or vertical tab. and then digits that represent the integer portion of the number. long int strtol(char *nptr.src. The string must have the following format: [space] [sign] digits [. For each function. The functions that convert to integers also have a third argument. The strtol function converts a string to a long integer. Argument endptr points to a pointer.c in rts. argument nptr points to the original string. carriage return. char **endptr). - The strtod function converts a string to a floating-point value. The string must be specified in the following format: [space] [sign] digits [. The pointer that endptr points to is set to point to this character. which tells the function on which base to interpret the string.Alphabetical Summary of Runtime-Support Functions strtod/strtol/strtoul strtod/strtol/ strtoul Syntax Convert String to Numeric Value #include <stdlib. form feed.c in rts.src Three functions convert ASCII strings to numeric values. errno is set to the value of ERANGE. Runtime-Support Functions 5-73 . if the converted string would cause an underflow. or newline. int base). the functions set this pointer to point to the first character after the converted string. base.digits] [e|E [sign] integer] The space is indicated by one or more of the following characters: space bar. char *stra = ”excuse me while I kiss the sky”.h> size_t strxfrm(char *tostring.strtok. char *s2). The value of s2 can change at each invocation. size_t n). Defined in Description strtok. In the comments. const char *fromstring. The n number of characters pointed to by fromstring are converted into the n characters pointed to by tostring. Each call returns a pointer to the next token.” ”). strxfrm Alphabetical Summary of Runtime-Support Functions strtok Syntax Break String into Token #include <string.src Converts the characters of one string into another string. char *ptr.” ”). the pointer stra points to the string “excuse” because strtok has inserted a null character where the first space used to be.c in rts.” ”). each delimited by a character from s2. /* ptr ––> ”while\0” */ Example strxfrm Syntax Convert Characters #include <string. Defined in Description strxfrm. ptr = strtok (stra. the notation “\0” represents the null character.h> char *strtok(char *s1.c in rts. /* ptr ––> ”excuse\0” */ ptr = strtok (0. Successive calls use a null pointer as the first argument. It is important to note that s1 is altered by the strtok function. After the first invocation of strtok in the example below.src Successive calls to the strtok function break s1 into a series of tokens. /* ptr ––> ”me\0” */ ptr = strtok (0. The first call to strtok uses the string s1. 5-74 . src The tanh function returns the hyperbolic tangent of a floating-point number x. y.0. double x. /* return value = 0. tanh tan Syntax Tangent #include <math.1415927/4.0 */ Runtime-Support Functions 5-75 . y.c in rts. An argument with a large magnitude may produce a result with little or no significance. x = 0. Example x = 3.h> double tanh(double x). Defined in Description tan.0. y = tanh(x). x is an angle expressed in radians.h> double tan(double x). y = tan(x).Alphabetical Summary of Runtime-Support Functions tan. Defined in Description Example tanh.c in rts. /* return value = 1.src The tan function returns the tangent of a floating-point number x. double x.0 */ tanh Syntax Hyperbolic Tangent #include <math. tmpfile.2.c in rts. _toascii. The value is the number of seconds since 12:00 A.c in rts. Defined in Description tmpnam. Defined in Description time. 5-76 .h header declares.src The toascii function ensures that c is a valid ASCII character by masking the lower seven bits. represented as a value of type time_t. the function returns –1.src Creates a temporary file.src Generates a string that is a valid filename.. tmpfile Syntax Create Temporary File #include <stdlib.c in rts. so you must write your own time function.13. 1900.src The time function determines the current calendar time. There is also an equivalent macro. the function also assigns the return value to the object that timer points to.time.M. page 5-11. toascii Syntax Convert to ASCII #include <ctype. refer to subsection 5. toascii Alphabetical Summary of Runtime-Support Functions time Syntax Time #include <time. If timer is not a null pointer.c in rts. Note: Writing Your Own Time Function The time function is target-system specific. tmpnam.h> char *tmpnam(char *s). If the calendar time is not available. Jan 1. Defined in Description toascii. tmpnam Syntax Generate Valid Filename #include <stdlib. For more information about the functions and types that the time. Defined in Description tmpfile.h> int toascii(char c).h> time_t time(time_t *timer).h> FILE *tmpfile(void). Alphabetical Summary of Runtime-Support Functions tolower/toupper. int toupper(char c). tolower returns it unchanged. to upper or lower case: The tolower function converts an uppercase argument to lowercase. The stream is pointed to by p. Description Example The functions have macro equivalents named _tolower and _toupper.h> int tolower(char c).src Two functions convert the case of a single alphabetic character. FILE *p).c in rts.src toupper. Defined in tolower. Runtime-Support Functions 5-77 .src Writes the character c to a stream. ungetc tolower/toupper Syntax Convert Case #include <ctype.c in rts. If c is not an uppercase letter.c in rts. If c is not a lowercase letter. Defined in Description ungetc. toupper returns it unchanged.h> int ungetc(int c. The toupper function converts a lowercase argument to uppercase. tolower (’A’) tolower (’+’) /* returns ’a’ */ /* returns ’+’ */ ungetc Syntax Write Character to Stream #include <stdio. c. Each time you call va_arg. The va_start macro initializes ap to point to the first argument in an argument list for the variable-argument function. called variable-argument functions. stdarg. /* Get next arg. va_end(ap). /* . a string */ long). fmt).. type). } 5-78 int). The va_end macro resets the stack environment after va_start and va_arg are used. it is the type of the current argument in the list. declared list. char* s. s = va_arg(ap. /* Get next arg.h> type void void va_list Defined in Description va_arg(ap. it modifies ap so that successive arguments for the variable-argument function can be returned by successive calls to va_arg (va_arg modifies ap to point to the next argument in the list). The va_arg macro returns the value of the next argument in a call to a variable-argument function.h as macros Some functions can be called with a varying number of arguments that have varying types. *ap. /* Get next arg. - - Note that you must call va_start to initialize ap before calling va_arg or va_end. The ap parameter points to an argument in the variable-argument list.va_arg/va_end/va_start Alphabetical Summary of Runtime-Support Functions va_arg/va_end/ va_start Syntax Variable-Argument Macros/Functions #include <stdarg. va_list ap. The type parameter is a type name. va_end(ap). va_start(ap. i = va_arg(ap. can use the following macros to step through argument lists at runtime. a long */ /* Reset */ . The parmN parameter points to the rightmost parameter in the fixed. va_start(ap..h> int printf(char *fmt. an integer */ char *).) { int i. Such functions.. . parmN).. */ i = va_arg(ap. Example #include<stdarg. How to write the stream is described by a string pointed to by format. vsprintf Syntax Write Stream #include <stdio. Runtime-Support Functions 5-79 . Defined in Description vprintf.c in rts. The ap parameter is the argument list.src Writes to the stream pointed to by iop. vprintf Syntax Write to Standard Output #include <stdio. Defined in Description vsprintf. How to write the stream is described by a string pointed to by format. const char *format. vsprintf vfprintf Syntax Write to Stream #include <stdio.h> int vfprintf(FILE *iop.Alphabetical Summary of Runtime-Support Functions vfprintf.c in rts. va_list ap). vprintf. va_list ap). The ap parameter is the argument list. const char *format. How to write the stream is described by a string pointed to by format. Defined in Description vfprintf.src Writes to the standard output device.src Writes to the array pointed to by string.c in rts. va_list ap). The ap parameter is the argument list.h> int vprintf(const char *format.h> int vsprintf(char *string. Chapter 6 Library-Build Utility When using the TMS320C3x/C4x C compiler, you can compile your code under a number of different configurations and options, which are not necessarily compatible with one another. Since it would be cumbersome to include all possible combinations in individual runtime-support libraries, this package includes the source file, rts.src, that contains all runtime-support functions, and all floating-point support functions. By using the mk30 utility described in this chapter you can custom build your own runtime-support libraries for the options you select. These are the topics covered in this chapter: Topic 6.1 6.2 Page Invoking the Library-Build Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 Options Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4 Library-Build Utility 6-1 Invoking the Library-Build Utility 6.1 Invoking the Library-Build Utility The general syntax for invoking the library utility is: mk30 [options ] src_arch1 [–lobj.lib1 ] [src_arch2 [–lobj.lib2 ]] mk30 is the command that invokes the utility. can appear anywhere on the command line or in a command file. (Options are discussed in Section 6.2 and below.) is the name of a source archive file. For each source archive named, mk30 will build an object library according to the runtime model specified by the command line options. is the optional object library name. If you do not specify a name for the library, mk30 uses the name of the source archive and appends a .lib suffix. For each source archive file specified, a corresponding object library file is created. An object library cannot be built from multiple source archive files. options src_arch –lobj.lib The mk30 utility runs the shell program cl30 on each source file in the archive to either compile or assemble it. It then collects all the object files into the output library. All the tools must be in your PATH. The utility ignores and disables the environment variables TMP, C_OPTION, and C_DIR. Library Utility Specific Options Most of the options that are included on the command line correspond directly to options of the same name used with the compiler and assembler. 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 completed execution. – –h instructs mk30 to use header files contained in the source archive and leave them in the current directory after the utility has completed execution. You will probably want to use this option to install the runtime-support header files from the rts.src archive that is shipped with the tools. instructs the mk30 utility to over-write files. By default, the utility aborts any time it attempts to create an object file when an object file of the same name already exists in the current directory, regardless of whether you specified the name or the utility derived it. instructs mk30 to suppress header information (quiet). – –k ––q 6-2 Invoking the Library-Build Utility – –u instructs mk30 not to use the header files contained in the source archive when building the object library. If the desired headers are already in the current directory, there is no reason to reinstall them. This option also gives you some flexibility in modifying runtime-support functions to suit your application. prints progress information to the screen during execution of the utility. Normally, the utility operates silently (no screen messages). – –v Example: The following command builds the standard runtime support library as an object library named rts40r.lib. The library is compiled for the TMS320C4x (–v40), optimized with inline function expansion (–x and –o), and uses the register-argument runtime conventions. The example assumes that the runtime support headers already exist in the current directory (––u). mk30 – –u –v40 –o –x –mr rts.src –1 rts40r.lib Library-Build Utility 6-3 Options Summary 6.2 Options Summary Options for the mk30 utility correspond directly to the options that the compiler uses. These options are described in detail in subsection 2.1.3 on page 2-5. General Options –g –vxx Parser Options –pk –pw –p? Optimizer Options –o0 –o1 –o2 (or –o) –o3 –ox (equivalent to –x2) Inlining Options Effect symbolic debugging specify processor TMS320Cxx (v30, v32, v40, v44) Effect K&R compatible; compatible with previous C standards suppress warning messages enable trigraph expansion Effect level 0; register optimization level 1; level 0 + local optimization level 2; level 1 + global optimization level 3; level 2 + file optimization defines _INLINE + invokes optimizer at level 2 Effect default inlining level defines _INLINE + invokes optimizer at level 2 Effect assumes aliased variables big memory model fast float to int conversion far pointers avoid RPTS loops runtime support assembly calls use far calls use MPYI for multiply enables optimization disabled by –g perform speed optimizations at cost of increased code size register argument conventions assume all memory accessible when optimizing generate Ada compatible frame structure generate Tartan LAJ–compatible function prolog –x1 –x2 (or –x) Runtime Model Options –ma –mb –mc –mf –mi –ml –mm –mn –mp –mr –ms –mt –mtc 6-4 Options Summary Type Checking Options –tf –tp Assembler Options –as Effect relax prototype checking relax pointer combination checking Effect keep labels as symbols Library-Build Utility 6-5 Appendix A Appendix A Description of Compiler Optimizations The TMS320C3x/C4x C compiler uses a variety of optimization techniques to improve the execution speed of your C programs and to reduce their size. Optimization occurs at various levels throughout the compiler. Most of the optimizations described here are performed by the separate optimizer pass that you enable and control with the –o compiler options. (For details about the –o options, refer to Section 2.4 on page 2-38.) However, the code generator performs some optimizations, particularly the target-specific optimizations, that you cannot selectively enable or disable. This appendix describes two categories of optimizations: general and targetspecific. General optimizations improve any C code, and target-specific optimizations are designed especially for the TMS320C3x/C4x architecture. Both kinds of optimizations are performed throughout the compiler. Some of the examples in this section were compiled with the –v40 option, and some with –v30. The code produced will be slightly different different depending on the version. For example, Example A–1 shows code produced with the –v40 option, so one of its local variables is assigned to register R8 (a register the ’C3x doesn’t have). Unless otherwise noted, the differences between –v30 and –v40 code are minimal. These are the optimizations covered in this appendix: Target-Specific Optimizations Register variables Register tracking/targeting Cost-based register allocation Autoincrement addressing Repeat blocks Parallel instructions Conditional instructions Delayed branches TMS320C4x-specific features General Optimizations Algebraic reordering, symbolic simplification, constant folding Alias disambiguation Copy propagation Common subexpression elimination Redundant assignment elimination Branch optimizations, control-flow simplification, delayed branches Loop induction variable optimizations, strength reduction Loop unrolling Loop rotation Loop invariant code motion Inline function expansion A-1 See Example A–1 and Example A–2. Register variables are particularly effective for pointers. The compiler is designed to make effective use of the registers. - Register variables The compiler helps maximize the use of registers for storing local variables.b) are tracked through both straight-line code and forward branches. Variables stored in registers can be accessed more efficiently than variables in memory. The compiler also uses register targeting to compute expressions directly into specific registers when required. and structure references such as (a. parameters. See Example A–1. for both general computations and in cases where specific registers can be used in specialized ways. constants. - Register tracking/targeting The compiler tracks the contents of registers so that it avoids reloading values if they are used again soon. and temporary values. as in the case of assigning to register variables or returning values from functions. A-2 .Description of Compiler Optimizations Effective register use The TMS320C3x/C4x DSPs have a large and versatile set of registers. Variables. opt30 –r –02 a1.R0. Register Variables and Register Tracking/Targeting int gvar.set AR3 .globl _gvar .if a1.bss _gvar. cg30 –p a1.R2. int j) { gvar = call () & i.globl _reg *********************************************************************** * FUNCTION DEF : _reg * *********************************************************************** _reg: PUSH R4 * * R4 assigned to parameter i * LDI AR2. ac30 –mr a1. } } *********************************************************************** * TMS320C30 C COMPILER Version X.version 30 FP . return j.if . j = gvar + i.@_gvar ADDI R4.R4 CALL _call AND R4.c a1.end Description of Compiler Optimizations A-3 .1 *********************************************************************** * UNDEFINED REFERENCES * *********************************************************************** .opt a1. reg(int i.opt .tmp .globl _call .Description of Compiler Optimizations Example A–1.R0 EPIO_1: POP R4 RETS .XX * *********************************************************************** .asm a1.globl _gvar .R2 STI R2. - Passing arguments in registers The compiler supports a new. the compiler tries to allocate loop counters into RC. For example. or *––p. such as for (i = 0.. the optimizer greatly increases effectiveness because operands are more likely to be in registers. Autoincrement addressing For pointer expressions of the form *p++. *++p. In many cases. and multiply/add can be paired with each other and executed in parallel. the loop optimizations convert the array references to indirect references through autoincremented register variable pointers. i < N. and those variables whose uses don’t overlap may be allocated to the same register. When adjacent instructions match the addressing requirements.. A-4 . ++i) a[i]. allocates registers to user variables and compiler temporary values according to their type. where code steps through an array in a loop. The allocation algorithm also minimizes pipeline conflicts that can result from performing calculations using address generation registers in the vicinity of indirection.. or RPTB for larger loops. the compiler can detect loops controlled by counters and generate code for them using the efficient repeat forms: RPTS for single-instruction loops. See Example A–2 and Example A–8. Parallel instructions Several TMS320C3x/C4x instructions such as load/load. For both forms.Description of Compiler Optimizations - Cost-based register allocation The optimizer. See Example A–2 and Example A–8. This can result in significant improvement in execution performance. the compiler uses efficient TMS320C3x/C4x autoincrement addressing modes. See Example A–2. the iteration count can be either a constant or an expression. Variables used within loops are weighted to have priority over others. use. optional calling sequence that passes arguments to registers rather than pushing them onto the stack. the compiler combines them in parallel. See Example A–5. *p––. store/operate. Although the code generator performs this optimization. especially if calls are important in the application. when enabled. and frequency. With the optimizer. Repeat blocks The TMS320C3x/C4x supports zero-overhead loops with the RPTS (repeat single) and RPTB (repeat block) instructions. Variables with specific requirements are allocated into registers that can accommodate them. opt30 –r –02 a2. Parallel Instructions. float sum.word 2.cinit” .1 .globl _dot_product *********************************************************************** * FUNCTION DEF : _dot_product * *********************************************************************** _dot_product: PUSH AR4 * * R2 assigned to variable sum * LDI @CONST+0.10 . Induction Variable Elimination. b[10]. float dot_product () { int i.asm a2.version 30 FP .*AR4++.R2 || MPYF *AR2++.2 .end Description of Compiler Optimizations A-5 . Register Variables.10 *********************************************************************** * DEFINE CONSTANTS * *********************************************************************** .R0 EPI0_1: POP AR4 RETS . Autoincrement Addressing. i++) sum += a[i] * b[i].R0 RPTS 8 ADDF R0.bss _b.R2 LDF R2. return sum } *********************************************************************** * TMS320C30 C COMPILER Version X.AR4 LDI @CONST+1.R0 ADDF R0.if a2.opt a2.bss CONST.AR2 MPYF *AR2++.XX * *********************************************************************** . .CONST .Description of Compiler Optimizations Example A–2.0 .word _a . cg30 –p a2. i<10.globl _b .tmp .set AR3 .globl _a . Strength Reduction.if .opt . for (i=0. and Loop Test Replacement float a[10].word _b .globl _a . Repeat Blocks.*AR4++.sect ”.bss _a. ac30 –mr a2.globl _b .c a2. c a3.if . For simple assignments such as a = condition ? exprl : expr2 or if (condition) a = b.*AR2 *** B L2 .XX * *********************************************************************** . Delayed branches The TMS320C3x/C4x provides delayed branch instructions that can be inserted three instructions early in an instruction stream.R0 TSTB R0.opt .) if (*p & 0x08) *p |= 0xF0 } *********************************************************************** * TMS320C30 C COMPILER Version X. TMS320C3x/C4x Delayed Branch Instructions wait(volatile int *p) { for(.set AR3 . and conditional delayed branches for counting loops.R1 OR R1.Description of Compiler Optimizations Conditional instructions The load instructions in the TMS320C3x/C4x can be executed conditionally. the compiler can use conditional loads to avoid costly branches. cg30 –p a3.end A-6 . Example A–3. opt30 –r –02 a3.BRANCH OCCURS . ac30 –mr a3.tmp ..*AR2 BZ L2 LDI 240.globl _wait *********************************************************************** * FUNCTION DEF : _wait * *********************************************************************** _wait * * AR2 assigned to parameter p * L2 LDI 8. avoiding costly pipeline flushes associated with normal branches.opt a3.*AR2.version 30 FP . The compiler uses unconditional delayed branches wherever possible. See Example A–3.asm a3.R2 STI R2.if a3. load address register (LDA). In addition. The new addressing modes allow constants and indirect+offset operands to be used in 3-operand instructions. load data page pointer (LDPK). Example A–4 illustrates some of the new ’C4x features.Description of Compiler Optimizations TMS320C4x-specific features The TMS320C4x has several instructions and addressing modes that are particularly useful in compiled code. and a 32×32 integer multiply (MPYI). Description of Compiler Optimizations A-7 . separate AR interlocks eliminate the pipeline delays associated with independent use of the AR registers. The instructions include store integer immediate (STIK). return p–>i.Description of Compiler Optimizations Example A–4. } s. cg30 –v40 a4.BRANCH OCCURS .tmp . } *********************************************************************** * TMS320C30 C COMPILER Version X.end A-8 .opt .asm a4.*+AR2(2) LDI *AR2.if a4.R0 STI R0. j.FP NOP SUB1 2.AR2 STIK 5.XX * *********************************************************************** .*+AR2(2).if .version 40 FP . opt30 –v40 –02 a4.opt a4. p–>k *= 10.SP B R1 .R0 EPIO_1: LDI *–FP(1).set AR3 .(2). sval (s *p) { p–>j = 5. FP * * AR2 assigned to parameter p * LDA *–FP. k.globl _sval *********************************************************************** * FUNCTION DEF : _sval * *********************************************************************** _sval PUSH FP LDI SP.R1 BD R1 LDI *FP. TMS320C4x-Specific Features typedef struct S {int i.*+AR2(1) MPYI 10. ac30 –v40 a4.c a4. it can be optimized to ((a + b) – c) – d. Frequently. Description of Compiler Optimizations A-9 . pointer references. For example. allowing the compiler to optimize such expressions. This aliasing of memory locations often prevents the compiler from retaining values in registers. because it cannot be sure that the register and memory continue to hold the same values over time. For example. Alias disambiguation Programs written in the C language generally use many pointer variables. Operations between constants are folded into single constants.Description of Compiler Optimizations Expression simplification For optimal evaluation. the compiler simplifies expressions into equivalent forms requiring fewer instructions or registers. the expression (a + b) – (c + d) requires 5 instructions and 2 registers to evaluate. compilers are unable to determine whether or not two or more I (lowercase L) values (symbols. Alias disambiguation is a technique that determines when two pointer expressions cannot point to the same location. a = (b + 4) – (c + 1) becomes a = b – c + 3. which takes only 4 instructions and 1 register. See Example A–5. or structure references) refer to the same memory location. Description of Compiler Optimizations Data-flow optimizations Collectively, the following three data-flow optimizations replace expressions with less costly ones, detect and remove unnecessary assignments, and avoid operations that produce values already computed. The optimizer performs these data flow optimizations both locally (within basic blocks) and globally (across entire functions). See Example A–5 and Example A–6. - Copy propagation Following an assignment to a variable, the compiler replaces references to the variable with its value. The value could be another variable, a constant, or a common subexpression. This may result in increased opportunities for constant folding, common subexpression elimination, or even total elimination of the variable. See Example A–5 and Example A–6. - Common subexpression elimination When the same value is produced by two or more expressions, the compiler computes the value once, saves it, and reuses it. See Example A–5. Redundant assignment elimination Often, copy propagation and common subexpression elimination optimizations result in unnecessary assignments to variables (variables with no subsequent reference before another assignment or before the end of the function). The optimizer removes these dead assignments. See Example A–5. A-10 Description of Compiler Optimizations Example A–5. Data-Flow Optimizations simp(int j) { int a = 3; int b = (j * a) + (j * 2); int c = (j << a); int d = (j << 3) + (j << b); call(a,b,c,d); } *********************************************************************** * TMS320C30 C COMPILER Version X.XX * *********************************************************************** ; ac30 –mr a5.c a5.if ; opt30 –r –02 a5.if a5.opt ; cg30 –p a5.opt a5.asm a5.tmp . version 30 FP .set AR3 .globl _simp *********************************************************************** * FUNCTION DEF : _simp * *********************************************************************** _simp * * AR2 assigned to parameter j * LDI 2,R0 LSH R0,AR2,R1 ADDI R1,AR2,R2 LDI 3,R1 LSH R1,AR2,R3 LSH R2,AR2,RC ADDI R3,RC LDI 3,AR2 CALL _call EPIO_1: RETS *********************************************************************** * UNDEFINED REFERENCES * *********************************************************************** .globl _call .end Description of Compiler Optimizations A-11 Description of Compiler Optimizations Branch optimizations / control-flow simplification The compiler analyzes the branching behavior of a program and rearranges the linear sequences of operations (basic blocks) to remove branches or redundant conditions. Unreachable code is deleted, branches to branches are bypassed, and conditional branches over unconditional branches are simplified to a single conditional branch. When the value of a condition can be determined at compile time (through copy propagation or other data flow analysis), a conditional branch can be deleted. Switch case lists are analyzed in the same way as conditional branches and are sometimes eliminated entirely. Some simple control-flow constructs can be reduced to conditional instructions, totally eliminating the need for branches. See Example A–6. A-12 Description of Compiler Optimizations Example A–6. Copy Propagation and Control-Flow Simplification fsm() { enum { ALPHA, BETA, GAMMA, OMEGA } state = ALPHA; int *input; while (state != OMEGA) switch (state) { case ALPHA: state = ( *input++ == 0 ) ? BETA: GAMMA; break; case BETA : state = ( *input++ == 0 ) ? GAMMA: ALPHA; break; case GAMMA: state = ( *input++ == 0 ) ? GAMMA: OMEGA; break; } } *********************************************************************** * TMS320C40 C COMPILER Version X.XX* *********************************************************************** ; ac30 –v40 a6.c a6.if ; opt30 –v40 –02 a6.if a6.opt ; cg30 –v40 a6.opt a6.asm a6.tmp .version 40 FP .set AR3 .globl _fsm **** ******************************************************************* * FUNCTION DEF : _fsm * *********************************************************************** _fsm * * AR2 assigned to variable input * LDI *AR2++,R0 BNZ L4 L2: LDI *AR2++,R0 BZ L4 LDI AR2++,R0 BZ L2 L4: LDI *AR2++,R0 BZ L4 EPIO_1: RETS .end Loop induction variable optimizations / strength reduction Loop induction variables are variables whose value within a loop is directly related to the number of executions of the loop. Array indices and control variables of for loops are very often induction variables. Strength reduction is the process of replacing costly expressions involving induction variables with more efficient expressions. For example, code that indexes into a sequence of array elements is replaced with code that increments a pointer through the array. Loops controlled by incrementing a counter are written as TMS320C3x/C4x repeat blocks or by using efficient decrement-and-branch Description of Compiler Optimizations A-13 Description of Compiler Optimizations instructions. Induction variable analysis and strength reduction together often remove all references to your loop control variable, allowing it to be eliminated entirely. See Example A–2 and Example A–8. Loop Unrolling When the compiler can determine that a short loop is executed a low, constant number of times, it replicates the body of the loop rather than generating the loop. This avoids any branches or use of the repeat registers. (“Low” and “short” are subjective judgments made by the compiler.) See Example A–7. Example A–7. Loop Unrolling add3(int a[3]) { int i, sum = 0; for (i=0; i<3; i++) sum += a[i] return sum; } *********************************************************************** * TMS320C30 C COMPILER Version X.XX* *********************************************************************** ; ac30 a7.c a7.if ; opt30 –02 a7.if a7.opt ; cg30 a7.opt a7.asm a7.tmp .version 30 FP .set AR3 .globl _add3 *********************************************************************** * FUNCTION DEF : _add3 * *********************************************************************** _add3: PUSH FP LDI SP, FP * * R2 assigned to variable sum * LDI *–FP(2),AR2 LDI O,R2 ADDI *AR2++,R2 ADDI *AR2++,R2 ADDI *AR2,R2 LDI R2,R0 EPIO_1: LDI *–FP(1),R1 BD R1 LDI *FP,FP NOP SUBI 2,SP *** B R1 ;BRANCH OCCURS .end A-14 Description of Compiler Optimizations Loop rotation The compiler evaluates loop conditionals at the bottom of loops, saving a costly extra branch out of the loop. In many cases, the initial entry conditional check and the branch are optimized out. Loop invariant code motion This optimization identifies expressions within loops that always compute the same value. The computation is moved in front of the loop, and each occurrence of the expression in the loop is replaced by a reference to the precomputed value. See Example A–8. Inline function expansion The special keyword inline directs the compiler to replace calls to a function with inline code, saving the overhead associated with a function call as well as providing increased opportunities to apply other optimizations. See Example A–8 and Example A–9. The optimizer inlines small functions not declared as inline when invoked with the –o3 option. The size of code growth allowed may be changed using the –oi size option. Example A–8. Inline Function Expansion, part one inline blkcpy (char *to, char *from, int n) { if (n > 0 ) do *to++ = *from++; while (––n != 0); } struct s {int a , b, c[10]; }; initstr (struct s *ps, char t[12]) { blkcpy((char *)ps, t, 12); } Description of Compiler Optimizations A-15 globl _initstr *********************************************************************** * FUNCTION DEF : _initstr * *********************************************************************** _initstr PUSH AR4 * * AR2 assigned to parameter ps * AR2 assigned to variable to * AR4 assigned to parameter to * AR4 assigned to variable from * LDI R2.*AR2++ EPI0_1: POP AR4 RETS .opt a8.version 30 FP . part two *********************************************************************** * TMS320C30 C COMPILER Version X.end A-16 .asm a8.opt .R0 STI R0.R0 RPTS 10 STI R0.AR4 CMPI 0.globl _blkcpy *********************************************************************** * FUNCTION DEF : _blkcpy * *********************************************************************** _blkcpy: PUSH AR4 * * R3 assigned to parameter n * AR2 assigned to parameter to * AR4 assigned to parameter from * LDI R2. opt30 –r –02 a8. Inline Function Expansion.*AR2++ || LDI *AR4++.RC SUBI 1.*AR2++ EPI0_2: POP AR4 RETS .tmp .AR4 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>ENTERING blkcpy() LDI *AR4++.R0 L5: STI R0.c a8.R3 BLE EPI0_1 LDI R3.RC RPTB L5 LDI *AR4++.if a8.XX * *********************************************************************** . cg30 –p a8.if .Description of Compiler Optimizations Example A–9.set AR3 . ac30 –mr a8. . Topic B. . . . . . . . . . . . the ANSI C standard defines a set of runtimesupport functions that perform these tasks. . . . . Using the ANSI standard library ensures a consistent set of functions that provide for greater portability. . or culture). . . . . The TMS320C3x/C4x C compiler implements the complete ANSI standard library. . . . . . . . . . . . . . . . . . . . nationality. . string operations.Appendix B Appendix A The C I/O Functions Some of the tasks that a C program performs (such as I/O. . . . . dynamic memory allocation. . .2 B. . B-2 Overview of Low-Level I/O Implementation . . . . . . . . . . However. the TMS320C3x/C4x runtimesupport library includes routines that give you direct C language I/O requests. . . . . . . . . . . . . . . . . . . except for those facilities that handle exception conditions and locale issues (properties that depend on local language.3 Page Using the I/O Functions . . In addition to the ANSI-specified functions. . . . . . and trigonometric functions) are not part of the C language itself. . . . . . . . . . . . . B-5 B-1 .1 B. B-3 Adding a Device For C I/O . . . world in the debugger command window B-2 .c: #include <stdio. world into that file Closes the file Prints the string Hello again. For example.lib –o main. world\n”). If there is not enough space on the heap for a C I/O buffer.Using the I/O Functions B.”Hello. For information on the –heap option. fprintf(fid. If a call to printf() mysteriously fails. With properly written device drivers. For example. To set the heap size. given the following program in a file named main. fclose(fid). Check the size of the heap.”w”). the library also offers facilities to perform I/O on a user-specified device. the capability to perform I/O on the host gives you more options when debugging and testing code.out Executing main.out under the debugger on a SPARC host accomplishes the following: 1) 2) 3) 4) Opens the file myfile in the directory where the debugger was invoked Prints the string Hello.out: cl30 main.c –z –heap 400 –l rts. When used in conjunction with the debugging tools. buffered operations on the file will fail. printf(”Hello again.h> main() { FILE *fid. use the –heap option when linking. world\n”). this may be the reason. printf statements executed in a program appear in the debugger command window.1 Using the I/O Functions The C I/O functions make it possible to access the host’s operating system to perform I/O (using the debugger).h for each module that references a function. To use the I/O functions: - Include the header file stdio. links. and creates the file main. fid = fopen(”myfile”. see the Linker Description chapter of the TMS320C3x/C4x Assembly Language Tools User’s Guide. } Issuing the following shell command compiles. scanf. The high-level functions are the standard C library of stream I/O routines (printf. low level.2 Overview of Low-Level I/O Implementation The code that implements I/O is logically divided into layers: high level.h and provide the interface between the high-level functions and the device-level drivers that actually perform the I/O command on the specified device. LSEEK.Overview of Low-Level I/O Implementation B. and UNLINK. The data structures interact as shown in Figure B–1. fopen. The low-level routines are comprised of basic I/O functions: OPEN. These low-level routines are declared in file. Figure B–1. Interaction of Data Structures in I/O Functions Stream table file_descriptor1 file_descriptor2 Device table open read open read The C I/O Functions B-3 . WRITE. CLOSE. and device level. and so on). The stream table interacts with the device table to ensure that an I/O command performed on a stream executes the correct device-level routine. RENAME. The low-level functions also define and maintain a stream table that associates a file descriptor with a device. getchar. These routines map an I/O request to one or more of the I/O commands that are handled by the low-level routines. READ. and they point to the host device and associated device drivers. B-4 . They map directly to the low-level I/O functions. The specifications for writing device-level routines to interface with the lowlevel routines are shown on pages B-7 to B-10. The runtime-support library includes the device drivers necessary to perform I/O on the host on which the debugger is running. and stderr. The First Three Streams in the Stream Table Stream table file_descriptor1 file_descriptor2 file_descriptor3 stdin stdout stderr open read Host Device table open read At the next level are the user-definable device-level drivers. Figure B–2. Each function must set up and maintain its own data structures as needed. Some function definitions perform no action and just return.Overview of Low-Level I/O Implementation The first three streams in the stream table are predefined to be stdin. stdout. Note: Use Unique Function Names The function names. call fopen() to open a stream and associate it with that device. The device table is a statically-defined array that supports n devices. Use other names for the device-level functions that you write. see the add_device function on page 5-23. The C I/O Functions B-5 . CLOSE.2.h and is composed of the following fields: name flags function pointers is the string for device name. The low-level routine add_device() finds the first empty position in the device table and initializes the device fields with the passed-in arguments. The structure representing a device is also defined in stdio. 2) Use the low-level function add_device() to add your device to the device_table. Overview of Low-Level I/O Implementation. specifies whether the device supports multiple streams or not. on page B-3. where n is defined by the macro _NDEVICE found in stdio. are pointers to the device-level functions: - CLOSE LSEEK OPEN READ RENAME WRITE UNLINK The first entry in the device table is predefined to be the host device on which the debugger is running. The procedure for using these facilities is: 1) Define the device-level functions as described in subsection B. and so on. READ.3 Adding a Device For C I/O The low-level functions provide facilities that allow you to add and use a device for I/O at runtime. Use devicename:filename as the first argument to fopen(). 3) Once the device is added.h. are used by the lowlevel routines. OPEN.Adding a Device For C I/O B. For a complete description. my_close. int fno). my_read. my_write.”Hello. extern int my_write(int fno. unsigned count). main() { FILE *fid. char *new_name). long offset.h> /****************************************************************************/ /* Declarations of the user–defined device drivers */ /****************************************************************************/ extern int my_open(char *path. fclose(fid).”w”). fprintf(fid. extern int my_rename(char *old_name. my_rename). world\n”). unsigned count). extern int my_lseek(int fno.Adding a Device For C I/O The following program illustrates adding and using a device for C I/O: #include <stdio. my_open. extern int my_read(int fno. unsigned flags. my_lseek. add_device(”mydevice”. fid = fopen(”mydevice:test”. char *buffer. } B-6 . extern int my_close(int fno). extern int my_unlink(char *path). my_unlink. char *buffer. int origin). _MSA. The file_descriptor is the stream number assigned by the low-level routines that is associated with the opened device or file.Alphabetical Summary of C I/O Functions CLOSE. The LSEEK function sets the file position indicator for the given file to origin + offset. The offset indicates the relative offset from the origin in characters. The origin is used to indicate which of the base locations the offset is measured from. - The file_descriptor is the stream number assigned by the low-level routines that the device-level driver must associate with the opened file or device. long offset. LSEEK CLOSE Syntax Description Close File or Device For I/O int CLOSE(int file_descriptor). Return Value The function returns one of the following values: 0 –1 if successful if fails LSEEK Syntax Description Set File Position Indicator long LSEEK(int file_descriptor. The origin must be a value returned by one of the following macros: SEEK_SET (0x0000) Beginning of file SEEK_CUR (0x0001) Current value of the file position indicator SEEK_END (0x0002) End of file Return Value The function returns one of the following values: # new value of the file-position indicator if successful EOF if fails The C I/O Functions B-7 . The file position indicator measures the position in characters from the beginning of the file. The CLOSE function closes the device or file associated with file_descriptor. int origin). Note. however. The OPEN function opens the device or file specified by path and prepares it for I/O. - The path is the filename of the file to be opened. depending on how data is interpreted by the device. including path information.OPEN Alphabetical Summary of C I/O Functions OPEN Syntax Description Open File or Device For I/O int OPEN(char *path. unsigned flags. The function returns one of the following values: stream number assigned by the low-level routines that the device-level driver associates with the opened file or device if successful if fails B-8 . depending on the open attributes. int mode). Return Value # <0 The mode is required but ignored. The flags are specified using the following symbols: O_RDONLY O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_BINARY (0x0000) (0x0001) (0x0002) (0x0008) (0x0100) (0x0200) (0x8000) /* /* /* /* /* /* /* open for reading */ open for writing */ open for read & write */ append on each write */ open with file create */ open with truncation */ open in binary mode */ These parameters can be ignored in some cases. The flags are attributes that specify how the device or file is manipulated. that the high-level I/O calls look at how the file was opened in an fopen statement and prevent certain actions. The buffer is the location of the buffer where the read characters are placed. unsigned count). Return Value The old_name is the current name of the file. The function returns one of the following values: 0 if the rename is successful Non-0 if it fails The C I/O Functions B-9 . The function returns one of the following values: if EOF was encountered before the read was complete number of characters read in every other instance if fails RENAME Syntax Description Rename File int RENAME(char *old_name. The count is the number of characters to read from the device or file. The READ function reads the number of characters specified by count to the buffer from the device or file associated with file_descriptor. Return Value 0 # –1 The file_descriptor is the stream number assigned by the low-level routines that is associated with the opened file or device. char *new_name).Alphabetical Summary of C I/O Functions READ. The RENAME function changes the name of a file. The new_name is the new name for the file. RENAME READ Syntax Description Read Characters From Buffer int READ(int file_descriptor. char *buffer. Return Value # –1 The file_descriptor is the stream number assigned by the low-level routines that is associated with the opened file or device. The buffer is the location of the buffer where the write characters are placed. Return Value The function returns one of the following values: 0 –1 if successful if fails WRITE Syntax Description Write Characters to Buffer int WRITE(int file_descriptor. The path is the filename of the file to be opened. The count is the number of characters to write to the device or file. The function returns one of the following values: number of characters written is successful if fails B-10 . The UNLINK function deletes the file specified by path. The WRITE function writes the number of characters specified by count from the buffer to the device or file associated with file_descriptor. including path information. unsigned count).UNLINK. char *buffer. WRITE Alphabetical Summary of C I/O Functions UNLINK Syntax Description Delete File int UNLINK(char *path). but aliasing can cause problems for the optimizer. assignment statement: A statement that assigns a value to a variable. The assembler substitutes absolute operation codes for symbolic operation codes. as when a pointer points to a named object. Glossary C-1 . or replace members of the archive library. block: A set of declarations and statements that are grouped together with braces. directives. and macro directives. allocation: A process in which the linker calculates the final memory addresses of output sections.cinit section) before beginning program execution. B binding: Associating or linking together two complementary software objects. autoinitialization: The process of initializing global C variables (contained in the . The optimizer has logic to detect aliasing. assembler: A software program that creates a machine-language program from a source file that contains assembly language instructions. extract. archive library: A collection of individual files that have been grouped into a single file. as well as to add new members. archiver: A software program that allows you to collect several individual files into a single file called an archive library.Glossary Appendix C Appendix A Glossary A aliasing: a method of accessing a single data object in more than one way. The archiver also allows you to delete. and absolute or relocatable addresses for symbolic addresses. You can use the . Comments are not compiled. which control the actions of a device). They are usually included in various batch files.data directive to assemble code into the .bss: One of the default COFF sections. D . they have no effect on the object file.data section.BAT. C-2 . You can use the . and their final values. entry point: The starting execution point in target memory. The . or linked. in AUTOEXEC.bss directive to reserve a specified amount of space in the memory map that can later be used for storing data.data section is an initialized section that contains initialized data. what line they were defined on. directive: Special-purpose commands that control the actions and functions of a software tool (as opposed to assembly language instructions. The .Glossary . C C compiler: A program that translates C source statements into TMS320C3x/C4x assembly language source statements.data: One of the default COFF sections. executable module: An object file that has been linked and can be executed in a TMS320 system. for example. which lines referenced them.bss section is uninitialized. COFF (common object file format): A binary object file format that promotes modular programming by supporting the concept of sections. cross-reference lister: A debugging tool that accepts linked object files as input and produces cross-reference listings as output. E environment variables: System symbols that you define and assign to a string. cross-reference listing: An output file created by the assembler that lists the symbols that were defined. assembled. comment: A source statement (or portion of a source statement) that is used to document or improve readability of a source file. constant: A numeric value that can be used as an operand. published by Prentice-Hall. Ritchie. input section: A section from an object file that will be linked into an executable module. Englewood Cliffs.data. G global: A kind of symbol that is either 1) defined in the current module and accessed in another. I initialized section: A COFF section that contains executable code or initialized data. a symbol. This book describes ANSI C and is used as a reference in this book. H high-level language debugging: The ability of a compiler to retain symbolic and high-level language information (such as type and function definitions) so that a debugging tool can use this information. or . K K & R: The C Programming Language (second edition).Glossary expression: A constant. hole: An area between the input sections that compose an output section that contains no actual code or data. or 2) accessed in the current module but defined in another. Paragraphs within the book are referred to with this symbol: §. by Brian Kernighan and Dennis M. New Jersey.sect directive. 1988. . L Glossary C-3 . a software-configurable data type whose length can be programmed to be any value in the range of 1–16 bits.text. An initialized section can be built up with the . F field: For the TMS320. or a series of constants and symbols separated by arithmetic operators. Glossary label: A symbol that begins in column 1 of a source statement and corresponds to the address of that statement. macro definition: A block of source statements that define the name and the code that make up a macro. their line numbers. listing file: An output file. of an assembly language instruction. macro call: The process of invoking a macro. union. as well as symbols and the addresses at which they were defined. created by the linker. loader: A device that loads an executable module into TMS320 system memory. that shows the memory configuration. map file: An output file. created by the assembler. M macro: A user-defined routine that can be used as an instruction. section composition. object library: An archive library made up of individual object files. assembler directive. or enumeration. O object file: A file that has been assembled or linked and contains machine-language object code. C-4 . macro expansion: The source statements that are substituted for the macro call and are subsequently assembled. that lists source statements. options: Command parameters that allow you to request additional or specific functions when you invoke a software tool. or parameters. archive. which is partitioned off into functional blocks. or macro directive. member: The elements or variables of a structure. operand: The arguments. and section allocation. memory map: A map of TMS320 target system memory space. linker: A software tool that combines object files to form an object module that can be allocated into TMS320 system memory and executed by the TMS320. and their effects on the SPC. real mode: Sixteen-bit native MS-DOS mode. output section: A final. structure: A collection of one or more variables grouped together under a single name. section header: A portion of a COFF object file that contains information about a section in the file. their previous value is resumed when the function or program is re-entered. The linker uses this model when you invoke the linker with the –c option. and variables are initialized at runtime. These programs require an extended memory manager and will run only on larger processors (’386 or better). executable object file that can be downloaded and executed on a target system. R RAM model: An autoinitialization model used by the linker when linking C code. S section: A relocatable block of code or data that will ultimately occupy contiguous space in the TMS320 memory map. ROM model: An autoinitialization model used by the linker when linking C code. Glossary C-5 . The RAM model allows variables to be initialized at load time instead of runtime.Glossary output module: A linked. P protected mode: Thirty-two bit extended DOS mode. This mode limits the available memory to 640K. etc. static: A kind of variable whose scope is confined to a function or a program. contains the section’s size. executable module. the linker loads the . They can utilize all the available RAM on the computer. Calls to DOS may involve switching from protected to real mode. allocated section in a linked. the header points to the section’s starting address. Each section has its own header. The linker uses this model when you invoke the linker with the –cr option. In the ROM model.cinit section of data tables into memory. The values of static variables are not discarded when the function or program is exited. Glossary symbol: A string of alphanumeric characters that represents an address or a value. symbolic debugging: The ability of a software tool to retain symbolic information so that it can be used by a debugging tool such as a simulator or an emulator. U uninitialized section: A COFF section that reserves space in the TMS320 memory map but that has no actual contents.usect directives. V virtual memory : The ability for a program to use more memory than a computer actually has available as RAM. When RAM is not sufficient. The TMS320C3x/C4x tools use a memory extender to provide virtual memory management. These sections are built up with the . unsigned: A kind of value that is treated as a positive number. W word: A 32-bit addressable location in target memory. symbol table: A portion of a COFF object file that contains information about the symbols that are defined and used by the file. This is accomplished by using a swap file on disk to augment RAM. This memory extender is not provided as an executable but is embedded in several of the object programs. union: A variable that may hold (at different times) objects of different types and sizes. C-6 . regardless of its actual sign. part of the program is swapped out to a disk file until it is needed again. The combination of the swap file and available RAM is the virtual memory.bss and . Appendix D Appendix A Summary of Updates in This Document This appendix provides a summary of the updates in this version of the document. D-1 . Updates within paragraphs appear in a bold typeface. asm file specifies the silicon revision of the target chip to enable additional functionality for more recent silicon releases. information see page 2-11. 40. Compiler Options Summary Table. otherwise interlist C and assembly source statements interlist C and assembly source statements undefine a constant specify processor. 31. For more information.Summary of Updates in This Document Page: 2–6 Change or Add: Add one row (-msrevx) s to the General Shell Option section of Table 2–1. Used in conjunction with –v flag. or 44 (default is –v30) (see also –msrev) enable linking (all options following are passed to linker) 2–6 –ss –uname –vxx –z 2–62 D-2 Specify silicon revision (see -msrev in shell) . 32.asm file) suppress progress messages (quiet) suppress all messages (super quiet) interlist optimizer comments and assembly source statements if available. xx = 30. Add note (see also -msrev) to the -vxx option General Shell Options These options control the overall operation of the cl30 shell. Example: –msrev6 –v31 : enable new (1996) ’C31 parallel instructions –msrev2 – v32 : enable new (1996) ’C32 parallel instructions –n –q –qq –s compile only (create . Option –@filename –c –dname[=def] –g –idir –k –msrevx Effect causes the compiler shell to read options from the specified file no linking (negates –z) predefine a constant enable symbolic debugging define #include search path keep . the compiler compares the name of the object to a list of standard control registers for the ’C3x/C4x (see Table 3–2). Valid Control Registers Register IE IF IOF ST Description CPU/DMS interrupt enable register CPU interrupt flag register I/O flags Status register The cregister keyword can only be used in file scope. Keywords. Keywords. you can use the register name directly.3. The cregister keyword is not allowed on any declaration within the boundaries of a function. The cregister keyword does not imply that the object is volatile. If the control register being referenced is volatile (that is. can be modified by some external control). Summary of Updates in This Document D-3 . 3.1. See TMS320C3x/C4x CPU and Instruction Set Reference Guide for detailed information on the control registers. It can only be used on objects of type integer or pointer. the compiler issues an error. Table 3–2.1. 3–7 Add Section 3. then the object should be declared with the volatile keyword also. Once you have declared the register. you must declare each register (with or without volatile) as follows: extern cregsiter volatile unsigned int register. The cregister keyword is not allowed on objects of any floating-point type or on any structure or union object. to the mini table of contents. with subsection cregister Keyword and subsection near and far keywords. Keywords Page: 3–1 Change or Add: Add Section 3. If the name does not match.3. If the name matches. the compiler generates the code to reference the control register. To use a control register in Table 3–2. When you use the cregister keyword on an object.1 The cregister Keyword The TMS320C3x/C4x compiler extends the C language by adding the cregister keyword to allow high level language access to control registers.Keywords Summary of Updates in This Document 3. bss holds the address of the variable. D-4 . This can be required if the total amount of program data is larger than the offset allowed (32K) from the DP. far int foo (). IOF. aro sti ro.3. unsigned myfunc (unsigned int mask) { while (ST & mask == 0) /* Do nothing. return IOF. Two storage class modifiers cannot be used together in a single declaration.2 The near and far Keywords The ’C3x/C4x C compiler extends the C language with the near and far keywords to specify how global and static variables are accessed and how functions are called. static near int x. the following are legal uses: far static int x. static int far x. @_var far keyword The compiler cannot access the data item via the dp. For example: ldiu @cl1. 3. after. They can appear before.Keywords of Updates in This Document Summary Example 3–1. Define and Use Control Registers extern extern extern extern cregisger cregister cregisger cregister volatile volatile volatile volatile unsigned unsigned unsigned unsigned int int int int IE. the near and far keywords are treated as storage class modifiers. *aro where cl1 in the . ST. or in between the storage class specifiers and types. For example. static far int foo () Near and far data objects Global and static data objects can be accessed in the following two ways: near keyword The compiler assumes that the data item can be accessed relative to the data page pointer. IF. } wait */. For example: sti ro. Syntactically. See section 3.2. or –mf are used. it is normally loaded using relative offset addressing from the data page pointer (DP.5. DP points to the beginning of the . ldiu @cl1. The DATA_SECTION pragma. when options –ml. which means that every data object is handled as if it were declared near. where constant cl1 in the . . If the options –ml. the compiler uses the PC-relative call instruction. –mf. or –mb are used.bss section.bss holds the address of the function. The default changes. Near and far function calls Function calls can be invoked in one of two ways: near keyword The compiler assumes that the destination of the call is within 224 bytes of the caller. call _func far keyword The compiler is told by the user that the call is not within 224 bytes of the caller. unless it is actually declared far.Keywords Summary of Updates in This Document By default. however. on page 3-13. unless it is actually declared far. This ensures access to the variable. the compiler generates small-memory model code.bss section. which is B14). If you use the DATA_SECTION pragma. the default assumptions change. –mb. . and this cannot be overridden. which means that every function call is handled as if it were declared near. and the compiler uses the register addressing mode of the call instruction. ro callu ro . Summary of Updates in This Document D-5 . since the variable might not be on the same data page as the . If an object is declared near. Here. See those options for how their usage changes the defaults of the standard memory model. By default. the object is indicated as a far variable. the compiler generates small-memory model code. . . D-6 . . restore AR4 restore upper 32 bits of restore lower 32 bits of restore upper 32 bits of restore lower 32 bits of deallocate local frame restore Frame Pointer restore STatus register R4 R4 R3 R3 B–2 Cut the second bullet for the Using the I/O Functions section. Exit POP POPF POP POPF POP SUBI POP POP reti AR4 R4 R4 R3 R3 2.Keywords of Updates in This Document Summary Page: 4–31 Change or Add: Change the last four lines of the EXIT code example. . . .SP FP ST . . obj file.00.0. works ok in v. aborting Assembler Generates incorrect “P” parallel-addressing mode 01 instead of 11.sym debug information contains wrong offset get incorrect results for long doubles divide operation TMS320C3x User’s Guide documents –gsrev6 switch Codegen creates illegal parallel instruction subf3 || stf Compiler generate “decomposition error” on sample code Logical AND operator bug in v.0 when small mem model Summary of Updates in This Document D-7 .Keywords Summary of Updates in This Document Page: Change or Add: The following is the list of known bugs fixed for this release.obj extension . Optimization appears to use direct instead of indirect addressing Hex3– –byte option.7 see detail file’s. MPYF3||SUBF3 Far function call generates invalid addresses in big memory configuration Compiler removes circular buffer references from asm (“ ”) statements pragma DATA_SECTION generates code incorrectly for v5. >> out of memory.10. doesn’t work with 5. R5. Please refer to the appropriate contact on the If You Need Assistance page of this manual for more information. 4. worked fine with 4. C Compiler generates wrong Assembly code for the #line Statement COMPILER ERROR: Unsupported constant operand for LDP optimizer generates wrong starting address for structure element When linking a debugger MemBlk Save . Bug number SDSsq02943 SDSsq03255 SDSsq03762 SDSsq03767 SDSsq03797 SDSsq03799 SDSsq03814 SDSsq03879 SDSsq03888 SDSsq03890 SDSsq03897 SDSsq03908 SDSsq03910 SDSsq03921 SDSsq03982 SDSsq03985 SDSsq03988 SDSsq03993 SDSsq04019 SDSsq04024 SDSsq04084 Description How should the SET COND bit be set in the C4x ST reg for the C Compiler? Passing –g to asm30 does not work with current Debuggers Command file for lnk30 does not allow embedded “–” in file name Archiver does not allow a default .70 optimization level 2 is not as effective as optimization level 1. 5. in ret. compiler generates bad shifts Incorrect code generated for calls to ISR and functions.const section. wastes space Compiler uses inefficient FP divide vs 4.70 Compiler is generating illegal code Compiler does not account for second word of long double when optimizing D-8 .src will print as 3 digits after year 2000 Compiler generates incorrect code using register passing model.Keywords of Updates in This Document Summary Bug number SDSsq04151 SDSsq04155 SDSsq04164 SDSsq04166 SDSsq04172 SDSsq04373 SDSsq04202 SDSsq04215 SDSsq04219 SDSsq04227 SDSsq04261 SDSsq04296 SDSsq04298 SDSsq04301 SDSsq04257 SDSsq04338 SDSsq04378 Description The year. tm_year. ST not popped last compiler code calls MOD_I40 instead of MOD_U40 Incorrect code generated for array reference using –o2 INCOMPATIBLE ADDRESSING MODES generated with –02 switch used Assembler swaps operands for MPYF3 || ADDF3 RTS has general errors/nuisances Compiler inserts unneeded .aligns into . PRTS30 macros for SWW control are incorrect Compiler allocating RS/RC/RE inside c_intxx()’s C4x 32-Bit FP Divide Routine DIV_F40 has error Codegen adds errant adds into assembly code With –mf. Wants to be able to use a C header to make assembly .string ASM directv Add capability for packed char/int arrays to save memory Sometimes the map and stdout do not report eh .struct directives Optimize the c_intxx() functions customer has problem compiling following code with v4.70 strtod() function does not give accurate results Invalid Divide Routine Request for compiler to be able to place init data in named sections Request for compiler to allow packed bytes Symbol “pinit” at address FFFFFFFF appears in link map Encoding of MPYF||SUBF changed from v4.Keywords Summary of Updates in This Document Page: Change or Add: The following is the list of bugs closed for this release: Bugs SDSsq02750 SDSsq02751 SDSsq02917 SDSsq02633 SDSsq02964 SDSsq02965 SDSsq02966 SDSsq02967 SDSsq02969 SDSsq03152 SDSsq03153 SDSsq03247 SDSsq03257 SDSsq03258 SDSsq03333 SDSsq03492 SDSsq03570 SDSsq03644 SDSsq03645 SDSsq03788 SDSsq03798 SDSsq03892 SDSsq03896 SDSsq03909 Description Enhancement request for error and warning summary Request to change the function of the block keyword Documentation incomplete Problem with STF.7 preprocessing does not work correctly for conditional compilations asm(“ ”) statement with circular addressing not compiled corrected by C compiler When converting to ascii-hex format. Need option to do RND before STF ISR’s should use more ARx’s than Rx’s to reduce push/pops switch (var & 7) generates useless default case data & prog on same page = direct addressing Allow assembly DATA in non-standard sections Assembler should warn of possible parallelism Add capabilities to support quoted strings in packed . sometimes places entry point in output file Summary of Updates in This Document D-9 .cinit section. 70 to V5.00 ASM30 generates an INDIRECT ADDRESS REQUIRED error that v.5. The #pragma CODE_SECTION doesn’t work D-10 .70 does not.Keywords of Updates in This Document Summary Bugs SDSsq03911 SDSsq04011 SDSsq04090 SDSsq04165 SDSsq04167 SDSsq04220 SDSsq04347 Description Error when compiling code with #line preprocessor command enhancement request – 40bit precision in register variable calls v. Differences from V4.4.00 Inline memcpy being generated in c_intxx()’s Optimizer ignores –onx from shell command line and –z from opt30 command line. 5-52 bsearch function. 5-27 atan2 function. 2-14. 3-17 assembler. 5-22. 2-36 bmalloc function. 2-20 aliasing. 2-36 Index-1 .h header. 4-3 forcing into a 64K data page. 5-22 abs function. 5-29 bmalloc8 function. 5-25 . 2-68. 2-23 autoinitialization. 5-4. 2-69 branch delay slot filling. 2-62 asm statement. 5-25. 2-42 alternate directories for include files.asm extension. 2-24 AR0 (FP). 4-6. 2-20 _BIGMODEL. 2-23 assembly language and C source statements. 5-27 archive library. 2-24 –aa compiler option.bss into a 64K data page. 2-68 archiver. 4-38 ROM model. 5-28 atol function. 4-39 –ax compiler option.Index Index A –a linker option. 2-57 acos function. 2-64 –b linker option. 4-37. 2-41. 4-37. 4-22 assert function. 5-36 atof function. 5-25 arc tangent.obj. 4-39 RAM model. 5-11. 5-29 bmalloc16 function. 5-29 boot. 2-70. 2-69. 2-33 ANSI C. 2-24 base-10 logarithm. using to force . 3-23 block linker directive. 2-23 aliased variables. 5-23 –al compiler option. 2-23 ASCII conversion functions. 5-34 asin function. 5-26 assert. 1-3. 2-23 B –b interlist utility option. 5-34. 5-28 –au compiler option. 2-57 options. 1-3 –as compiler option.bss section. 2-69. 2-54 –ar linker option. 4-37. 5-36 ac30. 4-28 C language. 5-22 arc sine. 5-64. 5-66 ansi_ftoi. 3-1–3-25. 2-69. 5-30 . 2-23 abort function. 5-28 asctime function. 2-49 assembly language modules. 5-27. 2-54 absolute value. 5-28 atoi function. 5-22 –ad compiler option. 5-47 big memory model. 5-22 as intrinsic. 2-31 bit fields. 3-21 broken-down time. 3-3. 4-4 AR1 (SP). 5-27 atexit function. 2-23 add_device function. 4-4 arc cosine. 5-14 atan function. 2-23 assembler options. 2-16. 2-31 _C31. 2-65. 2-1–2-75 error handling. 5-45 islower.Index buffer define and associate function. 3-20 intrinsics support. 5-14 . 2-56 running as separate passes. 2-51 far calls. 5-63. 5-5. 5-76 tolower. 2-33 _c_int0. 5-11. 4-2. 2-12–2-75 overview. 5-45 isalpha. 3-2 conversions. 2-57 C language.cl extension. 2-67 . 5-14 isalnum. 5-74 read function. 5-33 cosh function. 5-5 C language.h header. 5-52. 3-24–3-25 optimizer. 5-11. B-7 code generator. 4-2 constants. 2-2 concatenate strings. 5-45 isgraph. 2-56. 2-56 options. 4-4. 3-21 description. 2-31 calendar time. 2-28. 2-66. 5-38 read functions. 2-51 CODE_SECTION pragma. characteristics. 5-5. 5-31. 5-77 . 2-28 _C30. 5-69 compatibility. 2-64 CLK_TCK macro. multiple characters. 2-70 compiling C code. 3-2 – –c library build utility option. 4-38 . 5-68 . 5-34 ctype. 5-33 –cr linker option. 2-3 limits. 5-32 clearerr function. 5-45 isascii. 2-49 C_DIR environment variable. 2-54 invoking the. 3-3 cos function. 2-69. 2-51 code-F error messages. 5-32 clist. 5-76 calloc function. 3-12 compare strings. 2-66. 5-45 isupper. C language. 2-62 options. 2-62 character conversion functions. 2-12.c extension. 5-38 character constants. 5-45 isdigit. 2-51 code-I error messages. 5-37 CLOSE I/O function. 3-23 character sets. 5-45 Index-2 isxdigit. 5-32 cg30. 5-41. single character. 2-31 _C3x. 5-33 clock_t type. 5-45 iscntrl. 5-11 close file function. 5-51 calloc16 function. 5-61 specification function. 2-52 code-W error messages. 3-22–3-23 compiler branch delay slot filling. 2-4. 5-45 isspace.const section. 5-77 toupper. 2-12. 3-2 character-typing conversion functions. 2-70. 3-3. 5-45 isprint. 5-31 ceil function. 2-69 C_OPTION environment variable. 2-24. 6-2 –c linker option. 2-31 _C4x. 2-69. 5-34. 2-24. 2-69 C source statements and assembly language. 2-64 clear EOF function. 4-6 ctime function. 5-59 BUFSIZE macro.cinit section. 2-56–2-64 sections. 5-33 clock function. 5-31 calloc8 function. 3-18. 2-63 code-E error messages. a number of characters. 5-45 ispunct. 5-45 toascii. 2-31 _C40. 2-5. 5-9 C –c compiler option. 5-34 cosine. 5-34 div function. 2-69 for C code. 2-4. 2-52 error options. 2-54 fast_invf intrinsic. 5-36 exponential math function.h header. 5-10 division. 5-22. 5-37 ferror function. 2-15 –f linker option. 5-5 errors treated as warnings. 2-52 –fc file specifier. 5-27. 3-22 F –f compiler option. 5-26 NDEBUG macro. 5-5 errno. 4-3 data types. 5-53 error handling. 3-13 _ _DATE_ _. 5-36 exp function. 2-32. 2-54 fast_imult intrinsic. 3-2. 2-51 general. 2-24 EDOM macro. 3-3 dspcl. 2-14 –eo. C language. 5-32 mapping function. 2-33 C_DIR. 2-28 EOF macro. 5-44 environment variable. 3-3 default argument promotions. 4-4 ERANGE macro. 3-2. 2-53 error message macros. 5-5 entry points _c_int0.data section. 5-8. 3-3 external declarations. C language. 5-9 EPROM programmer. 5-14 assert.Index D –d compiler option. 3-23 exit function. 2-24 –fa file specifier. 2-28. 2-15 fclose function. 2-40 declarations. 4-25 device adding. 2-15 fabs function. 2-14 –e linker option. 2-4. 2-52 escape sequences. 5-36 as intrinsic. 1-4 Index-3 . 5-11 debugging optimized code. 5-23 diagnostic information. See NDEBUG macro difftime function. 2-33 C_OPTION. 2-15 –fc. 2-69 enumerator list. 3-3 C language. 5-36 expressions. 2-51 code-I. 2-14 –ea. 2-19 defining variables in assembly language. 2-15 –fo. 2-54 fatal errors. 2-31 daylight savings time. B-5 functions. 2-51. trailing comma. 5-26 diagnostic messages. 5-5 error indicators function. 2-3 dynamic memory allocation. 2-51 code-F. 3-23 environment information function. 2-51–2-53. 5-37 fflush function. 2-28 TMP. 2-15 –fa. 3-22 using error options. 5-37 feof function. 5-26 error messages code-E. 5-35 div_t type. 5-37 E –e compiler option. 3-20 fast_ftoi intrinsic. 2-12 . 2-53 error reporting. 5-4 assert. 3-4–3-6 DATA_SECTION pragma. 2-69 reset vector. 2-52 code-W. 2-54 far calls. float40 section. 3-6 floating-point math functions. 5-42 ldexp. 3-22 listing file. 5-75 floating-point remainder. 5-27 ceil. 5-17 abort.lib. 5-43 G –g compiler option. 5-9 fprintf function. 5-6 . 2-12 –g linker option. 4-15–4-21 function calls. 5-15 acos. 5-33 cosh. 2-15 fread function. 3-14 FUNC_IS_PURE pragma. 5-27 atof. 5-58 rename function. 5-28 . 2-16 fwrite function. 5-41 frexp function. 5-62 tan. 5-39 floor function. 5-40 –fr file specifier option. 2-14 –eo option.Index fgetc function. 3-15 FUNC_NO_GLOBAL_ASG pragma. 5-34 exp. 5-41 freopen function. 2-14 –e option. 2-31 filename. 5-42 fsetpos function. 2-15 fopen function. 5-39 FOPEN_MAX macro. 2-68 float. 5-46 log10. 5-76 filename extensions. 4-4. 2-14 –ea option. 2-15 fscanf function. 5-39 frexp. 5-27 atan2. 5-38 fgets function. 5-43 –ft file specifier option. 2-15 file. 5-40 fputs function. 5-36 fabs. 5-40 fputc function. 5-42 frieee intrinsic. 5-41 free8 function. described. 5-39 –fo file specifier option. 5-39 flush I/O buffer function. 5-47 modf. 3-15 FUNC_NEVER_RETURNS pragma. 5-75 tanh. 5-14. 5-42 fseek function.h header. 5-5 _ _FILE_ _.h header. 5-9 FP register. 3-16 function call conventions. 2-4 filename specifications. 5-62 sqrt. 5-8. 2-14 –f option. 4-3 function prototypes. 5-37 Index-4 fmod function. generate function. 5-38 fgetpos function. using the stack. 5-39 fmod. 2-4 FILENAME_MAX macro. 3-14 FUNC_IS_SYSTEM pragma. 5-22 atexit. 3-15 FUNC_NO_IND_ASG pragma. 5-58 FILE data type. 5-53 pow. 5-41 free16 function. 5-46 log. 3-13 FUNC_EXT_CALLED pragma. 2-15 ftell function. 5-38 file removal function. 5-36 floor. 2-54 –fs file specifier option. 5-9 flib. 5-22 asin. 5-22 abs. 2-19. 5-43 FUNC_CANNOT_INLINE pragma. 2-24 general utility functions. 2-14 file specifier options. 4-11 fpos_t data type. 5-10. 5-40 free function. 5-54 sinh. 5-9 file extension. 5-25 atan. 5-32 cos. B-10 WRITE. 5-28 bmalloc.h header. 5-34 hyperbolic math function. 5-57 strtod. 2-24 –heap8 linker option. 5-35 ltoa.h header. 2-70. 5-62 hyperbolic tangent. 4-2 H – –h library build utility option. 5-11 stdlib. 5-51 qsort. 1-4 HUGE_VAL. 5-73 strtol. 4-2 . 5-5 float. 5-29. 5-35 exit. 4-2 gmtime function. 3-2–3-3 #include files. 5-29 bsearch. 5-56 rand.const.h header.h header. 5-30 calloc. 5-28 atol. 2-12 . 5-5 described. 2-30. 5-43 getc function.Index atoi. 2-12 #include preprocessor directive.cinit.h header. 5-44 gregorian time. 5-43 getchar function. 5-41 labs. 2-33 –i linker option. 2-62 implementation errors. 5-4 initialization. 5-57 realloc. 5-61 srand. 2-12 get file-position function. B-7 flush buffer. 5-47 malloc. 5-5 errno.h header. 5-75 I –i compiler option. 5-8 hyperbolic cosine. 2-25 I/O adding a device. 5-15 identifiers.text. 5-8 setjmp. 5-73 strtoul. 5-6 limits. 2-16 generating symbolic debugging directives. 2-52 implementation-defined behavior. 5-8 stddef. 2-57. 5-48 –heap16 linker option. 2-60. 5-60 stdarg.h header.h header. 5-11 time. B-5 definitions. 5-4–5-12 assert. 4-3 –heap linker option. 5-48 minit. 5-5. B-3 I/O functions. 4-2 . 4-2 . 2-32. 3-18 reserved space. B-9 UNLINK. 5-8 hyperbolic sine.h header. B-10 implementation overview. 5-6 math. 5-11 heap. 6-2 –h linker option. 5-36 free. 5-57. 5-73 generating a preprocessed listing file.h header. B-9 RENAME. 5-44 gets function. 4-4 reserved space. low-level. 5-37 LSEEK.h header. C language. 5-5 file. 5-44 getenv function. 5-10 string.h header. 3-2 –idir compiler option.h header. 5-44 global variables.h header. 5-9 Index-5 . 2-24 hex conversion utility. 2-32 adding a directory to be searched. B-7 OPEN. B-8 READ. 5-9 stdio. 2-24. 2-69 initialized sections. B-2 functions CLOSE.if extension. 5-22 ldiv. 5-31 div. 5-4 ctype. 2-24 header files. 5-22 as intrinsic. 2-56 code generator. 5-45 iscntrl function. 4-22–4-29 asm statement. 3-1–3-25 L –l library build utility option. 2-54 fabs. 6-2 –l linker option. 5-45 isalpha function. 5-6 line and file information. 2-57 invocation. 3-18 _INLINE. 5-6 integer types. 2-24 –c override option.h header. 2-12 – –k library build utility option. 2-64 using with optimizer. 2-54 toieee. 5-45 isgraph function. suppressing. 2-31 linker. 2-67 –cr. 2-34 _ _LINE_ _. C language. 2-24 –f. 2-24 –g. 2-24 . 5-45 isxxx function. 6-2 options. 5-5 integer division. 2-65 options –a. 2-16 compatibility. 5-45 isxdigit function. 1-3. 6-2 limits compiler. 2-54 fast_ftoi. 4-30–4-31 INTERRUPT pragma. 5-45 isprint function. 2-64 options. 2-49. 3-16 intrinsic operators. 2-46 inline assembly construct (asm). 2-59 interrupt handling. 5-2 library build utility. 5-10 libraries. 2-54 ansi_ftoi. 3-18 initializing static variables. 2-57 isalnum function. 2-24 –e. 5-5. 5-45 isdigit function. 2-45 abs. 2-64 library build utility. 2-25. 5-35 interfacing C and assembly language. 4-28 inline functions. C language. 2-49. 6-2 linker. 5-46 ldiv function. 2-68 L_tmpnam macro. 2-62 interlist utility. 2-54 fast_imult. 2-54 ldexp function. 2-57. 3-24–3-25 floating-point types. 2-65 optimizer. 2-60 parser. 2-24 –b. 2-24 –h. 5-6 limits. 2-54 frieee. 5-35 ldiv_t type. 2-3 C compiler tools individually. 2-17 #line directive. 5-45 ispunct function. 4-28 interlist utility.Index initializing global variables. 6-1–6-6 optional object library. 2-54 fast_invf. 5-45 isspace function. 2-24 –c. 5-9 labs function. 5-27 invoking the C compiler. 2-44 input/output definitions. 2-66. 5-45 islower function. 4-28 inline assembly language. 2-40 intermediate file. 5-45 isascii function. 2-65 lnk30 command. 5-45 Index-6 isupper function. 2-54 labs. 2-54 inverse tangent of y/x. 2-24 –ar. 2-31. 5-45 K –k compiler option. 6-2 K&R. 2-20 memchr function. 5-41. 4-4. 2-25 –s. 2-24 –heap8. 5-34 localtime function. 2-20 macro definitions. 5-10 stdout. 5-51 minit8 function. 3-18 local time. 5-51 malloc16 function. 5-51 minit16 function. 5-51 realloc. 2-25 –m. 5-52 log function. 2-21 –mn compiler option. 2-25 –stack. 2-22 multibyte characters. 2-21 –mi compiler option. 5-61 memory model. 5-11. 6-2 mktime function. 2-16 lnk30. 5-8. 2-71–2-75 linking C code. 5-48 malloc8 function. 2-20 –mc compiler option. 5-50 –mf compiler option. 5-48 math. 2-22 –ms compiler option. 5-49 memcmp function. 5-57. 2-65. 2-25 –u.h header. 2-65–2-75 linking with the shell program. 2-25 –z enabling option. 2-25 –r. 5-5 LSEEK I/O function. 5-50 memory management functions bmalloc. 2-22 modf function. 2-21 minit function. 2-65 –mp compiler option. 2-66 loader. 4-6 ROM model. 5-10 MEMORY_SIZE constant. 5-29. 5-10 SEEK_END. 4-4 memset function. 2-34 generating. 5-52 –ml compiler option. 2-25 –o.Index –heap. 2-66 linker command file. 2-31–2-32 macro expansions. 2-66 listing file. 2-25 –v0. 4-2–4-6 dynamic memory allocation. 5-48. 2-22 –mr compiler option. 2-25 –n. 5-10 stdin. 3-2 Index-7 . 5-10 SEEK_SET. 2-25 –ma compiler option. 5-46 log10 function. 5-29 calloc. 2-24 –i. 2-25 –x. 5-48 reserved space. 4-4 RAM model. 4-2 stack. 2-24 –heap16. 2-25 –l. 5-14. 4-6 sections. 5-49 memmove function. 3-5 longjmp function. 5-60 low–level I/O functions. 5-53 modular programming. 5-10 stden. 5-51 mk30. 5-31 free. 5-47 long double data type. 5-49 memcpy function. B-7 ltoa function. 4-4 memory pool. 2-25 –q. 2-22 –mtc compiler option. 5-41 malloc. 5-10 malloc function. 2-21 –mm compiler option. 5-48 minit. 2-22 –mt compiler option. 2-25 –w. 5-47 M –m linker option. 5-15 –mb compiler option. 4-3 MEMORY_SIZE. 2-31–2-32 macros SEEK_CUR. 5-46. 2-59 –pe compiler option. A-1 autoincrement addressing. 2-60 options. 2-16. A-1 algebraic reordering. A-1–A-15 general. 2-27 –oN2 compiler option. A-15 redundant assignment elimination. 5-46 NDEBUG macro. A-12 copy propagation. 2-27 –op2 compiler option. 2-41 using with interlist utility. 2-16. A-9 information file. 2-51. 2-5–2-29 assembler. A-9 control-flow simplification. 2-16. 2-57 options. A-6 optimizer invoking. 2-60 opt30. 2-25. A-15 loop rotation. 2-17. 2-25 natural logarithm. 2-23 code generator. 5-26 non-local jumps. 5-53 –pf parser option. 2-26 –ol0 compiler option. 2-14 general. 2-71 offsetof macro. A-4 returns. 2-26 –ol2 compiler option. 2-4 –o linker option. 2-6 type-checking. 5-9 O . 2-26 TMS320C30-specific. 2-57.obj extension. A-10 constant folding. 3-23 –pl compiler option. 2-18. 5-4. 2-61 parser output. 2-34 –po compiler option. A-12 common subexpression elimination. 2-19 –os compiler option. A-9 alias disambiguation. A-15 loop induction variable optimizations. A-6 repeat blocks. 2-34 . 3-22. A-13 symbolic simplification. A-10 strength reduction. 2-58 parsing in two passes. options. 2-56.o extension. 2-40 options. 2-27 –on optimizer option. A-13 loop invariant code motion. 2-5 file specifiers. 2-34 –pm parser option. 2-27 –op0 compiler option. 2-26 –oi optimizer option. 2-50 P –p? compiler option. 2-17 –pn compiler option. 2-60. 2-60 optimization. 2-63 conventions. 2-27 –op1 compiler option. A-4 delayed branches. 2-26 –ol1 compiler option. 2-26 parser. 2-58 runtime-model. A-4 calls. 2-26 –ol compiler option. 2-52 perror function. 5-9 –oi compiler option. 2-26 –oN optimizer option. 2-66 . 2-16. 5-60 NULL macro. 2-20 summary table. 5-39.Index N –n compiler option. A-9 branch optimizations. 5-41 OPEN I/O function. options. 2-26 –oN0 compiler option. 2-34 parser.opt extension. A-6 cost-based register allocation. A-10 Index-8 inline function expansion. 2-27 open file function. B-8 . 2-12 –n linker option. 2-27 –oN1 compiler option. 2-59 special considerations. 2-27. 2-26 –ol optimizer option. 2-12 optimizer. 2-16. 2-27 library functions. 2-27 –op optimizer option. 2-16 –pk compiler option. 2-14 object libraries. 2-17. 5-59 from string to array. 2-31 TIME. 2-30 C language. 5-27 exit. 2-59 pointer combinations. 3-3 trailing tokens. 3-14 FUNC_IS_SYSTEM. 2-25 –qq compiler option. 5-57 RAND_MAX macro. 5-38 stream functions from standard input. 4-4. 2-31 C40. 2-31–2-32 _BIGMODEL. 5-44 READ I/O function. 2-31 TMS320C44. 5-40 string. 3-15 FUNC_NO_IND_ASG. 2-16 predefining name. 5-54 pragma. 3-16 predefined names. 5-41. 3-2. 2-31 TMS320C40. 2-34 preprocessor. 3-18 preprocess only. 2-31 DATE. 2-30–2-34 environment variable. 2-31 C31. 5-54 program termination functions abort (exit). 5-51. 5-36 prototype listing file. 2-17 preprocessed listing file. 5-42. 2-51 Index-9 . 5-57 ptrdiff_t type. 2-31 C32. 3-23 printf function.Index –po option. 2-12 symbols. 3-16 INTERRUPT. 5-63 read function. 5-58 realloc8 function. 5-10 read character functions multiple characters. 5-54 power. B-9 realloc function. 2-52 Q –q compiler option. 2-31 TMS320C32. 5-59 pow function. 2-31 TMS320C3x. 2-69 rand function. 2-64 –r linker option. 2-25 RAM model of autoinitialization. 5-38 next character function. 2-16 pseudorandom. 2-64 – –q library build utility option. 2-13 –q interlist utility option. . 3-14 FUNC_IS_PURE. 3-22 position file indicator function. 3-3 CODE_SECTION. 2-31 TMS320C30. 5-22 atexit. 3-13 FUNC_EXT_CALLED. 2-31. 2-31 C44. 5-43. 2-31 C30. 2-31 TMS320C4x. 2-31 preprocessor directives. 4-6 RAM model of initialization. 2-46 LINE. 2-31 preinitialized variables. 2-31 C3x. 5-9 putc function. 2-31 STDC. 3-15 FUNC_NEVER_RETURNS. 5-44 single character. 3-13 FUNC_CANNOT_INLINE. 2-31 C4x. 5-55 puts function. 6-2 –q linker option. 2-33 listing file. 3-12 DATA_SECTION. 5-57. 2-3. 2-31 _REGPARM. 5-56 R –r interlist utility option. 5-54 putchar function. 2-31 FILE. 2-13 qsort function. 2-31 _INLINE. 5-61 realloc16 function. 5-58 recoverable errors. 3-15 FUNC_NO_GLOBAL_ASG. 5-55 –pw option. 2-31 TMS320C31. 4-11–4-14 register variables. 5-56 source file extensions assembler files. 2-20 software development tools. 5-1–5-21 summary table. 2-35 rts40gr. 5-62 sqrt function. 4-3 . 5-13–5-21 runtime-support libraries. 2-66 rts40g. 4-3 . 2-35 rts40r. 4-4 RAM model. 2-68. 2-35 rts40. 2-25 scanf function. 2-13. 5-57 –ss compiler option. 3-3 register variables. 5-30 sections. 5-9 small memory model. 5-10 SEEK_SET macro. 5-59 setjmp function. 5-62 srand function. 5-1.data. 2-3–2-4 –i option. 4-6 ROM model.cinit. 4-2 . 4-4 specifying filenames. 2-35. 2-14 sprintf function. 4-28 interfacing C with assembly language. 2-35. 2-13 keeping the assembly language file. 2-15 object files. 5-59 searches. 5-10 set file-position functions fseek function. 4-38 . 5-59 ROM model of autoinitialization. 4-6 sections. 5-61 shell program. 4-2 precision considerations. 5-42 fsetpos function. 4-3 . 2-49. 2-69. 5-62 size_t type. 1-2–1-4 sorts.lib. 5-1 rts. 2-15 SP register. 2-33 C_OPTION environment variable. 4-1–4-40 defining variables in assembly language.sysmem. 2-15 C source files. 4-3 –stack linker option. 2-31 remove function. 4-30–4-31 memory model dynamic memory allocation.lib. 2-4. 4-3 SEEK_CUR macro. 5-58 RENAME I/O function. 5-43 setbuf function.lib. 2-35 runtime environment. 5-10. 3-2. 5-63 stack.lib. 2-69 rts. 2-20 runtime–support libraries. 5-58 rename function. 4-12 register storage class. 5-2 S –s compiler option. 2-28 enabling linking. 4-25 function call conventions.bss. 4-11–4-14 stack.lib. 2-68.lib.text. 2-13. 2-12 shift. 2-12 overview. 2-35 rts30r. 5-10 SEEK_END macro. 4-4 system initialization. 4-12 C language. 2-66 rts30g. 2-66.src. 6-1 runtime-support functions. 4-3 reserved space. 3-10 _REGPARM.Index register conventions. 2-50 sscanf function. 4-6 ROM model of initialization. 4-35 register conventions. 5-2. 2-25 . 5-60 setvbuf function. 2-35 rts30gr. 4-22–4-29 interrupt handling. 4-15–4-21 inline assembly language. 4-3 .stack. 6-1 rts30. 4-36–4-40 runtime-model options.lib.lib. 5-62 square root. B-9 rewind function. 2-50 Index-10 –s linker option.lib. 2-2 suppressing the linking option. 3-3 sinh function. 2-35. 5-10 stdio. 5-75 target processor.h header. 5-65 strerror. 5-72 strstr function.stack section. 2-70 suppress all output except error messages. 5-17 stdout macro. 4-4 . 5-66 strlen. 4-3 T tan function.h header. 5-70 strpbrk function. 5-8. 5-72 strstr. 5-67 strncat function. 5-38 strcat function. 2-13 temporary file creation function. 5-9 stden macro. 5-37 test error function. 5-74 strtol function. 5-73 strtoul function. 5-68 strncmp function. 5-65 strcspn function.h header. 5-66 strftime function. 4-3 STACK_SIZE constant. 5-64 strcoll function. 5-72 strtod function. 5-69 strncpy. 2-31 stddef. 4-3 system constraints MEMORY_SIZE. 5-64 strcmp. 5-63 strchr. 5-37 . 5-64 strcpy function. 4-4 STACK_SIZE. 5-76 tentative definition. 5-49 memcpy. 4-2 Index-11 . 4-37 system stack. 5-71 strspn function. 5-71 strspn.h header. 5-9 stdlib.h header. 2-70. 4-4 system initialization. 5-68 strncmp. 2-13 line and file information.text section. 2-12 . 5-64 strcpy. 2-64 symbolic debugging directives. 3-18 reserved space. 5-11. 4-3 stdarg. 5-74 string. 5-65 strerror function. 5-67 strncat. 5-50 strcat. 2-52 . 5-10. 5-73 structure members. 2-70–2-75 symbolic debugging. 4-36–4-40 autoinitialization. 5-10 store object function.Index stack management. 5-74 STYP_CPY flag. 5-15 _ _STDC_ _. 5-64 strcmp function. 4-4 static variables. 5-10 stdin macro. 5-15 described. 5-64 strcoll. 5-70 strpbrk. 5-65 strcspn. 4-4 stack pointer.switch section. 5-73 strtok function. 5-72 strtok. 5-19 strlen function. 5-19 memchr. 5-49 memmove. 5-71 strrchr. 5-75 tangent. 2-12 suppressing warning messages. 5-49 memcmp. 5-70 string functions. 5-50 memset. 5-69 strncpy function. 5-66 string copy. 3-3 strxfrm function. 2-17 linker option. 2-13 banner information. 5-11. 5-71 strrchr function. 3-23 test EOF function. 5-63 strchr function.sysmem section. 5-75 tanh function. 2-31 TMS320C3x/C4x C language. 5-52 strftime. 5-34 difftime. 2-54 tokens. 5-74 tolower function. 2-31 _TMS320C31. 5-78 va_end. 2-18 trigraph sequences. 5-15 variable-argument function. 5-43 write functions fprintf. 6-3 –v0 linker option. 2-19 –tp. 2-31 _TMS320C44. 2-25 warning messages. 5-66 time. 2-13 – –v library build utility option. B-10 V –v compiler option. 5-11. 2-19 The C Programming Language. 5-11 tm structure. 2-70. 2-31 toascii function. 2-34 Index-12 type-checking. 5-76 toieee intrinsic. 5-76 time functions. 4-3 . 5-46 mktime. 5-11 tm type. 2-29 TMP_MAX macro. 5-79 W –w linker option.Index –tf compiler option. 5-33 ctime. 2-31 time_t type. 5-78 va_end function. 5-79 volatile. 2-31 _TMS320C32. 5-76 time. compatibility with ANSI C language. 5-25 clock. 5-77 –tp compiler option. 3-22–3-23 _TMS320C40. 3-23 translation phases. 5-20 asctime. 5-78 va_start function. 5-40 fputc. 5-40 fputs. 2-28 overriding. 5-77 uninitialized sections. 5-11. 5-9 tmpfile function. 4-3 UNLINK I/O function. 3-1–3-25 time. 3-22 wildcard. 5-78 variable-argument functions and macros va_arg. 5-44 localtime. 2-25 va_arg function. 5-77 toupper function. enumerator list. 2-19 U –u compiler option. 5-78 va_start. 2-19 –tf. 5-8 trigraph expansion. 2-31 _TMS320C3x. 2-4 write block of data function. 5-34 gmtime. See broken-down time TMP environment variable. 5-78 variable argument functions and macros. 2-34 trigonometric math function. 5-76 _TMS320C30. 2-31 _TMS320C4x.h header. 5-25 time function. 2-19 type-checking options. 3-23 trailing tokens. 5-20 _ _TIME_ _. 5-79 vsprintf function. 6-3 –u linker option. 2-19 trailing comma. 5-8.bss. 2-52 warnings messages. 5-78 vfprintf function. 2-41 vprintf function. 5-76 tmpnam function. preprocessor directives. 2-25 ungetc function. 2-13 – –u library build utility option. 2-51 suppressing. pointer combinations. 5-40 . 2-3. 5-79 WRITE I/O function. 2-66 overriding. 5-79 vsprintf. 2-63 –z compiler option.Index printf. 5-54 putchar. 2-28 Index-13 . 2-28. B-10 X –x compiler option. 2-18 –x inlining option. 2-25 Z –z code generator option. 5-55 puts. 5-79 vprintf. 5-77 vfprintf. 2-13. 5-55 sprintf. 5-62 ungetc. 2-65. 5-54 putc. 2-18 –x linker option.
Copyright © 2024 DOKUMEN.SITE Inc.