background image

Function Structure and Calling Conventions

 

6-14

6.3 Function Structure and Calling Conventions

The C compiler imposes a strict set of rules on function calls. Except for special
run-time-support functions, any function that calls or is called by a C function
must follow these rules. Failure to adhere to these rules can disrupt the C envi-
ronment and cause a program to fail.

Figure 6

1 illustrates a typical function call. In this example, parameters are

passed to the function, and the function uses local variables. This example
also shows allocation of a local frame for the called function. Functions that
have 

no

 

arguments passed on the stack 

and no

 

local variables do not allocate

a local frame.

Figure 6

1. Stack Use During a Function Call

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

Caller’s local

frame

SP

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

Push Arguments,

Call Function

Return

address

Allocate

Local Frame

Before

CALL

argument

n

argument

1

FP

Old

FP

SP

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

ÉÉÉÉÉ

FP

SP

FP

Caller’s local

frame

Caller’s local

frame

Argument

n



Argument 1

Argument

n



Argument 1

Return

address

Old FP

Low

High

Local frame

Temporary

location

Summary of Contents for TMS320C2x

Page 1: ...TMS320C2x C2xx C5x Optimizing C Compiler User s Guide Literature Number SPRU024E August 1999 Printed on Recycled Paper...

Page 2: ...ONDUCTOR PRODUCTS MAY INVOLVE POTENTIAL RISKS OF DEATH PERSONAL INJURY OR SEVERE PROPERTY OR ENVIRONMENTAL DAMAGE CRITICAL APPLICATIONS TI SEMICONDUCTOR PRODUCTS ARE NOT DESIGNED AUTHORIZED OR WARRANT...

Page 3: ...e code for the TMS320C2x C2xx C5x devices This user s guide dis cusses the characteristics of the C compiler It assumes that you already know how to write C programs The C Programming Language second...

Page 4: ...y Reference material consisting of Appendix B provides a glossary Notational Conventions This document uses the following conventions Program listings program examples and interactive displays are sho...

Page 5: ...ack cover TMS320C2x User s Guide literature number SPRU014 discusses the hard ware aspects of the C2x fixed point digital signal processors It de scribes pin assignments architecture instruction set a...

Page 6: ...DS board TMS320C5x Software Development System Technical Reference liter ature number SPRU066 provides specific application and design in formation for using the TMS320C5x Software Development System...

Page 7: ...dard for Information Systems Programming Language C X3 159 1989 American National Standards Institute ANSI standard for C Programming in C Kochan Steve G Hayden Book Company Trademarks MS DOS is a reg...

Page 8: ...viii...

Page 9: ...prets Filenames fa fc and fo Options 2 15 2 3 4 Changing How the Shell Program Interprets and Names Extensions ea and eo Options 2 16 2 3 5 Specifying Directories 2 16 2 3 6 Options That Overlook ANSI...

Page 10: ...he opti mizer 3 1 Using the C Compiler Optimizer 3 2 3 2 Using the o3 Option 3 4 3 2 1 Controlling File Level Optimization oln Option 3 4 3 2 2 Creating an Optimization Information File onn Option 3 5...

Page 11: ...in Memory 4 11 4 5 4 A Sample Linker Command File 4 13 5 TMS320C2x C2xx C5x C Language 5 1 Discusses the specific characteristics of the TMS320C2x C2xx C5x C compiler as they relate to the ANSI C spec...

Page 12: ...12 6 2 4 Register Variables 6 12 6 2 5 Expression Registers 6 13 6 2 6 Return Values 6 13 6 3 Function Structure and Calling Conventions 6 14 6 3 1 How a Function Makes a Call 6 15 6 3 2 How a Called...

Page 13: ...7 5 7 2 2 Character Typing and Conversion ctype h 7 5 7 2 3 Error Reporting errno h 7 6 7 2 4 Limits float h and limits h 7 6 7 2 5 Inport Outport Macros ioports h 7 8 7 2 6 Floating Point Math math h...

Page 14: ...ns and dspcl Options 2 42 2 7 Code Generator Options and dspcl Options 2 44 3 1 Options That You Can Use With o3 3 4 3 2 Selecting a Level for the ol Option 3 4 3 3 Selecting a Level for the on Option...

Page 15: ...lacement 3 16 3 2 Delayed Branch Call and Return Instructions 3 17 3 3 Data Flow Optimizations 3 19 3 4 Copy Propagation and Control Flow Simplification 3 20 3 5 Inline Function Expansion 3 22 4 1 An...

Page 16: ...Symbol 4 9 TMS320C2x C2xx C5x Byte Is 16 Bits 5 5 Avoid Disrupting the C Environment With asm Statements 5 9 The Linker Defines the Memory Map 6 2 Stack Overflow 6 5 Using AR6 and AR7 as Global Regis...

Page 17: ...hiver a software simulator a full speed emulator and a software devel opment board This chapter provides an overview of these tools and introduces the features of the optimizing C compiler The assembl...

Page 18: ...ortions represent pe ripheral functions that enhance the development process Figure 1 1 TMS320C2x C2xx C5x Software Development Flow Assembler Linker Macro library Library of object files Hex conversi...

Page 19: ...ex plains how to use the archiver The linker combines object files into a single executable object module As it creates the executable module it performs relocation and resolves external references Th...

Page 20: ...Guide for more information about how to use the absolute lister The cross reference lister uses object files to produce a cross reference listing showing symbols their definitions and their reference...

Page 21: ...onversion timekeeping trigonometry and exponential and hyperbolic functions Functions for I O and signal handling are not included because these are target system specific For more information see Cha...

Page 22: ...iler s optimization techniques see Chapter 3 Optimizing Your Code Code to initialized data into ROM For standalone embedded applications the compiler enables you to link all code and initialization da...

Page 23: ...scription of how to use the dspcl shell to compile assemble and link your programs This chapter also describes the preprocessor inline function expansion fea tures and interlist utility Topic Page 2 1...

Page 24: ...age source code The assembler generates a COFF object file The linker links your files to create an executable object file Use of the linker is optional at this point You can compile and assemble vari...

Page 25: ...er Optimizer optional Code generator Assembler Assembler source COFF object files With the z Option For a complete description of the assembler and the linker see the TMS320C2x C2xx C5x Assembly Langu...

Page 26: ...compiler creates The z option and its associated information linker options and object files must follow all filenames and compiler options on the command line You can specify all other options except...

Page 27: ...module without the q option dspcl symtab symtab TMS320C2x 2xx 5x ANSI C Compiler Version X XX Copyright c 1987 1995 Texas Instruments Incorporated symtab c main symtab c lookup TMS320C2x 2xx 5x ANSI C...

Page 28: ...can be combined For example pe pf and pk can be combined as pefk Options that have parameters such as uname and idirectory cannot be combined They must be specified separately Options with parameters...

Page 29: ...ss messages quiet 2 14 qq Suppresses all messages super quiet 2 14 r register Reserves global register 2 14 s Interlists optimizer comments if available and assembly source statements otherwise interl...

Page 30: ...irectory Specifies assembly file directory 2 17 ftdirectory Override TMP environment variable 2 17 e Options that overlook ANSI C type checking Option Effect Page tf Relaxes prototype checking 2 18 tp...

Page 31: ...el optimization 3 6 pn Suppresses line directives in a pp file 2 26 po Preprocesses only 2 26 pr Generates an error listing 2 37 pw0 Disables all warning messages 2 37 pw1 Enables serious warning mess...

Page 32: ...any source statements from the input file are assembled 2 20 ahifilename Includes filename before any source statements from the input file are assembled 2 20 al Generates an assembly listing file 2 2...

Page 33: ...optimizer that your file does not declare or alter library functions Overrides the ol0 and ol1 options default 3 4 on0 Disables the optimization information file 3 5 on1 Produces an optimization infor...

Page 34: ...Changing the Compiler s Behavior With Options 2 12 os Interlists optimizer comments with assembly state ments 3 13...

Page 35: ...l symbols static 4 6 heap size Sets heap size bytes 4 6 idirectory Defines library search path 4 6 lfilename Supplies library or command filename 4 6 mfilename Names the map file 4 6 n Ignores all fil...

Page 36: ...ebuggers and enables assembly source debugging in the assembler idirectory Adds directory to the list of directories that the compiler searches for include files You can use this option a maximum of 3...

Page 37: ...which interweaves original C source with compiler generated assembly language If the optimizer is invoked on option this option might reorga nize your code substantially For more information see sec...

Page 38: ...can use wildcard characters to compile or assemble multiple files Wild card specifications vary by system use the appropriate form listed in your op erating system manual For example to compile all of...

Page 39: ...e extension are optional You can also write the example above as dspcl earrr eoo fit rrr 2 3 5 Specifying Directories By default the shell program places the object assembly and temporary files that i...

Page 40: ...agree with the default argument promotions which convert float to double and char to int int func old format int func float a char b new format tp Overlooks type checking on pointer combinations This...

Page 41: ...isabled by g If you use the g option to generate symbolic debugging information many code generator optimizations are disabled because they disrupt the debugger mr Lists register use information After...

Page 42: ...tell the assembler to include the specified file for the assembly module The file is included before source file statements The included file does not appear in the assembly listing files al Invokes...

Page 43: ...ng the C_OPTION environment variable If you do this the shell uses the default options and or input filenames that you name with C_OPTION every time you run the shell Setting the default options with...

Page 44: ...about linker options see section 4 4 Linker Options on page 4 6 2 4 2 Specifying a Temporary File Directory TMP The compiler shell program creates intermediate files as it processes your program By de...

Page 45: ...directives specified in the source file as lines beginning with the character The preprocessor produces self explanatory error messages The line number and the filename where the error occurred are pr...

Page 46: ...mpiler searches for the file in the following directories in this order 1 The directory that contains the current source file The current source file refers to the file that is being compiled when the...

Page 47: ...irective without specifying any directory information for the file instead you can specify the directory information with the i option For example assume that a file called source c is in the current...

Page 48: ...on in the output files with input position from the original source files You can use the pn option to suppress line directives See section 2 5 4 2 Remov ing the line Directives From the Preprocessed...

Page 49: ...meaning as defined by the ISO 646 1983 Invariant Code Set On systems with limited character sets these characters cannot be represented For example the trigraph equates to The ANSI C standard defines...

Page 50: ...lled inline expansion is performed when you invoke the compiler with optimization x option and the compiler encounters the inline keyword in code Note Function Inlining Can Greatly Increase Code Size...

Page 51: ...ate command line option this option invokes the optimizer at the default level o2 2 6 3 Using the inline Keyword Definition controlled inline expansion is performed when you invoke the com piler with...

Page 52: ...ontrolled by the oi switch and J The function is declared before it is called A function may be disqualified from inlining if it Returns a struct or union Has a struct or union parameter Has a volatil...

Page 53: ...izer is invoked Using the x2 option automatically invokes the optimizer at the default level o2 Use this syntax to define a function as inline within a module inline return type function name paramete...

Page 54: ..._INLINE preprocessor symbol in your header files in the same way that the function libraries use it so that your programs run regardless of whether inlining is selected for any or all of the modules i...

Page 55: ...d memcpy void _s1 const void _s2 size_t _n if _INLINE Declare the inlined function static inline void memcpy void to const void from size_t n register char rto char to register char rfrom char from re...

Page 56: ...t way to invoke the interlist utility is to use the s option To compile and run the interlist utility on a program called function c enter dspcl s function The s option prevents the shell from deletin...

Page 57: ...of dspcl refer to section 2 9 5 Invoking the Interlist Utility page 2 46 Note Using the s Option With the Optimizer Optimization makes normal source interlisting impractical because the opti mizer ext...

Page 58: ...an cause unex pected results The compiler continues running when this occurs Code E errors are recoverable resulting from a condition that violates the semantic rules of the language Although these ar...

Page 59: ...rating an output file Normally code E F and I errors are fatal while W errors are not The pe option causes the compiler to treat code E errors as warnings so that the compiler generates code for the f...

Page 60: ...c endif If you invoke the compiler with the q option 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 gen...

Page 61: ...ng the Parser on page 2 40 describes how to run the parser The parser in addition can be run in two passes the first pass preprocesses the code and the second pass parses the code The optimizer is an...

Page 62: ...x C program is to invoke the C parser The parser reads the source file performs preprocessing functions checks syntax and produces an intermediate file that can be used as input for the code generator...

Page 63: ...t tf tf Relax prototype checking tp tp Relax pointer combination uname uname Undefine macro name v25 v25 Enable use of TMS320C2x instructions v2xx v2xx Enable use of TMS320C2xx instructions v50 v50 En...

Page 64: ...s 1 Run the parser with the po option specifying preprocessing only dspcl po file c If you want to use the d u or i options use them on this first pass This pass produces a preprocessed output file ca...

Page 65: ...hell options and the corresponding func tions Section 3 1 Using the C Compiler Optimizer on page 3 2 provides a detailed list of the optimizations performed at each level Table 2 6 Optimizer Options a...

Page 66: ...e C code generator The code generator converts the intermediate file pro duced by the parser into an assembly language source file You can modify this output file or use it as input for the assembler...

Page 67: ...d b mb Disable the noninterruptible RPTK instruction for moving structures gregister rregister Reserve global register l ml Disable optimization for reducing LDPK instructions n mn Reenable optimizati...

Page 68: ...less lines lines containing comments and lines containing only or q removes banner and status information r removes symbolic debugging directives The interlist utility uses line directives produced by...

Page 69: ...2 47 C Compiler Description...

Page 70: ...zations are performed when you use it This chapter also describes how you can use the interlist utility with the optimizer and how you can profile or debug optimized code Topic Page 3 1 Using the C Co...

Page 71: ...3 which controls the type and degree of optimiza tion o0 J Performs control flow graph simplification J Allocates variables to registers J Performs loop rotation J Eliminates unused code J Simplifies...

Page 72: ...n J Identifies file level variable characteristics If you use o3 see section 3 2 Using the o3 Option on page 3 4 for more information The levels of optimization described above are performed by the st...

Page 73: ...When you invoke the optimizer with the o3 option some of the optimizations use known properties of the standard library functions If your file redeclares any of these standard library functions these...

Page 74: ...or 2 The resulting file has an nfo extension Use Table 3 3 to select the appropriate level to append to the on option Table 3 3 Selecting a Level for the on Option If you Use this option Do not want...

Page 75: ...tion If a function is not called directly or indirectly the compiler removes the function To see which program level optimizations the compiler is applying use the on2 option to generate an informatio...

Page 76: ...am level optimization altogether Table 3 5 lists the combinations of op levels and conditions that cause the compiler to revert to other op levels Table 3 5 Special Considerations When Using the op Op...

Page 77: ...combination with pm o3 and op1 or op2 If any of the following situations apply to your application use the suggested solution Situation Your application consists of C source code that calls assem bly...

Page 78: ...pm o3 op3 Because you do not use the FUNC_EXT_CALL pragma you must use the op3 op tion which is less aggressive than the op2 option and your optimization may not be as effective Keep in mind that if...

Page 79: ...usually safe to use asm statements to manipulate hardware controls such as interrupt masks but asm statements that attempt to interface with the C environment or access C variables can have unexpected...

Page 80: ...rs point to the same object The compiler assumes that if the address of a local variable is passed to a func tion the function might change the local variable by writing through the pointer This makes...

Page 81: ...imizer multiplies the number of times the function is inlined plus 1 if the function is externally visible and its declara tion cannot be safely removed by the size of the function The optimizer inlin...

Page 82: ...use it might prevent some optimization from crossing C statement boundaries Optimization makes normal source interlisting impractical because the optimizer extensively rear ranges your program Therefo...

Page 83: ...s some optimizations which you cannot selectively enable or disable Following are the optimizations performed by the compiler These optimiza tions improve any C code Optimizations Page Cost based regi...

Page 84: ...dressing modes In many cases where code steps through an array in a loop such as for i 0 i n i a i the loop optimizations convert the array references to indirect references through autoincremented re...

Page 85: ...erate a repeat block Strength reduction turns the array references into efficient pointer autoincrements 3 8 4 Delays Banches Calls and Returns The TMS320C5x provides a number of of delayed branch cal...

Page 86: ...ACC AR2 AR2 i0 SACL AR2 stack ACC CALLD _process begin call LAC AR1 ACC AR2 SACL stack ACC CALL _process OCCURS call occurs SBRK 2 pop stack L2 loop control MAR AR5 AR5 i0 LARK AR5 1 CALLD _input beg...

Page 87: ...wing the compiler to freely opti mize such expressions 3 8 7 Data Flow Optimizations Collectively the following three data flow optimizations replace expressions with less costly ones detect and remov...

Page 88: ...ed sign extension for right shift LAC 12 AR1 high ACC j 3 ADD 15 add TOS to high ACC SACH 1 AR2 stack high ACC LAC 3 AR1 ACC j 3 SACL AR2 stack ACC ADRK 4 LF1 AR2 b LAC AR1 ACC b SACL stack ACC CALLD...

Page 89: ...ced to conditional instruc tions totally eliminating the need for branches See Example 3 4 Example 3 4 Copy Propagation and Control Flow Simplification fsm enum ALPHA BETA GAMMA OMEGA state ALPHA int...

Page 90: ...riable analysis and strength reduction together often remove all references to your loop control variable allowing it to be eliminated entirely See Example 3 1 and Example 3 5 3 8 10 Loop Rotation The...

Page 91: ...L 1 LARK AR2 3 LF1 AR2 ps MAR 0 LAR AR6 AR6 ps AR2 pt LAR AR5 AR5 AR5 pt LACK 11 SAMM BRCR repeat 12 times RPTB L4 1 LAC AR6 ps pt SACL AR5 NOP must have 3 words in repeat block L4 The compiler finds...

Page 92: ...how to invoke the linker with each method It also discusses special requirements of linking C code including the run time sup port libraries specifying the type of initialization and allocating the pr...

Page 93: ...ASCII file that contains linker commands The default output file name is a out unless you use the o option to name the output file options affect how the linker handles your object files Options can a...

Page 94: ...program consisting of modules prog1 prog2 and prog3 the output file is named prog out enter dsplnk c prog1 prog2 prog3 o prog out l rts25 lib The linker uses a default allocation algorithm to allocat...

Page 95: ...ith the C_OPTION environment variable All arguments that follow z on the command line are passed on to the linker These arguments can be linker command files additional object files linker options or...

Page 96: ...variable and want to selectively disable linking with the c option on the command line The c linker option has a different function than and is independent of the c shell option By default the compile...

Page 97: ...Defines global_symbol as global even if the global sym bol has been made static with the h linker option h Makes all global symbols static heap size Sets heap size for dynamic memory allocation to si...

Page 98: ...e stack size Sets the C system stack size to size words and defines a global symbol that specifies the stack size Default is 1K words u symbol Places the unresolved external symbol symbol into the out...

Page 99: ...an archive path or object file To use the l linker option type on the com mand line dsplnk c cr filenames l libraryname Generally you should specify the library as the last name on the command line b...

Page 100: ...autoinitializes global variables when using the c option 3 Calls main 4 Calls exit when main returns Chapter 7 describes additional run time support functions that are included in the library These fu...

Page 101: ...y The cinit output section is padded with a termination record so that the loader load time initialization or the boot routine run time initialization knows when to stop reading the initialization tab...

Page 102: ...d switch Jump tables for large switch statements text Executable code and floating point constants b Uninitialized sections Name Contents bss Global and static variables stack Software stack sysmem Dy...

Page 103: ...ection type requires Section Type of Memory Page text ROM or RAM 0 cinit ROM or RAM 0 const ROM or RAM 1 switch ROM or RAM 0 bss RAM 1 stack RAM 1 sysmem RAM 1 For more information about allocating se...

Page 104: ...p file o example out Output file name main obj First C module sub obj Second C module asm obj Assembly language module l rts25 lib Runtime support library l matrix lib Object library MEMORY PAGE 0 PRO...

Page 105: ...ded This program uses several routines from an archive library called matrix lib so it is also named as linker input Note that only the library members that resolve undefined references are linked To...

Page 106: ...ational Standard for Information Sys tems Programming Language C X3 159 1989 The second edition of The C Programming Language is based on the ANSI standard ANSI C encom passes many of the language ext...

Page 107: ...tifiers are significant Case is significant uppercase and lowercase characters are distinct for identifiers These characteristics apply to all identifiers internal and external ANSI 3 1 2 K R A2 3 The...

Page 108: ...SI 3 3 7 K R A7 8 5 1 5 Declarations The register storage class is effective for all character short integer and pointer types ANSI 3 5 1 K R A8 1 Structure members are not packed into words with the...

Page 109: ...notation The type char is a signed type equivalent to int Objects of type enum are represented as 16 bit values the type enum is equivalent to int in expressions All floating point types float double...

Page 110: ...s TMS320C2x C2xx C5x 1 19209290e 38 3 4028235e 38 long double 32 bits TMS320C2x C2xx C5x 1 19209290e 38 3 4028235e 38 pointers 16 bits binary 0 0xFFFF Many of the range values are available as standar...

Page 111: ...assigned to the first register variable AR7 is assigned to the second variable The address of the variable is placed into the allocated register to simplify access Thus 16 bit types char short int an...

Page 112: ...any declaration definition or reference to the func orsym bol argument If you do not follow these rules the compiler issues a warning 5 4 1 The CODE_SECTION Pragma The CODE_SECTION pragma allocates s...

Page 113: ...the pm option the compiler uses program level optimization When you use this type of optimization the compiler removes any function that is not called directly or indirectly by main You might have C f...

Page 114: ...a label a blank a tab or a comment asterisk or semicolon The compiler performs no checking on the string if there is an error the assembler detects it For more information about the assembly language...

Page 115: ...variable normally for example register struct data_struct AR6 define data_pointer AR6 data_pointer element data_pointer 5 6 1 When to Use a Global Register Variable There are two reasons that you woul...

Page 116: ...value in the register is corrupted You must save the global register on entry into a module that uses it and you must restore the register at exit The longjmp function restores global register variabl...

Page 117: ...file this method can have the unwanted effect of significantly increasing the size of the output file 5 7 1 Initializing Static and Global Variables With the const Type Qualifier Static and global var...

Page 118: ...rations of port variables must be done at the file level Port variables declared at the function level are not supported For example the following code declares the I O port as unsigned port 10h write...

Page 119: ...ations or preprocessor constructs Instead pk simply liberalizes the ANSI rules without revoking any of the features The specific differences between the ANSI version of C and the K R version of C are...

Page 120: ...t K R compilers this sequence is illegal because a is defined twice ANSI prohibits but K R allows objects with external linkage to be redeclared as static extern int a static int a illegal unless pk u...

Page 121: ...id exceeding a compiler limit Many compiler tables have no absolute limits and are limited only by the amount of memory available in the host system Table 5 2 specifies the limits that are absolute Al...

Page 122: ...ype 12 derivations Aggregate initialization nesting 32 levels Static initializers 1500 per initialization approximately Local initializers 150 levels approximately Nesting of if statements switch stat...

Page 123: ...ers Notes 1 This limit reflects the number of characters after splicing of lines This limit also applies to any single macro definition or invocation 2 This limit reflects the number of characters bef...

Page 124: ...lso important to follow the guidelines in this chapter if you write assembly language functions that interface with C code Topic Page 6 1 Memory Model 6 2 6 2 Register Conventions 6 9 6 3 Function Str...

Page 125: ...d data into target memory The compiler assumes nothing about the types of memory available about any locations not available for code or data holes or about any locations reserved for I O or control p...

Page 126: ...switch statements Uninitialized sections reserve space in memory usually RAM A program can use this space at run time for creating and storing variables The compiler creates the following uninitialize...

Page 127: ...pe requires Section Type of Memory Page text ROM or RAM 0 cinit ROM or RAM 0 switch ROM or RAM 0 const ROM or RAM 1 bss RAM 1 stack RAM 1 sysmem RAM 1 For more information about allocating sections in...

Page 128: ...the actual address of the stack is determined at link time If you allocate the stack as the last section in memory highest address the stack has unlimited space for growth within the limits of system...

Page 129: ...manner To change any of the names you must edit boot asm and change the names in the same way 6 1 4 Dynamic Memory Allocation Dynamic memory allocation is not a standard part of the C language The ru...

Page 130: ...data from these tables in ROM to the initialized variables in bss RAM In situations where a program is loaded directly from an object file into memory and run you can avoid having the cinit section oc...

Page 131: ...1 In an expression For example strcpy s abc When a string is used in an expression the string itself is defined in the const section with the string assembler directive along with a unique label that...

Page 132: ...riable registers is the method by which they are preserved across calls It is the called function s responsibility to preserve save on entry register variables and the calling function s responsibilit...

Page 133: ...ter Yes AR2 Local variable pointer No AR2 AR5 Expression analysis No AR6 AR7 Register variables Yes Accumulator Expression analysis return values No P Expression analysis No T Expression analysis No b...

Page 134: ...Field Name Presumed Value Modified BRAF Block repeat active flag Yes NDX Index register enable bit 0 No TRM Enable multiple TREGs 0 No 6 2 2 Stack Pointer Frame Pointer and Local Variable Pointer The...

Page 135: ...f the status register PMST is 0 which means that changes to the register AR0 are shad owed in INDX This also means that the INDX register must be preserved across calls just as AR0 is For code executi...

Page 136: ...on specific registers allocated to specific variables Note Using AR6 and AR7 as Global Register Variables If you have disabled the compiler from using AR6 and AR7 with the r option AR6 and AR7 are not...

Page 137: ...n call In this example parameters are passed to the function and the function uses local variables This example also shows allocation of a local frame for the called function Functions that have no ar...

Page 138: ...struction SBRK n n is the number of argument words that were pushed 6 3 2 How a Called Function Responds A called function child function must perform the following tasks On function entry the ARP is...

Page 139: ...e allocate frame SAR AR6 push AR6 SAR AR7 push AR7 code for the function MAR AR1 set ARP SP MAR point to saved AR7 LAR AR7 pop AR7 LAR AR6 pop AR6 SBRK SIZE 1 deallocate frame point to saved FP LAR AR...

Page 140: ...declare functions that return structures both at the point where they are called so the caller passes the address of the return space as the last argument and where they are defined so the function k...

Page 141: ...ware stack RETD return delayed LAR AR0 restore FP NOP fill delay slots of RETD If the return address is not saved on the stack which means a PSHD will not be generated the RETD will be moved two words...

Page 142: ...s straightforward if you follow the calling conventions defined in section 6 3 Function Structure and Calling Conventions on page 6 14 and the register conventions defined in section 6 2 Register Conv...

Page 143: ...values in the accumulator 16 bit integer values and pointers must be loaded in the accumulator with proper sign extension No assembly module should use the cinit section for any purpose other than aut...

Page 144: ...P LARK AR0 1 Size of frame LAR AR0 0 AR2 Set up FP and SP LDPK _gvar Point to gvar SSXM Set sign extension LAC _gvar Load gvar LARK AR2 3 Offset of argument MAR 0 Point to argument ADD AR0 Add arg to...

Page 145: ...n you use the asm statement be careful not to disrupt the C environment The compiler does not check or analyze the inserted instructions Inserting jumps or labels into C code may produce unpredictable...

Page 146: ...n bss From C a C program extern int var External variable var 1 Use the variable b Assembly language program Note the use of underscores in the following lines bss _var 1 Define the variable global _v...

Page 147: ...a separate section _sine The table starts here float 0 0 float 0 015987 float 0 022145 6 4 4 Modifying Compiler Output You can inspect and change the assembly language output produced by the compiler...

Page 148: ...ting local variables and calling other functions When an interrupt routine is entered the run time support function I SAVE is called to save the complete context of the interrupted function All regist...

Page 149: ...must be of type void and it should be declared with no arguments The compiler does not save all the device registers The compiler saves only those registers listed in Table 6 1 You must handle any spe...

Page 150: ..._int0 6 5 4 TMS320C5x Shadow Register Capability The TMS320C5x device automatically saves certain registers upon an inter rupt trap in a set of internal shadow registers See the TMS320C5x User s Guide...

Page 151: ...ot portable 6 6 2 Integer Division and Modulus The TMS320C2x C2xx C5x does not directly support integer division so all division and modulus operations are performed through calls to run time sup port...

Page 152: ...access to the upper 16 bits of a 16 bit multiply in C language For example Signed results intm1 m2 intresult result long m1 long m2 16 Unsigned results unsigned m1 m2 unsigned result result unsigned l...

Page 153: ...ivision Comparisons Conversions from integer or long to floating point and floating point to inte ger or long both signed and unsigned Standard error handling These functions do not follow standard C...

Page 154: ...utput module to the symbol _c_int0 This does not however set the hardware to automatically vector to c_int00 at reset see the The c_int0 function performs the following tasks to initialize the environ...

Page 155: ...and line and specifying the stack size as a constant directly after the option 6 8 2 Automatic Initialization of Variables Some global variables must have initial values assigned to them before a C pr...

Page 156: ...ariable 2 The second field word 1 contains the starting address of the area within the bss section where the initialization data must be copied 3 The third field words 2 through n contains the data th...

Page 157: ...use this method invoke the linker with the c option Using this method the cinit section is loaded into memory along with all the other initialized sections The linker defines a special symbol called...

Page 158: ...o 1 normally cinit points to the beginning of the initialization tables This indicates to the boot routine that the initialization tables are not present in memory accordingly no run time initializati...

Page 159: ...6 36...

Page 160: ...ocal language nationality or culture Using the ANSI standard library ensures a consistent set of functions that provide for greater portability In addition to the ANSI specified functions the TMS320C2...

Page 161: ...library as one of the linker input files so that references to the I O and run time support functions can be resolved You should specify libraries last on the linker command line because the linker se...

Page 162: ...rts25 lib For more information about the archiver see the TMS320C1x C2x C2xx C5x Assembly Language Tools User s Guide 7 1 3 Building a Library With Different Options You can create a new library from...

Page 163: ...t first use the include preprocessor directive to include the header file that declares the function For example the isdigit function is declared by the ctype h header Before you can use the isdigit f...

Page 164: ...h The ctype h header declares functions that test type and convert characters The character typing functions test a character to determine whether it is a letter a printing character a hexadecimal dig...

Page 165: ...umeric representations Table 7 1 and Table 7 2 list these macros and their limits Table 7 1 Macros That Supply Integer Type Range Limits limits h Macro Value Description CHAR_BIT 16 Maximum number of...

Page 166: ...LDBL_MAX_EXP 128 Maximum integer such that FLT_RADIX raised to that power is a representative finite float double or long double FLT_EPSILON DBL_EPSILON LDBL_EPSILON 1 19209290E 07F Minimum positive...

Page 167: ...ction that reads an int from the specified port and returns the value the function follows this syntax _in_port int port _out_port a function that writes the output to the specified port and has no re...

Page 168: ...Nonlocal Jumps setjmp h The setjmp h header defines a type and a macro and declares a function for bypassing the normal function call and return discipline These include jmpbuf an array type suitable...

Page 169: ...offsetof type identifier a macro that expands to an integer that has type size_t The result is the value of an offset in bytes to a structure member identifier from the beginning of its structure typ...

Page 170: ...inated with a 0 null character The string functions named strxxx all operate according to this convention Additional functions that are also declared in string h allow you to perform corresponding ope...

Page 171: ...nt tm_mon months since January 0 11 int tm_year years since 1900 0 99 int tm_wday days since Saturday 0 6 int tm_yday days since January 1 0 365 int tm_isdst Daylight Saving Time flag tm_isdst can hav...

Page 172: ...Most of the functions described are per the ANSI standard and behave exactly as described in the standard The functions and macros listed in Table 7 3 are described in detail in section 7 4 Descripti...

Page 173: ...ests c to see if it is any printing character except a space 7 35 int islower int c Tests c to see if it is a lowercase alphabetic ASCII charcter 7 35 int isprint int c Tests c to see if it is a print...

Page 174: ...pport Functions c Inport outport macros ioports h Macro Description Page int inport int port int ret Returns a value from the specified port via the point er ret 7 34 void outport int port int value W...

Page 175: ...x Returns the largest integer x expands inline if x is used 7 32 double fmod double x double y Returns the exact floating point remainder of x y 7 32 double frexp double value int exp Returns f and e...

Page 176: ...absolute value of val expands inline unless x0 is used 7 21 int atexit void fun void Registers the function pointed to by fun called without arguments at program termination 7 24 double atof const ch...

Page 177: ...44 void srand unsigned int seed Resets the random number generator 7 44 double strtod const char st char endptr Converts a string to a floating point value 7 56 long strtol const char st char endptr i...

Page 178: ...t are not in chs 7 49 char strerror int errno Maps the error number in errno to an error mes sage string 7 50 size_t strlen const char string Returns the length of a string 7 51 char strncat char dest...

Page 179: ...e time_t time1 time_t time0 Returns the difference between two calendar times 7 29 struct tm gmtime const time_t timer Converts local time to Greenwich Mean Time 7 33 struct tm localtime const time_t...

Page 180: ...ed as follows void abort exit 0 This makes the abort function equivalent to the exit function Absolute Value abs labs Syntax include stdlib h int abs int j long int labs long int k Defined in abs c in...

Page 181: ...me c in rts src Description 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 F...

Page 182: ...fined NDEBUG as a macro name when the assert h header is included in the source file then the assert macro is defined to have no effect If NDEBUG is not defined when assert h is included the assert ma...

Page 183: ...o determine the quadrant of the return value Both argu ments cannot be 0 The return value is an angle in the range radians Example atan2 1 0 1 0 returns 4 atan2 1 0 1 0 returns 3 4 atan2 1 0 1 0 retur...

Page 184: ...ign digits The atol function converts a string to a long integer Argument st points to the string the string must have the following format space sign digits The space is indicated by a space characte...

Page 185: ...he function returns a pointer to the matching member of the array if no match is found the function returns a null pointer 0 Argument compar points to a function that compares key to the array ele men...

Page 186: ...d sysmem in memory c The constant __SYSTEM_SIZE defines the heap as 1K words You can change this amount at line time by invoking the linker while the _heap option and specifying the desired size of th...

Page 187: ...st write your own clock function You must also define the CLOCKS_PER_SEC macro accord ing to the units of your clock so that the value returned by clock number of clock ticks can be divided by CLOCKS_...

Page 188: ...pointed to by timer to local time in the form of a string This is equivalent to asctime localtime timer The function returns the pointer returned by the asctime function For more information about th...

Page 189: ...ot quotient int rem remainder div_t The ldiv function performs long integer division The input arguments are long integers the function returns the quotient and the remainder in a structure of type ld...

Page 190: ...TMS320C2x C2xx C5x implementation of the abort function makes it equivalent to the exit function Exponential exp Syntax include math h double exp double x Defined in exp c in rts src Description The e...

Page 191: ...s the exact floating point remainder of x divided by y If y 0 the function returns 0 Example double x y r x 11 0 y 5 0 r fmod x y fmod returns 1 0 Deallocate Memory free Syntax include stdlib h void f...

Page 192: ...If value is 0 both parts of the result are 0 Example double fraction int exp fraction frexp 3 0 exp after execution fraction is 75 and exp is 2 Greenwich Mean Time gmtime Syntax include time h struct...

Page 193: ...s you cannot use them in expressions This is an example of the incorrect use of the macro call inport 1 i Incorrect use of macro Instead the macro must be used as below inport 1 i call i Correct use T...

Page 194: ...isdigit is true isalpha identifies alphabetic ASCII characters tests for any character for which islower or isupper is true isascii identifies ASCII characters characters 0 127 iscntrl identifies cont...

Page 195: ...ouble result result ldexp 1 5 5 result is 48 0 result ldexp 6 0 3 result is 0 75 See div ldiv on page 7 30 ldiv Local Time localtime Syntax include time h struct tm localtime const time_t timer Define...

Page 196: ...g10 function returns the base 10 logarithm of a real number x A domain error occurs if x is negative a range error occurs if x is 0 Example float x y x 10 0 y log x Return value 1 0 See setjmp longjmp...

Page 197: ...pecifying the desired size of the heap directly after the option For more information see section 6 1 4 Dynamic Memory Allocation on page 6 6 Example This example allocates free space for a structure...

Page 198: ...emcpy void s1 const void s2 size_t n Defined in memcpy c in rts src Description The memcpy function copies n characters from the object that s2 points to into the object that s1 points to If you attem...

Page 199: ...nction resets all the space that was previously allocated by calls to the malloc calloc or realloc functions The memory that minit uses is in a special memory pool or heap The constant __SYSTEM_SIZE d...

Page 200: ...nal value of tm_mday is not sent until tm_mon and tm_year are determined The return value is encoded as a value of type time_t If the calendar time cannot be represented the function returns the value...

Page 201: ...integer part as a double at the object pointed to by iptr Example double value ipart fpart value 3 1415 fpart modf value ipart After execution ipart contains 3 0 and fpart contains 0 1415 Raise to a P...

Page 202: ...ent compar points to a function that compares key to the array ele ments The comparison function should be declared as int cmp ptr1 ptr2 void ptr1 ptr2 The cmp function compares the objects that ptr1...

Page 203: ...rts src Description The realloc function changes the size of the allocated memory pointed to by packet to the size specified in bytes by size The contents of the memory space up to the lesser of the o...

Page 204: ...the longjmp function the setjmp macro re turns a nonzero value The longjmp function restores the environment that was saved in the jmp_buf argument by the most recent invocation of the setjmp macro If...

Page 205: ...lude math h double sinh double x Defined in sinh c in rts src Description The sinh function returns the hyperbolic sine of a floating point number x A range error occurs if the magnitude of the argume...

Page 206: ...copy of string2 including a terminating null character to the end of string1 The initial character of string2 overwrites the null character that originally terminated string1 The function returns the...

Page 207: ...g Compare strcmp strcoll Syntax include string h int strcoll const char string1 const char string2 int strcmp const char string1 const char string2 Defined in strcmp c in rts src Description The strcm...

Page 208: ...memory locations In the comments the notation 0 represents the null character char a The quick black fox char b jumps over a The quick black fox 0 b jumps over 0 strcpy a b a jumps over 0 b jumps ove...

Page 209: ...charac ters can be written to out The format parameter is a string of characters that tells the strftime function how to format the time the following list shows the valid characters and describes wha...

Page 210: ...ring In C a character string is termi nated by the first byte with a value of 0 a null character The returned result does not include the terminating null character The strlen function is expand ed in...

Page 211: ...not like 0 b Sam I am 0 c I do not like green eggs and ham 0 Compare Strings strncmp Syntax include string h int strncmp const char string1 const char string2 size_t n Defined in strncmp c in rts src...

Page 212: ...ains a leading space to make it five characters long Also note that the first five characters of strc are an I a space the word am and another space so that after the second execution of strncpy stra...

Page 213: ...ave char a a strpbrk stra strb After this example a points to the w in wasn t Find Last Occurrence of a Character strrchr Syntax include string h char strrchr const char string int c Defined in strrch...

Page 214: ...th length strcspn stra strb length 3 length strcspn stra strc length 0 Find Matching String strstr Syntax include string h char strstr const char string1 const char string2 Defined in strstr c in rts...

Page 215: ...unction returns the converted string if the original string is empty or does not have the correct format the function returns a 0 If the converted string would cause an overflow the function returns H...

Page 216: ...strtok function Example After the first invocation of strtok in the example below the pointer stra points to the string excuse 0 because strtok has inserted a null character where the first space use...

Page 217: ...The time function determines the current calendar time represented in sec onds since 12 00 A M Jan 1 1900 If the calendar time is not available the function returns 1 If timer is not a null pointer th...

Page 218: ...ified in the field and the field padded with 0s or blanks depending on whether 0 is used as above s d specifies the argument s type An s indicates that the argument is of type char a d indicates that...

Page 219: ...void va_start ap parmN va_list ap Defined in stdarg h as macros Description Some functions are called with a varying number of arguments that have vary ing types Such a function called a variable argu...

Page 220: ...ent after va_start and va_arg are used You must call va_start to initialize ap before calling va_arg or va_end Example int printf char fmt va_list ap va_start ap fmt Get next arg an integer i va_arg a...

Page 221: ...n individual run time support libraries this package includes the source file rts src that contains all run time support functions You can build your own run time support libraries by using the dspmk...

Page 222: ...nd that invokes the utility options affect how the library build utility treats your files Options can ap pear anywhere on the command line or in a linker command file Options are discussed in section...

Page 223: ...to install the run time support header files from the rts src archive that is shipped with the tools k Overwrite files By default the utility aborts any time it attempts to create an object file when...

Page 224: ...presses warning messages p Enables trigraph expansion c Options that control the optimizer Option Effect o0 Compiles with optimization register optimization o1 Compiles with optimization local optimiz...

Page 225: ...licon bugs f Options that overlook type checking Options Effect tf Overlooks relax prototype checking tp Overlooks relax pointer combination checking g Options that control the assembler Option Effect...

Page 226: ...8 6...

Page 227: ...dual files into a single file called an archive library With the archiver you can add delete extract or replace members of the archive library assembler A software program that creates a machine langu...

Page 228: ...s also 16 bits This yields results you may not expect for example sizeof int 1 not 2 TMS320C2x C2xx C5x bytes and words are equivalent 16 bits C C compiler A software program that translates C source...

Page 229: ...memory allocation A technique used by several functions such as malloc calloc and realloc to dynamically allocate memory for vari ables at run time This is accomplished by defining a large memory pool...

Page 230: ...cessed in another or accessed in the current module but defined in another H hex conversion utility A utility that converts COFF object files into one of several standard ASCII hexadecimal formats sui...

Page 231: ...tatement A label is the only assembler statement that can begin in column 1 linker A software program that combines object files to form an object mod ule that can be allocated into system memory and...

Page 232: ...quest additional or specific functions when you invoke a software tool output module A linked executable object file that is downloaded and executed on a target system output section A final allocated...

Page 233: ...A portion of a COFF object file that contains information about a section in the file Each section has its own header the header points to the section s starting address contains the section s size et...

Page 234: ...MS320C2x TMS320C2xx or TMS320C5x based system into which executable object code is loaded text section One of the default COFF sections The text section that is ini tialized contains executable code Y...

Page 235: ...spmk command library build utility dspopt command optimizer common object file format COFF diagnostic messages NDEBUG macro NDEBUG macro environment variable C_DIR environment variable C_OPTION enviro...

Page 236: ...FP register pointer frame frame pointer pointer stack SP register pointer stack stack pointer string constants constants string sprintf function ti_sprintf function system stack stacks time functions...

Page 237: ...ler option 2 19 append file contents to command line ar linker option 4 6 AR0 FP 6 4 AR1 SP 6 4 6 32 AR6 5 11 6 13 AR7 5 11 6 13 arc cosine 7 21 arc sine 7 21 arc tangent 7 23 archive library linking...

Page 238: ...shell and linker options differ 4 5 C preprocessor 2 22 C source statements and assembly language 2 33 _c_int00 described 4 10 C_OPTION environment variable 2 20 calendar time 7 11 7 28 7 40 7 57 cal...

Page 239: ...in 5 15 floating point maximum number of unique 5 18 string 5 2 escape sequences in 5 15 maximum number of unique 5 18 conversions 5 3 7 5 C language 5 2 copy file ahc assembler option 2 19 cos funct...

Page 240: ...F 2 35 code I 2 35 code W 2 35 general 2 35 error options 2 37 error reporting 7 6 errors treated as warnings 2 36 escape sequences 5 2 5 15 exit function 7 20 7 23 7 30 exp function 7 30 exponential...

Page 241: ...shell option 2 16 FUNC_EXT_CALLED pragma described 5 8 use with pm option 3 8 function alphabetic reference 7 20 call 6 15 conventions 6 14 to 6 18 using the stack 6 4 general utility 7 16 inlining 2...

Page 242: ...clude preprocessor directive 7 4 INDX register 6 12 shadow register capability 6 27 initialization at load time 6 35 of variables 6 7 types 4 9 initialization tables 6 33 initialized sections 6 3 allo...

Page 243: ...library build utility option 8 2 l linker option 4 2 4 8 label retaining 2 19 labs function 7 20 expanding inline 2 28 ldexp function 7 35 ldiv function 7 29 ldiv_t type 7 10 libraries 7 2 library bui...

Page 244: ...unction 7 38 memmove function 7 38 memory data 6 2 program 6 2 memory management functions calloc 7 26 free 7 31 malloc 7 37 minit 7 39 realloc 7 43 7 45 memory model 6 2 to 6 8 allocating variables 6...

Page 245: ...s 3 2 list of 3 14 to 3 22 program level 3 6 optimized code debugging 3 13 optimizer 1 3 2 41 to 2 43 and interrupts 3 11 invoking 2 41 invoking with shell options 3 2 options 2 42 parser output 2 42...

Page 246: ...mum number of 5 17 pseudorandom 7 43 ptrdiff_t 5 2 ptrdiff_t type 7 10 pw parser option 2 36 Q q library build utility option 8 3 q interlist option 2 45 q linker option 4 7 q shell option 2 5 2 13 qq...

Page 247: ...13 S s extension 2 15 s linker option 4 7 s shell option 2 14 2 33 searches 7 25 sections 6 3 allocating memory 4 11 bss 6 3 cinit 6 4 6 33 created by the compiler 4 11 data 6 3 stack 6 3 sysmem 6 3 t...

Page 248: ...nction 7 53 strspn function 7 54 strstr function 7 54 strtod function 7 55 strtok function 7 56 strtol function 7 55 strtoul function 7 55 structure members 5 3 structure packing 6 8 structures nestin...

Page 249: ...on 7 59 trailing comma enumerator list 5 15 trailing tokens preprocessor directives 5 15 translation phases 2 25 trigonometric math function 7 9 trigraph sequences 2 25 type checking overlooking 2 17...

Page 250: ...Index Index 14 Z z shell option 2 2 2 4 2 14 overriding with c option 4 5 overriding with n option 2 13...

Reviews: