Home
DSP56KCC User's Manual
Contents
1. w MOTOROLA DSP56KCC User s Manual A 75 mblen mblen EXAMPLE include lt stdio h gt include lt stdlib h gt char gstr NULL void main int max MB CUR MAX char strnull gstr char str1 709 printf mblen strnull 5 d n mblen strnull 5 printf mblen str1 max d n mblen str1 max printf mblen Wabcdef 5 d n mblen abcedf 5 printf mblen abcdef 2 d n mblen abcedf 2 prints to standard output mblen strnull 5 3 mblen str1 5 3 mblen abcdef 5 3 mblen abcdef 2 2 A aO O A 76 DSP56KCC User s Manual MOTOROLA mbstowcs mbstowcs NAME mbstowcs Convert multibyte string to wide character string SYNOPSIS include lt stdlib h gt int mbstowcs wchar_t pwcs const char s size tn DESCRIPTION The mbstowcs function converts the character string pointed to by s into a wide character string pointed to by pwcs Each character of the multibyte string is converted as if by the mbtowc function At most n characters will be converted and stored in the wide character string Multibyte characters that follow a NULL character will not be examined or converted If s and pwcs overlap the behavior is undefined If an invalid character is encountered mbstowcs returns size t 1 Otherwise mbstowcs returns the number of characters converted not including the terminating NULL character
2. 00 0 eee eee B 5 B 3 5 Object FilesCOnuOls sestien riran E eke eh eM ols ANA B 5 B 3 6 Macros and Conditional Assembly 02 0e0 eee ee B 5 B 3 7 Structured Prodramming 4 seus Gas ne pP EPIS e B 6 Appendix C Utilities asm56000 Motorola DSP56000 DSP56001 COFF Assembler C 2 cldinfo Memory size information from Motorola DSP COFF object file C 7 cldlod Motorola COFF to LOD Format converter coooo o oooo C 8 cofdmp Motorola DSP COFF File Dump Utility C 9 dsplib Motorola DSP COFF Libratiatiesc 25400 a ore es C 10 dsplnk Motorola DSP COFF Linker 00 000005 C 12 gdb56 GNU Source level Debugger for DSP56000 DSP56001 C 17 run56 Motorola DSP56000 DSP56001 Simulator Based Execution Device C 19 srec Motorola DSP S Record Conversion Utility C 20 iV DSP56KCC User s Manual MOTOROLA Table of Contents Continued Paragraph Page Number Title Number Appendix D GNU Debugger GDB o O E 1 Commands Not Implemented ooocccococcoccc ees E 1 DSP56000 Family Differences Specific Requirements o o ooooooooo E 1 Sl AA A O A ta Leib E Ran E 3 GNEEGENERADPUBEIG EIGENSE 2 20 es utis atin bate ce E a E 4 Preamble nececito aaa l ene ee ee as eee eee E 4 TERMS AND CONDITIONS S 50 eto o Ped e eR RO dha ne EA E 5 NO WARRANIY s oro eR nog Re hg ANA ni ear ada Ep XI CR E 7
3. int volatile i 0 j 1 The example above generates code to initialize variables i and j even though they are not used anywhere else Without the key word volatile the optimizing C compiler will eliminate the two local variables because they are not referenced anywhere in the main function 4 11 5 Tail Merging When two or more conditional blocks of code have similar ending sequences the sections of code are rewritten to generate similar code only once _ __ __ __ _z gt gt gt gt ___ __________ 4 16 DSP56KCC User s Manual MOTOROLA This is a space saving optimization technique For example if a gt b if a gt b b a becomes b a func a else func a func a 4 11 6 Strength Reduction Strength reduction replaces expensive operators with less expensive operators This optimization method is very machine specific For instance a popular strength reduction for many compilers is to replace a multiplication by a constant with a series of shifts additions and subtractions The exact opposite is the case on the DSP56000 DSP56001 however since a series of left shifts is replaced with a single multiply by a constant power of 2 4 11 7 Loop Invariant Code Motion Loop Invariant Code Motion is a method in which all C expressions that yield the same result each time through the loop are moved outside of the loop and are executed once prior to entering the loop
4. C gt g56k DDSP56000 dsp c Cri a cld dsp c C gt run56 a cld message DSP56000 C gt g56k dsp c Geya des a cld dsp c OIN rumbo anclada message DSP56001 rn A MOTOROLA DSP56KCC User s Manual 3 7 Preprocessor Phase Options DMACRO DEFN Define preprocessor macro MACRO as DEFN Example 3 10 The program dsp c uses the macro FROM_COMMAND_LINE which prints a message to the standard output using a message code given on the command line C gt type dsp c include lt stdio h gt main printf message code d n FROM COMMAND LINE j C gt g56k DFROM COMMAND LINE 56000 dsp c CEN QUE a cld dsp c C gt run56 acid message code 56000 E The input source file will only be preprocessed through CPP and the output results will be sent to the standard output See the o option to save the output into a named file Example 3 11 This example shows how to preprocess the C source program foo c and send the results to the standard output C gt type foo c define DELAY 1000 main int cnt DELAY while cnt C gt g56k E foo c 1 foo c main int cnt 1000 while cnt 3 8 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options Example 3 12 The CPP output can be saved into file foo i by using the o option C gt type foo c define DELAY 1000 main int cnt DELAY while cnt
5. Es Ga6k SB GEOOG o fooi C gt dir foo c foo i C gt type foo i 1 foo c main int cnt 1000 while cnt MOTOROLA DSP56KCC User s Manual 3 9 Preprocessor Phase Options IDIR The control line of the C source program of the form include lt filename gt will cause the replacement of that line by the entire contents of the file filename This is normally referred to as file inclusion The named file is searched for in a se quence of implementation dependent directories The standard include directory for this compiler is usr local dsp include Similarly a control line of the form include filename searches first in the current working directory and if that fails then searches as if the control line were include lt filename gt The option IDIR directs the C compiler to include the directory DIR in addition to the standard include directory For the file inclusion lt filename gt the compiler searches first in the DIR directory and if that fails then searches usr local dsp in clude For the file inclusion filename the compiler searches first in the DIR directo ry and if that fails then searches the current working directory and if that fails also then searches usr local dsp include Example 3 13 A delay program foo c uses delay constant DELAY which is defined in the include file myinclude h The program uses the control line include myinclude h to include the
6. Example 5 9 OES modifier g Program bit checker looks to see if any bit in the 48 bit registers x or y is a one In this case Bit Checker looks to see whether the variable foo which is placed in either the x or y register is all zeros or contains a one The result is stored in register a1 If register a1 is not 0x000000 then foo has one or more bits set to one The variable foo can be allocated to either the x or y register by using the operand constraint S The OR instruction only operates on 24 bit registers so that to OR the x register with another register x1 must be ORed separately from x0 The same applies for the y register main long volatile foo _ asm volatile clr a _ asm volatile or 0 a S foo _ asm volatile or g0 a S foo ooo MOTOROLA DSP56KCC User s Manual 5 11 Example 5 10 OES modifier i The modifier can be used to generate the following assembly code because x is a register without a O or 1 portion In line Assembly code int foo asm move l 0 96i0 R foo Assembly Code Generated move 0 x Example 5 11 OES modifier f The f modifier can be used to generate the following assembly code Assuming that Y memory space is used and the memory location of the variable foo is 233 then the desired memory space indicator y will be automatically generated by the f modifier In line Assembly code int foo __asm
7. X I n MOTOROLA DSP56KCC User s Manual F 11 define HOST_FLAGO 8 Host interface flags define HOST_FLAG1 16 constants used enable disable interrupts define NT_ENABLE 0x3006 bit pattern for Int Priority Reg define INT_DISABLE 0x0000 disables all interrupts addresses of memory mapped peripherals define SCI_ADDR OxFFFO on chip peripheral addresses define SSI_ADDR OxFFEC define PORTS_ADDR OxFFEO define A_CONTROL_ADDR OxFFFE define NT_PRIORITY_ADDR OxFFFF constants used as indices into arrays define VOL 0 offsets from assembly label F_GAIN define STAGE_1G 1 define STAGE_2G 2 define STAGE_3G 3 Macro definitions watch out for side effects x ie repeated evaluation of expressions A and B define MAX A B A B A B define MIN A B A lt B A B define ABS A A gt 0 A 1 A Definitions of global structures defining on chip peripheral interfaces struct sci_port int control sci interface control register int status sci status register int clock sci clock control register int tx_addr sci transmit data address register int lo_data sci low data register int mid_data sci middle data register int hi_data sci high data register y struct ssi_port t int control A ssi control register A int
8. DESCRIPTION The strcpy function copies the characters of string s2 including the terminating character into the string pointed to by s1 If the strings overlap the behavior is undefined The value of s1 is returned When the header file string h is included the default case will be in line see section A 3 Forcing Library Routines Out of line SEE ALSO memcpy Copy one memory area to another memset Initialize a memory area strncpy Copy a portion of one string to another EXAMPLE include lt stdio h gt include lt string h gt void main char string 80 char sptr strcpy string no bald feet for george jetson puts sptr prints to standard output no bald feet for george jetson A A 128 DSP56KCC User s Manual MOTOROLA sircson sircson NAME strcspn Compute the length of the prefix of one string consisting entirely of characters from another SYNOPSIS include lt string h gt int strcspn const char s1 const char s2 DESCRIPTION The strcspn function computes and returns the length of the prefix of the string pointed to by s1 that consists entirely of characters not found in the string pointed to by s2 SEE ALSO memchr Find first occurrence of a character in a memory area strchr Find first occurrence of a character in a string strpbrk Find first occurrence of any character from one string in another string strrchr Find last occurrenc
9. define ARROW_DOWN 66 define ARROW_RIGHT 67 define ARROW_LEFT 68 define CRLF 015 012 carriage return line feed string define NORMAL o screen attributes for Wyse terminal define BLANK lt use logical OR to define BLINK uz combine attribute define REVERSE 14 define UNDERSCORE 8 define DIM p define ECHO 1 flags for getc routine define NO_ECHO 0 define DIGIT i flags for getstr routine define ALPHA 0 define HEX 16 radix for putint routine define DEC 10 define BIN 2 constants and masks used to interface to a target s Host Interface these are included for completeness since the io_host c file includes host interface routines but they are not used by the project code define B_RXDF 1 Host port status register flags define B_TXDE 2 define INT_CONTROL 0x000 Host interface register addresses define CMD_VECTOR 0x100 define INT_STATUS 0x200 define INT_VECTOR 0x300 define HI_BYTE 0x500 define MID_BYTE 0x600 define LO_BYTE 0x700 define RESET_DSPS 0x0000 pattern to reset DSPs bit 12 0 define READ BYTE 0x7800 Host read enable mask define WRITE_BYTE 0x7000 Host write enable mask define LATCH DATA 0x7C00 disable host I O or latch data mask define DSPO OxBFFF DSP enable bit masks bit 14 low define DSP1 OxDFFF bit 13 low List F 5 Include File global h I mR
10. 3 the argument in the first pragma is the string that will be passed as either the runtime or load time argument to the org assembler directive This address which is optional is of the form x address value where x is the counter associated with the x y l or p memory and address value is the value to be initially assigned to that counter As an example p 300 might be used for the counter string p load 4 the C function or data storage definition is a declaration that reserves storage 5 The second counter string should be the same as the first counter string and will return the memory specification to the default setting If and only if the memory space of the counter string in the pragma directive matches the memory model of the C compiler then the compiler will insert an assembly org statement of the form 1 org a runtime address b loadtime address or 2 org a runtime_address where a is the run time counter and runtime address is the optional initial value for that counter as specified in the argument to pragma b is the load time counter and loadtime_address is the optional initial value for that counter as specified in the argument to pragma The following two examples illustrate that the load time counter is optional See the section on the ORG statement in the Motorola DSP56000 DSP56001 Assembler Manual for a complete description and list of options Notice that the pragma directive
11. If for example the compiler s dsp directory tree was installed in c usr mydir then c usr mydir dsp bin would need to be added as follows PATH C NUSRMMYDIRNDSPNBIN 6 Make sure that other DOS memory managers do not interfere with the DOS ex tended memory manager for g56k The compiler uses its own DOS extended memory manager called dos4gw exe and this memory manager may not work if a different memory manager is already installed Although this DOS extender is DPMI 0 9 compliant It is recommended that initially all other DOS extended mem ory managers be removed in order to test the installation The DOS extended memory manager dos4gw exe is called during the compiler s execution and re pee I a _ _ ___ ______ 2 2 DSP56KCC User s Manual MOTOROLA quires at least 2M bytes of RAM This memory manager uses hard drives for the swap space for the memory management By default the swap space location is the C drive and the size of the swap space is 16 Mbytes 7 The DOS environment DOS4GVM controls the configuration of the DOS extended memory management and the environment DOS4GVM has the following format option value option value The possible parameters for the option are MINMEM The minimum amount of RAM managed by the memory manager Default value is 512KB MAXMEM The maximum amount of RAM managed by the memory manager Default value is 4MB SWAPNAME The swap file name for the memory manager uses for th
12. Motorola DSP COFF Librarian SYNOPSIS dsplib a c d I r u v x f lt argfil gt library files DESCRIPTION dsplib is a utility that allows separate files to be grouped together into a single file The resulting library file can then be used for linking by the Mo torola DSP Cross Linker program or for general purpose archival storage library is an operating system compatible file name including optional pathname indicating the library file to create or access If no extension is supplied the librarian will automatically append clb to the file name If no pathname is specified the librarian will look for the library in the current di rectory files is a list of operating system compatible file names For input opera tions the file names may also contain an optional pathname the path is stripped when the file is written to the library For output operations only the file name should be used to refer to library modules If no arguments are given on the command line the librarian enters an in teractive mode where multiple commands may be entered without exiting the program The syntax for the interactive mode is command library files where command is an action corresponding to one of the options listed below library is the library name and files is the optional based on the action requested list of files modules upon which to operate For exam ple the command add foo bar cln adds the module
13. SYNOPSIS include lt setjmp h gt void signal int sig void func int int DESCRIPTION The signal function chooses one of three ways in which to handle the receipt of signal sig 1 If the value of func is the macro SIG_DFL default handling for the signal will occur 2 If the value of func is the macro SIG_IGN the signal is ignored 3 Otherwise func is a pointer to a function that will be called on the receipt of signal sig When a signal occurs the signal handler for sig is reset to SIG_DFL this is equivalent to making the call signal sig SIG_DFL The function func terminates by executing the return statement or by calling the abort exit or longjmp function If the function func terminates with a return statement execution continues at the point the signal was caught Note that if the value of sig was SIGFPE the behavior is undefined Also note that in order to continue catching signal sig the signal handler must reissue the signal call For more information see Chapter 6 SEE ALSO raise Raise a signal pe aee O A 114 DSP56KCC User s Manual MOTOROLA signal signal EXAMPLE include lt stdio h gt void main int onintr signal SIGINT onintr raise SIGINT onintr printf caught SIGINT see ya n exit 9 j prints to standard output caught SIGINT see ya ee ae M MOTOROLA DSP56KCC User s Manual A 115 sin sin NAME sin Sine
14. include lt stdio h gt include lt stdlib h gt void main char char_array if char_array char malloc 709 sizeof char NULL printf error not enough memory n exit 1 printf space for 709 chars allocated OK n prints to standard output space for 709 chars allocated OK i A A A AAA A 74 DSP56KCC User s Manual MOTOROLA mblen mblen NAME mblen Length of a multibyte character SYNOPSIS include lt stdlib h gt int mblen const char s size tn DESCRIPTION The mblen function determines the number of characters in the multibyte character pointed to by s The mblen function is equivalent to mbtowc wchar t 0 s n If s is a NULL pointer mblen returns a zero If s is not NULL mblen returns 1 zero if s points to a NULL character 2 the number of characters that comprise the multibyte character or 3 1 if an invalid multi byte character is formed In no case will the return value exceed n or the MB CUR MAX macro SEE ALSO mbtowc Convert multibyte characters into wide characters wctomb Convert wide characters into multibyte characters SPECIAL NOTE The DSP56000 DSP56001 does not provide byte addressing thus characters always require an entire word of memory each One way to better utilize data memory with a run time cost is to combine the ANSI data type wchar_t and the special ANSI multibyte and wide character library routines r
15. jer Fabort jer Fabort Interrupt Table jer Fabort jer Fabort jmpF start Figure 4 2 Default Program Memory Configuration DSP56KCC activation record consists ot the following elements and is illustrated in Figure 4 3 1 Parameter data space Information passed to C subroutines is stored in a parameter data space which is similar to the local data space see Figure 4 3 However the data is in reverse order and each parameter is referenced via a negative offset from the frame pointer Actual parameters are pushed onto the activation record in reverse order by the calling subroutine 2 Old frame pointer Once the called subroutine has completed execution the frame pointer will be updated with this value 3 Return address which is pushed on the DSP s system stack high ssh register This is the return address to the calling subroutine The return address is not saved for subroutines that have been determined to be a leaf A leaf subroutine is one that makes no subroutine calls 4 Local data space The location of C variables that have a lifetime that extends only as long as the subroutine is active and that could not be explicitly promoted to register storage class by the optimizer Note The frame pointer rO points to the first element in the local data space 5 Register spill and compiler temporary space This area is utilized by the compiler to store intermediate results and preserve register
16. o o o oooooooooo E 62 3 31 Giving the Program a Signal 22 2 ues RARE ERR E 63 3 32 Returning from a FunctiON oococccccocoocco E 63 D 11 Canned Sequences of Commands o occcccccco o E 65 3 33 User Defined Commands 2 xa er eee exhi Eri E 65 3 34 COMMAnd ElES gt GULES ae TK p tires E 66 3 35 Commands for Controlled Output oooocccccooocoo oo E 66 D 12 Options and Arguments Tor DB cora As E 69 3 36 Mode ODIOS il ae wats a ooo E 69 3 37 Ella specilylng OPHOAS 22 3525 9s Sikes litte bee tetas E 69 3 38 Other Arguments 1 5 imc aie teer poete Sa ace abr dea BS eee geo E 70 D 13 Using GDB under GNU Emacs cesta ee ee es as E 71 Appendix E Additional Support Motorola DSP Product Support mb oie oe en a mee ORS oa kw eee Bee D 2 DSP56000CLASx Assembler Simulator 0000 eee D 2 Macro Cross Assembler Features 000 cece eee eens D 2 Simulator Features coe vee od ok odes ex tede wwe eA Pas nue nd exe D 3 DSP320to56001 Translator 20 coca didas D 4 DSP320t056001 Translator Features 0 00 00 cece eee mm D 4 DSP56000ADSx Application Development System 002 eee eee ee D 4 DSP56000ADS Application Development System Hardware Features D 4 DSP56000ADSx Application Development System Software Features D 4 Support Integrated Circuits ia are D 5 _ _ _____ _ gt lt _ cXX 1 vi DSP56KCC User s Ma
17. return data Example 5 21 Line Separation This in line program is functionally identical to Example 5 20 except that line separation is used to insert the entire assembly language program Dr BuB IIR filter program iirl asm into a single _ asm statement Notice how much easier it is to read the program A AAA 5 14 DSP56KCC User s Manual MOTOROLA int iir1 int data int sptr int cptr int state1 state2 coef __asm n move y 4 2 n move y 5 1 n mac 968 967 YO ty 5 1 n move y 4 3 n macr 9 7 0 t 8 y 4 n move 6 y 4 D data R coef R state1 S state2 A sptr A cptr 0 data 1 coef 2 state1 3 state2 return data Example 5 22 Instruction Template Label The following in line assembly code which generates the label foo uses a return character n to insure that there is no white space in front of the label asm nfoo Example 5 23 Program DSP56001 SCI Timer The SCI timer can be programmed so that a SCI interrupt service routine is accessed periodically The following in line assembly program is based on the SCI timer described in section 11 2 of the DSP56000 DSP56001 User Manual asm nSCR EQU FFFO __asm inSCCR EQU FFF2 asm nIPR EQU FFFF main asm move 0 r7 n movep 2000 x SCR n movep 013f x
18. the space character This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main check the beep character if iscntrl 0x07 printf beep 0x07 control character n if iscntrl printf O not control character n prints to standard output beep 0x07 control character not control character A A 58 DSP56KCC User s Manual MOTOROLA isdigit isdigit NAME isdigit Test for numeric character SYNOPSIS include lt ctype h gt int isdigit int c DESCRIPTION The isdigit function returns a nonzero value for any decimal character zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if isdigit 1 printf 1 is a decimal character n if isdigit f printf f not a decimal character n prints to standard output 1 is a decimal character f not a decimal character I E MOTOROLA DSP5
19. 2 2 2 4 controle er PEE 3 10 control program cs riadas 3 1 COS ir NE ai A 23 COS send ae A 24 Counter SUING pex 5 21 CITOP secar dz 3 3 3 30 CAO AA NN Ra ole Rites Min wie 6 1 D aD OPON ee tate ois ec 3 3 3 7 Data ALU gt lt eam ener ek 4 8 Data Memory Configuration 4 12 DELETESWAP ica RE Rate 2 3 denormalized numbers 4 7 OV aos 3 6 5 Savon eC A 25 o AM or MSN EOM rr eee OM aca 4 15 DOS extended memory manager 2 2 DOSAGQVM 1t aui otra eel ses 2 3 DOS4GVM SWP 5 eee cet a Mies 2 3 dos4gw exe Lo 2 2 A A tiaras EE AES 4 3 SIZE ad a 6 2 dep 2 dud Es 2 1 A ache ETE C 10 OSD a2 dp Acad es tee ws ace C 12 G56KCC User s Manual JS EOD sus estos iio tos 2 1 2 2 2 4 E E option 25 31 dde ea ES 3 3 3 8 Gro riid annnka tE Ene EG 4 15 6 8 ME a e marks NA Eaa A 26 EXD ee eee ode EE de eee eee A 27 eXpONEN wisin soe sro eA chek 4 6 F EU CL PT 4 15 FUMA etcetera 4 15 TAOS 22 be aah s A 28 A 29 A 30 A 31 e bas cts hens weet omens er ces 4 15 fcaller saves option 3 3 3 20 CMP A Gu Seta etes 4 15 fcond mismatch option 3 3 3 20 io IBAA A Soh the EP 4 15 ffixed REG option 3 3 3 20 fforce addr option 3 3 3 20 file inclusion ii 2 3 10 finline functions option 3 3 3 20 fkeep inline functions option 3 3 3 20 JOB cato trust to Mote bea eld 4 3 floor A 32 A 33 A 34 A 35 A 36 A 53 A Suo da irlanda A 55
20. Cao type food int foo main int main return foo int foo C gt qo6k Wreturn type foo c foo c In function foo foo c 6 warning control reaches end of non void function C gt dit a cld foo c Wunused Warn whenever a local variable is unused aside from its declaration whenever a function is declared static but never defined and whenever a statement computes a result that is explicitly not used Example 3 30 The file foo c contains an undefined static function unused local variable and a dead statement The Wunused option will issue warnings to indicate these situations Ce gt AIr foo c C gt type foo c static int foo main int x 243 C gt g56k Wunused foo c foo c In function main foo c 5 warning statement with no effect foo c 4 warning unused variable x foo c At top level 3 28 DSP56KCC User s Manual MOTOROLA Assemble Phase Options foo c 1 warning foo declared but never defined Cet LE a cld foo c Wswitch Warn whenever a switch statement has an enumeration type of index and lacks a case for one or more of the named codes of that enumeration The presence of a default label prevents this warning case labels outside the enumeration range also provoke warnings when this option is used Wall All of the above W options combined The remaining W options described below are not implied by Wall because certain kinds of useful macros are al
21. command is the only sure way to make sure the core dump file is used once again AA AAA M MMC E 22 DSP56KCC User s Manual MOTOROLA It is also useful if you wish to run the program outside the debugger for once and then go back to debugging it The kill command is also useful if you wish to re compile and re link the program since on many systems it is impossible to modify an executable file which is run ning in a process But in this case it is just as good to exit GDB since you will need to read a new symbol table after the program is re compiled if you wish to debug the new version and restarting GDB is the easiest way to do that AA A A A AA AA A A A A A M MOTOROLA DSP56KCC User s Manual E 23 AA A E EA4A Am A A A A A E 24 DSP56KCC User s Manual MOTOROLA D 5 Stopping and Continuing When you run a program normally it runs until it terminates The principal purpose of us ing a debugger is so that you can stop it before that point or so that if the program runs into trouble you can investigate and find out why 3 9 Signals A signal is an asynchronous event that can happen in a program The operating system defines the possible kinds of signals and gives each kind a name and a number For ex ample SIGINT is the signal a program gets when you type Ctrl c SIGSEGV is the signal a program gets from referencing a place in memory far away from all the areas in use SI GALRM occurs when the alarm clock tim
22. isalnum c amp amp isalnum 1 printf c 1 alpha and numeric n if isalnum E printf O neither alpha nor numeric n prints to standard output c 1 alpha and numeric neither alpha nor numeric ee A 56 DSP56KCC User s Manual MOTOROLA isalpha isalpha NAME isaloha Test for alphabetic character SYNOPSIS include lt ctype h gt int isalpha int c DESCRIPTION The isalpha function returns a nonzero value for any alphabetic character zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if isalpha c printf c alpha n if isalpha O 88 isalpha 1 printf 1 non alpha n prints to standard output c alpha 1 non alpha I B MOTOROLA DSP56KCC User s Manual A 57 iscntrl iscntrl NAME iscntrl Test for control character SYNOPSIS include lt ctype h gt int iscntrl int c DESCRIPTION The iscntrl function returns a nonzero value for any control character zero is returned in the false case A control character is any character that is NOT a letter digit punctuation or
23. printf testing atexit n void func_1 void void func_2 void prints to standard output testing atexit second function called first function called printf first function called n printf second function called sss MOTOROLA DSP56KCC User s Manual A 13 atof atof NAME atof String to floating point SYNOPSIS include lt stdlib h gt double atof const char nptr DESCRIPTION The atof function converts the string pointed to by nptr t a o double If the result can not be represented the behavior is undefined This is exactly equivalent to strtod nptr char NULL SEE ALSO atoi String to integer atol String to long integer striod String to double strtol String to long integer strtoul String to unsigned long integer EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf atof 7 09 f n atof 7 09 prints to standard output atof 7 09 7 090000 r A O A 14 DSP56KCC User s Manual MOTOROLA atol atol NAME atoi String to integer SYNOPSIS include lt stdlib h gt int atoi const char nptr DESCRIPTION The atoi function converts the string pointed to by nptr to an integer If the result can not be represented the behavior is undefined This is exactly equivalent to int strtol nptr char NULL 10 SEE ALSO
24. wchar_t wstr 10 L abcdefgh void main char ptr char wstr int convert convert wcstombs array wstr 10 printf packed array n while ptr 0 printf 0 6x ptr printf nin printf d chars extracted unpacked array n ptr array while ptr 0 printf 0 6x ptr printf n prints to standard output packed array 616263 646566 676800 8 chars extracted unpacked array 000061 000062 000063 000064 000065 000066 000067 000068 EES MOTOROLA DSP56KCC User s Manual A 159 wctomb wctomb NAME wctomb Convert wchar_t character to multibyte character SYNOPSIS include lt stdlib h gt int wctomb char s wchar_t wchar DESCRIPTION The wctomb function examines and converts the wide character wchar into a string of characters pointed to by s At most MB_CUR_MAX characters will be stored in s If s is a NULL pointer wctomb returns zero If s is not NULL wctomb returns the number of characters that comprise the converted multibyte character unless an invalid multibyte character is detected in which case a 1 will be returned SEE ALSO mblen Determine the length of a multibyte character mbstowcs Convert a multibyte string into a wide character string mbtowc Convert a multibyte character into a wide character SPECIAL NOTE The DSP56000 DSP56001 does not provide byte addressing thus characters always require an ent
25. 1 Add the following line to each C module or once to a common header file undef ROUTINE_NAME where ROUTINE_NAME is the library routine that must be forced out of line For example to force the library routine ceil out of line undef ceil 2 Use the command line option U see Chapter 3 Control Program Options This will force the library routine to be called for this compilation If the code is re compiled the U option must be used again C gt g56k Uceil file c 3 Do not include the header file A 4 Function Descriptions The following section describes each function in complete detail The synopsis provides the syntax of the function and the options section discusses each option in detail Many function descriptions also include references to related functions and an example of how to use the function The list shown below provides an abbreviated description of each function abort Force abnormal program termination abs Absolute value of integer acos Arc cosine asin Arc sine atan Arc tangent atan2 Arc tangent of angle defined by point y x atexit Register a function for execution upon normal program termination atof String to floating point atoi String to integer atol String to long integer bsearch Perform binary search calloc Dynamically allocate zero initialized storage for objects ceil Ceiling function clearerr Clear error indicators associated with a s
26. 4 11 8 Hardware DO Loop Instruction The DSP56000 family architecture provides a method in hardware to perform zero overhead looping via the do instruction DSP56KCC may exchange the standard increment compare conditional jump sequence with a single do instruction this is called do loop promotion when the following conditions are met 1 The body of the loop contains no subroutine calls 2 The loop is entered from the top i e no goto label entries 3 No conditional exits from the loop are allowed 4 The loop s induction variable is only altered in the body of the loop once per iteration Please note that this includes any modifications to the induction variable within the actual for or while statement 4 11 9 Loop Rotation Loop rotation is the elimination of the code generated to check the loop s entry conditions When a loop fails to qualify for do loop promotion i e it does not meet the a MOTOROLA DSP56KCC User s Manual 4 17 four conditions listed above it will qualify for loop rotation if the length of the loop is known at compile time for example for i 05 i1 lt 10 i The loop created with this for statement will always be executed at least one time Therefore the is i lt 10 test does not have to be run the first time through the loop and as a result can be eliminated during the first pass through the loop only If the result of the first test cannot be predetermined then it cannot be eliminated In the e
27. If the program is interactive make it output a short notice like this when it starts in an in teractive mode Gnomovision version 69 Copyright C 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY for details type show w This is free software and you are welcome to redistribute it under certain conditions type show c for details The hypothetical commands show w and show c should show the appropriate parts of the General Public License Of course the commands you use may be called something other than show w and show c they could even be mouse clicks or menu items what ever suits your program _____ _ gt _ gt __ ______ 1 E 8 DSP56KCC User s Manual MOTOROLA You should also get your employer if you work as a programmer or your school if any to sign a copyright disclaimer for the program if necessary Here a sample alter the names Yoyodyne Inc hereby disclaims all copyright interest in the program Gnomovision a program to direct compilers to make passes at assemblers written by James Hacker signature of Ty Coon 1 April 1989 Ty Coon President of Vice That s all there is to it r C T n MOTOROLA DSP56KCC User s Manual E 9 r A A A A A E 10 DSP56KCC User s Manual MOTOROLA D 1 Input and Output Conventions GDB
28. Initialize memory area modf Break a double into it s integral and fractional parts perror Print error message indicated by errno pow Raise a double to a power printf Write formatted output to the stream stdout putc Write a character to a stream this may be a macro putchar Write a character to the stream stdout this may be a macro puts Write a string to the stream stdout qsort Quick sort raise Raise a signal rand Pseudo random number generator realloc Change size of dynamically allocated storage area remove Remove a file from the disk rename Rename a file on the disk rewind Reset the file position indicator of a stream to the beginning of the file on the disk scanf Read formatted input from the stream stdin setjmp Save a reference of the current calling environment for later use by longjmp setbuf Associate a buffer with a stream setvbuf Associate a buffer with a stream while also specifying the buffering mode and buffer size signal Set up signal handler sin Sine sinh Hyperbolic Sine sprintf Write formatted output to a string sqrt Square root srand Seed the pseudo random number generator sscanf Read formatted input from a string eau U ME MOTOROLA DSP56KCC User s Manual A 5 strcat Concatenate two strings strchr Find first occurrence of a character in a string strcmp
29. SYNOPSIS include lt math h gt double sin double x DESCRIPTION The sin function computes and returns the sine of x measured in radians SEE ALSO asin The arc sine of an angle EXAMPLE include lt stdio h gt include lt math h gt void main printf sin 45 0 f n sin 45 0 prints to standard output sin 45 0 0 850904 pee EO O A 116 DSP56KCC User s Manual MOTOROLA sinh sinh NAME sinh Hyperbolic Sine SYNOPSIS include lt math h gt double sinh double x DESCRIPTION The sinh function computes and returns the hyperbolic sine of x measured in radians When the value of x is too large errno will be set to ERANGE and the return value will be HUGE_VAL with the sign of x SEE ALSO cosh Hyperbolic cosine of an angle tanh Hyperbolic tangent of an angle EXAMPLE include lt stdio h gt include lt math h gt void main printf sinh 3 1415 f n sinh 3 1415 prints to standard output sinh 3 1415 11 547661 AAA AAA A A A e OE MOTOROLA DSP56KCC User s Manual A 117 sprintf sprintf NAME sprintf Print to a string SYNOPSIS include lt stdio h gt int sprintf char s const char format DESCRIPTION The sprintf function is equivalent to printf except that s specifies a string that the generated output is printed to rather than standard output A null character is written at the end of th
30. _ _____ 1 E 40 DSP56KCC User s Manual MOTOROLA info frame addr Print a verbose description of the frame at address addr without selecting that frame The selected frame remains unchanged by this command info args Print the arguments of the selected frame each on a separate line info locals Print the local variables of the selected frame each on a separate line These are all variables declared static or automatic within all program blocks that execution in this frame is currently inside of eee A A AAA AA A M oO MOTOROLA DSP56KCC User s Manual E 41 pee A A A E 42 DSP56KCC User s Manual MOTOROLA D 7 Examining Source Files GDB knows which source files your program was compiled from and can print parts of their text When your program stops GDB spontaneously prints the line it stopped in Likewise when you select a stack frame see section Selection GDB prints the line which execution in that frame has stopped in You can also print parts of source files by explicit command 3 17 Printing Source Lines To print lines from a source file use the list command abbreviated l There are several ways to specify what part of the file you want to print Here are the forms of the list command most commonly used list linenum Print ten lines centered around line number linenum in the current source file list function Print ten lines centered around the beginning of function function list P
31. main printf x xin mac01 0x123456 mactwo 0x123456 0x0147ae printf x xin mac02 0x123456 mactwo 0x123456 0x28f5c C gt g56k main c mod1 asm mod2 asm C run56 a cld 2e9a 2e9a 5d35 5d35 5 4 2 Global C and Static Variables in C The global C variables are accessed using labels generated by the C compiler Any vari ables that are static to an assembly language subroutine will be accessed the same way These variables are placed into memory at compile time and are referenced symbolically according to the labels automatically generated by the compiler However it is possible to override the default labels by using the asm keyword as explained in Section 5 2 5 Controlling Labels Generated by Compiler For example using the default labeling convention the global integer Ginteger which can be declared within the C statement extern int Ginteger is loaded into the input reg ister X0 in assembly code as follows move y FGinteger xO When declaring C global variables in an assembly language file the programmer must be careful to follow the label generating convention or use the asm keyword to report to the compiler that the labeling convention has been changed In both cases the as sembler directive global is used to export the labels to the C files DO NOT use the XDEF XREF pair of directives NOTE that it is the programmers responsibility to allocate space for the global variables dec
32. xxxyz lt 0 puts xxx is less than xxxyz puts xxx is greater than xxxyz if stremp xxxyz Xxx lt 0 puts xxxyz is less than xxx puts xxxyz is greater than xxx if stremp xxxyz XXXyZ 0 puts xxxyz is equal to xxxyz prints to standard output xxx is less than xxxyz XXXyz is greater than xxx xxxyz is equal to xxxyz i A 126 DSP56KCC User s Manual MOTOROLA strcoll strcoll NAME strcoll Compare two strings based on current locale SYNOPSIS include lt string h gt int strcoll const char s1 const char s2 DESCRIPTION The strcoll function compares the string pointed to by s1 to the string pointed to by s2 both strings are interpreted using the LC_COLLATE category of the current locale If string slis lexicographically greater than equal to or less than s2 an integer greater than equal to or less than zero will be returned The comparison of two strings of unequal length in which the longer string contains the smaller string yields the result that the longer string compares greater than For DSP56KCC strcoll functions exactly like strcmp SEE ALSO strxfrm Transform a string into locale independent form strcmp Compare two strings AAA A A AA A A M MOTOROLA DSP56KCC User s Manual A 127 strcpy strcpy NAME strcpy Copy one string into another SYNOPSIS include lt string h gt int strcpy char s1 const char s2
33. 1C3F 1D4C 270 io_host_c 1D4D 1EC5 377 io_atoi_c 1EC6 2064 415 io ctype c P Memory low Start End Length Section No sections P Memory high Start End Length Section No sections rn O M oO MOTOROLA DSP56KCC User s Manual F 9 crt0 asm The CRTO file performs several functions required in order to execute C code The following global C variables are defined and initialized Stack safety Since dynamic memory and the stack grow towards each other This constant tells brk and sbrk what the minimum amount of space should be left between the top of stack during the brk or sbrk call and the end of any allocated memory mem limit a constant telling brk and sbrk where the end of available memory is _ _break pointer to the next block of memory that can be allocated The heap may be moved by changing the initial value of _ _break This is the base of the heap _y_size the base of dynamic memory The F_ _start routine is invoked upon reset as defined in the vector table in the file vectors asm F_ _start initializes the stack pointer register for the C environment as well as the pointer register used to handle fast SSI interrupts The Status Register is set to permit level 1 2 and 3 interrupts Then a jump to the main C function is made The F _crt0_end routine executes when the main C function returns F_ _crt _end simply stops execution of the program with the
34. Compute the length of the prefix of a string contained in another string EXAMPLE include lt stdio h gt include lt string h gt void main char string fred flintstone driving on bald feet char found found strchr string b puts found prints to standard output bald feet ee A 124 DSP56KCC User s Manual MOTOROLA sircmp sircmp NAME strcmp Compare two strings SYNOPSIS include lt string h gt int stremp const char s1 const char s2 DESCRIPTION The stremp function compares the string pointed to by s1 to the string pointed to by s2 If string stis lexicographically greater than equal to or less than s2 an integer respectively greater than equal to or less than zero will be returned The comparison of two strings of unequal length in which the longer string contains the smaller string yields the results that the longer string compares greater than i e stremp xxx xxxyz lt 0O or stremp xxxyz xxx gt 0 When the header file string h is included the default case will be in line see section A 3 Forcing Library Routines Out of line SEE ALSO memcmp Compare two memory areas strcoll Compare two strings based on current locale strncmp Compare portions of two strings ae e M MOTOROLA DSP56KCC User s Manual A 125 sircmp sircmp EXAMPLE include lt stdio h gt include lt string h gt void main if stremp xxx
35. NJ Prentice Hall Inc 1983 SIGNAL PROCESSING ALGORITHMS S Stearns and R Davis Englewood Cliffs NJ Prentice Hall Inc 1988 SIGNAL PROCESSING HANDBOOK C H Chen New York NY Marcel Dekker Inc 1988 q _ UMM A AAA MOTOROLA DSP56KCC User s Manual D 15 SIGNAL PROCESSING THE MODERN APPROACH James V Candy New York NY McGraw Hill Company Inc 1988 THEORY AND APPLICATION OF DIGITAL SIGNAL PROCESSING Rabiner Lawrence R Gold and Bernard Englewood Cliffs NJ Prentice Hall Inc 1975 Digital Audio and Filters ADAPTIVE FILTER AND EQUALIZERS B Mulgrew and C Cowan Higham MA Kluwer Academic Publishers 1988 ADAPTIVE SIGNAL PROCESSING B Widrow and S D Stearns Englewood Cliffs NJ Prentice Hall Inc 1985 ART OF DIGITAL AUDIO THE John Watkinson Stoneham MA Focal Press 1988 DESIGNING DIGITAL FILTERS Charles S Williams Englewood Cliffs NJ Prentice Hall Inc 1986 DIGITAL AUDIO SIGNAL PROCESSING AN ANTHOLOGY John Strawn William Kaufmann Inc 1985 DIGITAL CODING OF WAVEFORMS N S Jayant and Peter Noll Englewood Cliffs NJ Prentice Hall Inc 1984 DIGITAL FILTERS ANALYSIS AND DESIGN Andreas Antoniou New York NY McGraw Hill Company Inc 1979 DIGITAL FILTERS AND SIGNAL PROCESSING Leland B Jackson Higham MA Kluwer Academic Publishers 1986 DIGITAL SIGNAL PROCESSING Richard A Roberts and Clifford T Mullis New York NY Addison Welsey Publishing Company In
36. SEE ALSO wcstombs Convert wide character strings into multibyte strings SPECIAL NOTE The DSP56000 DSP56001 does not provide byte addressing thus characters always require an entire word of memory each One way to better utilize data memory with a run time cost is to combine the ANSI data type wchar t and the special ANSI multibyte and wide character library routines rn Ml MOTOROLA DSP56KCC User s Manual A 77 mbstowcs mbstowcs EXAMPLE include lt stdio h gt include lt stdlib h gt wchar_t warray 10 void main i char array abcdedgh char ptr array int convert convert mbstowcs warray array 10 printf unpacked array looks like n while ptr 0 printf 20 6x ptr printf nin printf d chars packed packed array looks like n ptr warray while ptr 0 printf 0 6x ptr printf n prints to standard output unpacked array looks like 000061 000062 000063 000064 000065 000066 000067 000068 8 chars packed packed array looks like 616263 646566 676800 eS AAA A AAA A 78 DSP56KCC User s Manual MOTOROLA mbtowc mbtowc NAME mbtowc Convert a multibyte character to a wide character SYNOPSIS include lt stdlib h gt int mbtowc wchar_t pwc const char s size tn DESCRIPTION The mbtowc function examines the multibyte i e multi character string pointed to by s and converts it into
37. The value is the 16 bit constant with p modifier and 24 bit constant with q modifier see Example 5 12 m A memory location will be allocated to the C expression see Example 5 11 The DSP56000 DSP56001 has four memory spaces X Y L and P but the C compiler may only use the X Y or L memory spaces for this expression The OES modifier f can only be associated with operand constraint m see Sec tion 5 2 1 number Inherit all memory or register characteristics of the operand indicated by the operand id number see Example 5 3 This constraint is usually used for read write operands which are declared by using the same C variable as both the input and output operand The operand is sometimes referred to as a read only operand if it is used only as input see Example 5 14 and it is called a write only operand if it is used only as an output see Example 5 15 In most of cases the operand is used as both an input and an out put operand see Example 5 16 and Example 5 17 In these cases the operand should be described as both Since output operands should be listed first the operand id num gt gt ___ ____ _ _ ___ __ gt gt gt _ _ _ __ ______ ______ 2 5 6 DSP56KCC User s Manual MOTOROLA ber is determined when the input operand is declared The id number will be used as the operand constraint of the input operand Table 5 1 lists the operand constraints and their related modifiers Table 5 1 Operand Constraints
38. This is equivalent to a source statement of the form MACLIB lt mpath gt The M lt mpath gt sequence may be repeated as many times as desired The directories will be searched in the order specified on the command line O lt opt gt lt opt gt opt can be any of the options that are available with the assembler OPT di rective If multiple options are supplied they must be separated by com mas The O lt opt gt sequence may be repeated for as many options as desired R lt rev gt lt rev gt Run the assembler without the specified processor revision level enhance ments This is for backward compatibility so that the assembler will flag new constructions as illegal rev can be any of the revision specifiers given be low but must be appropriate for the target processor Processor Revision DSP56000 C If multiple revision levels are supplied they must be separated by commas The R lt rev gt sequence may be repeated as many times as desired Z This option causes the assembler to strip symbol information from the ab solute load file Normally symbol information is retained in the object file for symbolic reference purposes Note that this option is valid only when the assembler is in absolute mode via the A command line option and when an object file is created B option V Indicates that the assembler should be verbose during processing display ing a progress report as it assembles the input files T
39. This is useful if output is to a file or to an editor buffer Also GDB may at times produce more information about its own workings than is of interest to the user Some of these informational messages can be turned on and off with the set verbose command set verbose off Disables GDB s output of certain informational messages set verbose on Re enables GDB s output of certain informational messages Currently the messages controlled by set verbose are those which announce that the symbol table for a source file is being read see section File Commands in the description of the command symbol file AAA A AAA OO E 12 DSP56KCC User s Manual MOTOROLA D 2 Specifying GDB s Files GDB needs to know the file name of the program to be debugged both in order to read its symbol table and in order to start the program To debug a core dump of a previous run GDB must be told the file name of the core dump 3 1 Specifying Files with Arguments The usual way to specify the executable and core dump file names is with two command arguments given when you start GDB The first argument is used as the file for execution and symbols and the second argument if any is used as the core dump file name Thus gdb progm core specifies progm as the executable program and core as a core dump file to examine You do not need to have a core dump file if what you plan to do is debug the program in teractively See section
40. USR DIRECTORY 3 The contents of an MS DOS directory are examined by entering CAS DIR 4 The contents of an MS DOS file are displayed by entering C gt TYPE FILE 5 The program HELLO EXE would be executed by the command line C gt HELLO OMM 1 4 DSP56KCC User s Manual MOTOROLA 1 4 Manual Organization Installation details are provided in Chapter 2 the compiler operation is described in Chapters 3 6 and reference information is in Chapter 3 and Appendices A E The contents of each chapter and each appendix are described below Chapter 1 Introduction describes the overall organization of the DSP56KCC compiler system It also details the structure of this document and conventions followed herein Chapter 2 Installation Guide describes the installation and organization of DSP56KCC It details how to set up an operating environment on the host system by defining global environment variables and includes a step by step installation procedure Chapter 3 Compiler Operation discusses the four passes of the compilation process with particular attention to the functions of the compiler control program g56k This chapter includes a list of the compiler invocation options along with example command lines for different memory and program configurations Chapter 4 About g56k provides information on the compiler run time environment including explanations of compiler register and memory usage stack frame architecture stack
41. cofdmp is a utility that reads an absolute or relocatable COFF file and pro duces a formatted display of the object file contents The entire file or only selected portions may be processed depending on command line options The program also can generate either codes or symbolic references to en tities such as symbol type or storage class file is an operating system compatible file name Only a single file name may be supplied and it must be explicit there is no default extension for the input file OPTIONS Any of the following command line options may be given Option letters may be entered in either upper or lower case If no option is specified the entire object file is dumped C Dump the object file string table This information may not be available if the object file has been stripped d Dump to output file f Dump the file header of the object file h Dump the object file section headers l Dump the object file line number information This information may not be available if the object file has been stripped 0 Dump the object file optional header r Dump the object file relocation information This information is available only in relocatable object files S Dump the object file raw data contents t Dump the object file symbol table V Dump the object file symbolically expanding bit flag symbol type and stor age class names A aaa MOTOROLA DSP56KCC User s Manual C 9 dsplib dsplib NAME dsplib
42. e g Jul 22 1991 TIME _ YES The compilation time a character string of the form hh mm ss __STDC_ YES Decimal constant 1 indicates ANSI conformation _ _DSP56K__ NO Decimal constant 1 indicates that code is being generated for the DSP56000 DSP56001 Digital Signal Processor VERSION _ NO The version number of the compiler a character string of the form d dd d _ INCLUDE LEVEL NO Decimal constant indicates the current depth of file inclusion 4 4 1 Integral Data Types The type char unsigned char signed char short int int long int and the enumerated types comprise the integral data types The type sizes and ranges are defined in Table 4 3 Table 4 3 Integral Data Type Sizes and Ranges Data Type Size words Min value Max value char 1 8388608 8388607 unsigned char 1 0 OxFFFFFF short 1 8388608 8388607 unsigned short 1 0 OxFFFFFF int 1 8388608 8388607 unsigned int 1 0 OxFFFFFF long 2 140737488355328 140737488355327 unsigned long 2 0 OxFFFFFFFFFFFF 4 4 2 Floating point Types In DSP56KCC the C data types float and double are both implemented as single precision see Table 4 4 DSP56KCC does not implement the IEEE STD 754 1985 oen M 4 2 DSP56KCC User s Manual MOTOROLA standard format for binary floating point arithmetic A description of the format and a comparison with the IEEE standard follow Table 4 4 Floating point Data Type Sizes and Ranges Data Typ
43. latgent asm 1 0 Test program for latgen asm 1269 latnrm asm 1 0 Normalized Lattice IIR Filter Macro 1407 latnrm hlp Help for latnrm asm 7475 latnrmt asm 1 0 Test program for latnrm asm 1595 Matrix Operations matmul1 asm 1 0 1x3 8x3 1x3 Matrix Multiplication 1817 matmul1 hlp Help for matmul1 asm 527 matmul2 asm 1 0 General Matrix Multiplication C AB 2650 matmul2 hlp Help for matmul2 asm 780 matmul3 asm 1 0 General Matrix Multiply Accumulate 2815 C AB Q matmul3 hlp 1 0 Help for matmul3 asm 865 Reed Solomon Encoder readme rs 1 0 Instructions for Reed Solomon coding 5200 rscd asm 1 0 Reed Solomon coder for DSP56000 simulator 5822 newc c 1 0 Reed Solomon coder coded in C 4075 table1 asm 1 0 Include file for R S coder 7971 table2 asm 1 0 Include file for R S coder 4011 Sorting Routines sort1 asm 1 0 Array Sort by Straight Selection 1312 sort1 hlp Help for sort1 asm 1908 sortit asm 1 0 Test program for sort1 asm 689 sort2 asm 1 1 Array Sort by Heapsort Method 2183 sort2 hlp Help for sort2 asm 2004 sort2t asm 1 0 Test program for sort2 asm 700 q _ ______ _z_ gt gt E gt EE M 1 MOTOROLA DSP56KCC User s Manual D 11 Document ID Version Synopsis Size Speech Igsol1 asm 2 0 Leroux Gueguen solution for PARCOR 4861 LPC coefficients lgsol1 hlp Help for Igsol1 asm 3971 durbin1 asm 1 2 Durbin Solution for PARCOR 6360 LPC coefficients durbin1 hlp Help f
44. ni Execute one machine instruction but if it is a subroutine call proceed until the subroutine returns An argument is a repeat count as in next A typical technique for using stepping is to put a breakpoint see section Break points at the beginning of the function or the section of the program in which a problem is believed to lie and then step through the suspect area examining the variables that are interesting until the problem happens The cont command can be used after stepping to resume execution until the next breakpoint or signal q _ __ ______ __ _ _z gt 4 E 36 DSP56KCC User s Manual MOTOROLA D 6 Examining the Stack When your program has stopped the first thing you need to know is where it stopped and how it got there Each time your program performs a function call the information about where in the pro gram the call was made from is saved in a block of data called a stack frame The frame also contains the arguments of the call and the local variables of the function that was called All the stack frames are allocated in a region of memory called the call stack When your program stops the GDB commands for examining the stack allow you to see all of this information One of the stack frames is selected by GDB and many GDB commands refer implicitly to the selected frame In particular whenever you ask GDB for the value of a variable in the program the value is found i
45. o A EDT oats loan A A 37 IMPIDA e e E 4 15 IG Gs vst sonic abt desde 4 15 fno defer pop option 3 3 3 19 fno opt option 3 3 3 19 fno peephole option 3 3 3 19 fno strength reduce option 3 3 3 19 Frame Pointer 2 22 oon 4 9 frame pointer 4 10 6 2 free A 38 A 40 A 41 A 42 A 43 A 44 A MOTOROLA A cet edd A 52 A 97 AS PER Leer PBs A 46 A 47 PSU IG RM ti hg doo 4 15 fvolatile option 3 3 3 20 fwritable strings option 3 3 3 20 OPIO tds od 3 3 3 22 G56 EXEC PREFIX nux 3 4 3 30 GONE S ere eae a ek ceete Donate dri d 2 4 9561 601 ite eins a e i 3 19 E A ERE EE GRE IR 3 1 DB56 25 oot pU RERPC REN 3 22 ofa ore A A RR C 17 global assembler directive 5 32 H NEO c 2 5 NOSE ero s o 6 2 SP OPUON seso ac tct 3 3 3 10 3 11 i option DOS TES 3 3 3 13 identifier length limits 4 1 IEEE P754 1985 atk Eu a eges 4 2 in line assembly instruction template 5 3 in line assembly code 5 1 Input Registers 4 8 Instalan 2 1 AAN ST 4 2 4 8 interrupt vectors s aer 6 1 EA A 50 A 51 A 56 ISAIDNA 2 aspirando cria A 57 Esp AA A EDEN A 58 o e i ios aoe ele SEM cud A 59 MOTOROLA ISOLaDpDi 3 ni sat S aes ente a ce ee A 60 ISIG WOM XT A 61 ISP quico be ded A 62 E A eet oe Reece ede ENS A 63 ISS pace ua abs A 64 ISUDDGR ida ended emai ahead A 65 Sl S s da
46. 0 002 c eee eee 5 21 5 3 pragma Directive sirsie read IDEA AAN 5 21 5 4 Out of line Assembly Code ooocccccoocco ees 5 24 5 4 1 General Templates gt 206210020 5 25 5 4 1 1 A A 5 25 5 4 1 2 Save all register Sent ata dos Maa ected eee es Beas 5 26 5 4 1 3 Main Program 6 fof aul Rie o a gue Sek wee ee Bap 5 26 5 4 1 4 Restore all registers 5 4 ete Reo tie chor tee eee RAs 5 27 5 4 1 5 EPO EM TOR 5 27 5 4 1 6 Out of line Assembly Code Example o o o o 5 28 5 4 2 Global C and Static Variables in C o oooocoooooooo 5 32 5 4 3 Using Run time Stack for Local Data o o o oooooooo 5 34 5 4 4 Calling C Routines crore eU ERE dis 5 35 5 4 5 Optimization Techniques 000 cee eee eee 5 35 Chapter 6 Software Hardware Integration 6 1 pu c Dc 6 1 6 2 Run Time Environment Specification Files o o 6 1 6 3 CMO Geet spe uds 8 A aec Lui ee Oe Saat M 6 2 6 3 1 Bootstrapping the C program lselllsesseleesss 6 2 6 3 2 Memory Configuration and Management 5 6 3 6 3 3 Interr pt V OCIO secas mets ten ST IDEE PS o SE UE ERE 6 6 6 3 4 Miscellaneous Code o zx det EN Oe Se one on ede A NES 6 8 6 4 Signal File p pU 6 9 6 4 1 A ciae ter id acted pec Dti uses Pride 6 9 6 4 2 arci cT 6 11 6 5 SC MMS da d rueda vt Svea io pec bep 6 11 6 6 Host Supported VO printf etal es sena rd bs 6 12 6 6 1 DSP functions __send and receive
47. 10 If the value of the return value is too large to be expressed by a long int errno is set to ERANGE and ULONG_MAX is returned SEE ALSO atof String to double atoi String to integer atol String to long integer strtod String to double strtol String to long integer _ gt _ __ EL E MOTOROLA DSP56KCC User s Manual A 145 strtoul strtoul EXAMPLE include lt stdio h gt include lt string h gt void main char hexstr Oxabcdef709hexstr stopped char decstr 709709709decstr stopped char octstr 012341234octstr stopped char stopped unsigned long result printf result t tstop string Wn result strtol hexstr amp stopped 16 printf lu t t s result stopped result strtol decstr amp stopped 10 printf lu t t s result stopped result strtol octstr amp stopped 8 printf lu t t s result stopped prints to standard output result stop string 2883516169 hexstr stopped 709709709 decstr stopped 12341234 octstr stopped A AAA AAA A A O A 146 DSP56KCC User s Manual MOTOROLA strxfrm strxfrm NAME strxfrm Transform a string into locale independent form SYNOPSIS include lt string h gt size_t strxfrm char s1 const char s2 size tn DESCRIPTION The strxfrm function transforms the string pointed to by s2 and places the resulting string in th
48. All registers are saved before the c sig dispatch function calls the C signal handler Pseudo function c sig dispatch then calculates the signal number using the return address program counter of the ssh Since the signal number is the same as the interrupt vector address each entry ofthe c sig goto dispatch table corresponds to an inter rupt vector The pseudo function uses the signal number to fetch the actual C signal han dler from the c sig handlers table which is the C function pointer table Once the C signal handler is fetched from the c sig handler table its entry is replaced with the default signal handler SIG DFL This replacement is in compliance with the ANSI standard and forces the next signal service to abort In most situations this feature is not needed because any given interrupt will always invoke the same interrupt service routine Resetting signal after each C service routine or modifying this file so that it does not re place the table entry with SIG DFL will change the interrupt service scheme Modification of the signal file is only recommended when optimization of the service time is critical to the application Upon return from the C signal handler all the registers are restored Finally the rti instruc tion is executed to return to the code that was executing when the interrupt occurred No tice two factors in this scheme 1 all registers are saved and restored before and after the C signal
49. BCLR Bit test and clear BSET Bit test and set _ qv gt gt gt z_ ___ MME B 2 DSP56KCC User s Manual MOTOROLA BCHG Bit test and change BTST Bit test on memory JCLR Jump if bit clear JSET Jump if bit set JSCLR Jump to subroutine if bit clear JSSET Jump to subroutine if bit set B 2 4 Loop Instructions The instructions used for loop operations are DO Start hardware loop ENDDO Exit from hardware loop B 2 5 Move Instructions The instructions used for move operations are LUA Load updated address MOVE Move data MOVEC Move control register MOVEM Move program memory MOVEP Move peripheral data B 2 6 Program Control Instructions The instructions used for program control are Jcc Jump conditionally JMP Jump JScc Jump to subroutine conditionally JSR Jump to subroutine NOP No operation HEP Repeat next instruction RESET Reset on chip peripheral devices RTI Return from interrupt RTS Return from subroutine STOP Stop processing low power stand by SWI Software interrupt WAIT Wait for interrupt low power stand by EEE MOTOROLA DSP56KCC User s Manual B 3 B 3 Directive Summary Directives can be grouped by function into seven types Assembly control Symbol definition Data definition storage allocation Listing control and options Object file control Macros and conditional
50. Compare two strings strcoll Compare two strings based on current locale strcpy Copy one string into another strcspn oe the length of the prefix of a string not contained in a second string strerror Map error code into an error message string strlen Determine length of a string strncat Concatenate a portion of one string to another strncmp Compare a portions of two strings strncpy Copy a portion of one string into another strpbrk Find the first occurrence of a character from one string in another strrchr Find the last occurrence of a character in a string strspn Compute the length of the prefix of a string contained in a second string strstr Find the first occurrence of one string in another strtod String to double strtok Break string into tokens strtol String to long integer strtoul String to unsigned long integer strxfrm Transform a string into locale independent form tan Tangent tanh Hyperbolic tangent tmpfile Create a temporary binary file on the disk to be referenced via a stream tmpnam Generate a unique valid file name tolower Convert uppercase character to lowercase toupper Convert lowercase character to uppercase ungetc Push a character back onto a specified input stream vfprintf Write formatted output to a stream using a va list vprintf Write formatted output to the stream stdout us
51. HUGE VAL is returned SEE ALSO exp Raising e to a power logi0 Base 10 logarithm EXAMPLE include lt stdio h gt include lt math h gt void main printf log 7 09 f n log 7 09 prints to standard output log 7 09 1 958685 pe aO O A 70 DSP56KCC User s Manual MOTOROLA log10 log10 NAME log10 Base ten logarithm SYNOPSIS include lt math h gt double log10 double x DESCRIPTION The log10 function computes the natural logarithm of x If the value of x is less than zero errno is set to EDOM and the value HUGE_VAL is returned If x is equal to zero errno is set to ERANGE and the value HUGE_ VAL is returned SEE ALSO exp Raising e to a power log Natural logarithm EXAMPLE include lt stdio h gt include lt math h gt void main printf log10 7 09 f n log10 7 09 prints to standard output log10 7 09 0 850646 A _ _ gt IO M MOTOROLA DSP56KCC User s Manual A 71 longjmp longjmp NAME longimp Execute a non local jump SYNOPSIS include lt setjmp h gt void longjmp jmp_buf env int val DESCRIPTION The longjmp function restores the calling environment referenced by env which must have been initialized by a previous call to setjmp If there has been no invocation of setjmp or if the function containing the call to setjmp has terminated execution before the call to longjmp the behavior is undefined Upon
52. I O function io host c EE F 30 DSP56KCC User s Manual MOTOROLA return status write_hreg Write the value byte to the host register specified by reg addr on the DSP processor specified by target void write hreg target reg addr byte int target int reg addr int byte t void B config out B config out ports B data WRITE BYTE amp target reg addr byte ports B data LATCH DATA byte B putword Output a 24 bit word to the host port of the DSP processor specified by target NOTE x The 24 bit word is treated as unsigned to prevent sign E extension during shifting void B putword target word int target unsigned int word int read hreg void putint void putstr void B config out int high byte middle byte low byte int high word middle word low word int latch high latch middle latch low while read hreg target INT STATUS amp TX EMPTY wait for target s transmit byte registers to clear B config out configure port B to write break word into bytes high byte word gt gt 16 middle byte word amp OxOOFF00 gt gt 8 low byte word amp OxOO00FF create command words to write data to target high word WRITE BYTE amp target HI BYTE high byte middle word WRITE BYTE amp target MID BYTE middle byte low word WRITE BYTE amp target LO BYTE low by
53. Loo Lo LL So Lo Loo Lo LL mo Loo ost N A ABA ABA 9 AA A b Mantissa Data Range 3 Exponent Reserved Ela HE 8 Qoo D Q wu A Exponent Value Hex 000000 003FFF 004000 7FFFFF c Exponent Data Range E 003FFF E 000000 E 000000 E 003FFF M 800000 M BFFFFE 0 M 400000 M 7FFFFF Largest Smallest Smallest Largest Negative Number Negative Number Positive Number Positive Number 1 00 x 2 8192 0 5 x 28192 0 5 x 28192 0 999 x 2 8192 0 109 x 10 2817 0 916 x 102816 0 916 x 102816 0 109 x 10 2817 Note E Exponent and M Mantissa d Mantissa and Exponent Data Range Figure 4 1 Mantissa and Exponent Data Range of C floating point rithmeti IEEE 4 4 DSP56KCC User s Manual MOTOROLA checking and exceptions in favor of real time execution speed and efficient implementation on the DSP56000 DSP56001 All exception conditions are handled in line i e an exception routine is not invoked according to predefined rules The reason for this is the fact that real time systems must continue to process data non stop It is not possible to stop execution until the application program determines a solution to the problem and corrects it and so there is no choice but to provide an output with some amount of error should an exception occur Table 4 5 Floating point Format Description IEEE Format Characteristic DSP56KCC Value Decimal Value m 2 e ebias Mantissa 24 bit two s
54. M MOTOROLA DSP56KCC User s Manual A 141 strtok strtok EXAMPLE include lt stdio h gt include lt string h gt void main char str1 this is string tnumber one char str2 a b c char token while token strtok str1 t NULL printf s token stri NULL printf n token strtok str2 printf s token token strtok NULL printf 96s token token strtok NULL printf s n token if token strtok NULL l NULL printf error strtok busted n prints to standard output this is string number one a bc pe eee M A 142 DSP56KCC User s Manual MOTOROLA strtol strtol NAME strtol String to long integer SYNOPSIS include lt stdlib h gt long int strtol const char nptr char endptr int base DESCRIPTION The strtol function converts and returns the string pointed to by nptr to a long integer First strtol decomposes nptr into three sections 1 an initial possibly empty sequence of white space characters 2 a subject in the form of an integer constant and 3 a final string of one or more unrecognized characters including the terminating null character of the input string If the first unrecognized character is not NULL a pointer to that character is stored in to the object that endptr points to If the string is empty or the subject contains no floating
55. Modifiers Associations Operand Constraint Modifier Address Register rx j Rn s paired offset register Destination Register a b e Upper word a1 b1 h Lower word a0 b0 k Extension a2 b2 Multiplier Register x0 y0 9eg Select other register portion i Strip 0 1 from register name Source Register x0 x1 y0 y1 g Select other register portion i Strip 0 1 from register name Constant number p 16 bit immediate value q 24 bit immediate value Memory Location 9ef Memory space identifier Any one of above corresponding modifier 5 2 3 Explicit Register Saving It is possible to manually perform register allocation in fact this may simplify the process of converting an existing body of DSP56000 DSP56001 assembly language subroutines to in line assembly code The programmer need only identify each register explicitly ref erenced in the assembly code and list them in the reg save argument region see Sec tion 5 2 This guarantees that the content of each register is preserved across __asm calls Use of registers rO and r6 is prohibited in the assembly code because they are re served for the C compiler during run time where rO is the frame pointer and r6 is the stack pointer Registers Mn are used by the compiler as temporary registers and Nn are not used by the C compiler at all As a result these registers do not need to be saved un less the programmer uses them in assembly cod
56. S P EAE 3 3 3 5 OI iiu Ek ES ERG a Ex 6 2 Option Assemble asm String Eire qune Soror 3 30 BO 2 u s satel nena le ds 3 30 Option Command line Bdirectory 3 4 SDPREPBDX ti ciini te tt 3 4 SEPEIEE ue tUe ra reden dua 3 5 INDEX 4 G56KCC User s Manual AN ros d utaris il 3 5 Option Compile fcaller saves 3 20 fcond mismatch 3 20 ffixed REG 2 44 eas oes 3 20 fforce addr roe 3 20 finline functions 3 20 fkeep inline functions 3 20 fno defer pop 3 19 SIHOSODE Suda as 3 19 fno peephole 3 19 fno strength reduce 3 19 IVOlatile us oe tee aia tia es 3 20 fwritable strings 3 20 FU uvae q eT wee 3 22 ml memory 3 24 mno biv plus linv promotion 3 23 mno do loop generation 3 23 mno dsp optimization 3 23 mstack check 3 23 MX MEMOTY usse eem xs 3 23 sys MEMO ir asl a 3 24 3 oues Bo Se ee ae Se eee Reh en 3 23 pedantic nia e a ee 3 24 a loca A oS 3 25 A whe tee acd Beets 3 25 SW sachet dae E de 3 25 ON ee we NA 3 25 Wall nora ed 3 29 Wcast qual vasa wearers die vinden 3 29 Wid clash LEN 3 29 Wimplicit a eg ie leads 3 27 Wpointer arith 3 29 Wreturn type 3 27 WshadowW cido ros 3 29 WSWIICIY eere er E eed ie cus 3 29 MOTOROLA Wunused 3 28 Wwrite str
57. S3 record addresses are computed based on the data word count AAA A A AA A M MOTOROLA DSP56KCC User s Manual C 21 Srec Srec r d O C 22 DSP56KCC User s Manual MOTOROLA Appendix D GNU Debugger GDB Introduction Appendix E contains the GNU Debugger Manual This preface to the GDB manual describes the differences between the standard gdb source level debugger and the gdb56 debugger that uses the Motorola DSP56000 family simulator A short description of the way the simulator is embedded in gdb56 will help explain some of the differences The DSP56000 device is simulated by the same non display version of the simulator program that is supplied with the DSP56000 Development Software The simulator is linked with the gdb program When a program is executed on the simulated DSP56000 it is done via direct function calls to the simulator library functions rather than via ptrace calls to an inferior process as in other versions of gdb Commands Not Implemented 1 The attach and detach commands are not implemented because the simulator program is linked directly to the gdb56 program As a result there is no ability to attach or release a separately running simulation 2 The core file command is not implemented at this time All other commands work as documented in the GDB Manual for the gnu Source Level Debugger Third Edition October 1989 Some enhancements listed below were necessary to accommodate ope
58. SCCR n movep C000 x IPR n andi fc mr n nEND jmp END __asm org p 001cnm move r7 n nop ee MOTOROLA DSP56KCC User s Manual 5 15 5 2 5 Controlling Labels Generated by the Compiler Using the _ asm keyword it is possible for the programmer to override the compilers label generation conventions for subroutines and global variables This may be useful for 1 calling assembly language subroutines 2 Calling C subroutines from assembly code 3 referencing assembly language global variables from C 4 referencing global C variables from assembly code 5 2 5 1 Calling Assembly Subroutines Calling a subroutine or function requires using a label that points to the subroutine or function The C compiler uses a predetermined labeling convention see Section 4 7 and does not generate arbitrary labels like most assembly programs In order to call as sembly subroutines labeled in an arbitrary fashion _ asm can be used to overwrite the C convention label with an arbitrary label To illustrate how to use the _ asm directive for this purpose Example 5 24 reads the data at x memory location 100 and y memory location y 2 For test purposes the y memory space is filled with the integer sequence 0 through 9 and the x memory space is left uninitialized The printf statement prints the data returned from the functions ValOfX 100 and ValOfY y 2 These two functions are constructed in assembly code and r
59. STOP command Note The two underscores are distinguished by a blank but it should be typed as two consecutive underscores should be typed in as section crt0 org x global F stack safety F stack safety dc 16 global F mem limit F mem limit dc S7fff top of memory global F_ break F break dc S7fff base of HEAP 32k words globalF _y size F y size dc DSIZE base of STACK org p global F_ _start F_ _start move DSIZE r6 move SSI_RCV_D0 r7 initialize the stack pointer to base of stack initialize pointer to SSI receive buffer i i move 1 m7 P movec 0100 sr permit level 1 2 and 3 exceptions jsr Fmain run user program global F_ _crt0_end F_ _crt0_end stop all done endsec end of section crt0 List F 4 Crt0 file C F 10 DSP56KCC User s Manual MOTOROLA globals h This file contains definitions of all global variables and data structures It is included at the top of files that use global data All global variables declared in main c E E E constants used by IO C routines define TX_EMPTY 2 SCI port status register flags define TX_RDY 4 define RX_FULL 4 define NUL 0 ASCII character codes define BEEP 7 define BACKSPACE 8 define LEFT 8 define DOWN 10 define UP 11 define RIGHT 12 define ENTER 13 define CANCEL 24 define ESCAPE 27 define SPACE 32 define DEL 127 define ARROW_UP 65 2nd characters of escape sequences
60. The data in assembly language programs must be accessible to C programs to take full advantage of the DSP56000 family architecture since the C language cannot access all of the DSP56000 features directly One way to access this data is through global data which can be defined in assembly language and accessed in the C program environ ment This feature is particularly useful to allocate modulo buffers for C variables De tailed information on modulo buffers can be found in the DSP56000 DSP56001 User s Manual Section 5 Address Generation Unit and Address Modes Example 5 27 Generate data with assembly language The data file sqtbl asm is generated in assembly language and consists of the squares of the numbers 0 8 Notice that directives BSC DC DS DSM and DSR see Section 6 3 of the Motorola DSP56000 Macro Assembler Reference Manual can be used depending on the A ess QQ gt gt gt _A z _ AAA 5 18 DSP56KCC User s Manual MOTOROLA application C gt type sqtbl asm section data global table org y table dc 0 1 4 9 16 25 36 49 64 endsec Example 5 28 Access data with C This test program called test c prints the value of 5 on the screen C gt type test c include lt stdio h gt extern int SQUARE asm table main printf square of d is d n 5 SQUARE 5 The following two command lines for Example 5 28 test the two programs sqtbl asm and test c CA gt g56k test c sqtbl asm C
61. The function setjmp always returns a zero The function longjmp takes two arguments an environment buffer and a return value It restores all registers from the buffer passed including the frame pointer and stack point er It then places the return value passed into accumulator A and sets the ccr to reflect the return value just stored in accumulator A The function longjmp discards the return program counter on the hardware stack and jumps to the address pointed to by the pro gram counter stored in the buffer This file must conform to the include files setimp h and longjmp h Since these two algo rithms are very straightforward modification of the file may be not needed If modification is absolutely necessary then the ANSI standard of the functions setimp and longjmp should be followed 6 6 Host Supported I O printf et al The library provided with DSP56KCC includes a full implementation of the ANSI C stan dard input and output routines These routines already work with gdb56 and run56 and can easily be embedded in custom applications Anywhere that formatted I O is desired these library routines can be included to simplify development The entire suite of routines is based upon a simple communication protocol between the DSP and a host resident l O driver so porting the entire system to custom hardware is trivial 6 6 1 DSP functions _send and _ receive All standard I O functions no matter how complicated
62. This construct is allowed re gardless of what kind of data is officially supposed to reside at addr gt __ ____ _z_ _______ _ _ _ _ _ __ _ gt gt MOTOROLA DSP56KCC User s Manual E 47 3 21 Program Variables The most common kind of expression to use is the name of a variable in your program Variables in expressions are understood in the selected stack frame see section Selec tion they must either be global or static or be visible according to the scope rules of the programming language from the point of execution in that frame This means that in the function foo a inta bar a int b test bar b the variable a is usable whenever the program is executing within the function foo but the variable b is visible only while the program is executing inside the block in which b is de clared As a special exception you can refer to a variable or function whose scope is a single source file even if the current execution point is not in this file But it is possible to have more than one such variable or function with the same name if they are in different source files In such a case it is not defined which one you will get If you wish you can specify any one of them using the colon colon construct block variable Here block is the name of the source file whose variable you want 3 22 Artificial Arrays It is often useful to print out several successive objects of the same type in memory a s
63. Wiley and Sons 1973 CLASSIFICATION ALGORITHMS Mike James New York NY Wiley Interscience 1985 Spectral Analysis STATISTICAL SPECTRAL ANALYSIS A NONPROBABILISTIC THEORY William A Gardner Englewood Cliffs NJ Prentice Hall Inc 1988 THE FAST FOURIER TRANSFORM AND ITS APPLICATIONS E Oran Brigham Englewood Cliffs NJ Prentice Hall Inc 1988 THE FAST FOURIER TRANSFORM AND ITS APPLICATIONS R N Bracewell New York NY McGraw Hill Company Inc 1986 Speech ADAPTIVE FILTERS STRUCTURES ALGORITHMS AND APPLICATIONS Michael L Honig and David G Messerschmitt Higham MA Kluwer Academic Publishers 1984 DIGITAL CODING OF WAVEFORMS N S Jayant and P Noll Englewood Cliffs NJ Prentice Hall Inc 1984 DIGITAL PROCESSING OF SPEECH SIGNALS Lawrence R Rabiner and R W Schafer Englwood Cliffs NJ Prentice Hall Inc 1978 LINEAR PREDICTION OF SPEECH J D Markel and A H Gray Jr New York NY Springer Verlag 1976 MEO D 20 DSP56KCC User s Manual MOTOROLA SPEECH ANALYSIS SYNTHESIS AND PERCEPTION J L Flanagan New York NY Springer Verlag 1972 SPEECH COMMUNICATION HUMAN AND MACHINE D O Shaughnessy Reading MA Addison Wesley Publishing Company Inc 1987 Telecommunications DIGITAL COMMUNICATION Edward A Lee and David G Messerschmitt Higham MA Kluwer Academic Publishers 1988 DIGITAL COMMUNICATIONS John G Proakis New York NY McGraw Hill Publishing Co 1983 AAA AAA A
64. a backtrace of the entire stack one line per frame for all frames in the stack You can stop the backtrace at any time by typing the system interrupt character normally Control C backtrace n btn Similar but print only the innermost n frames YS EEE A AAA E 38 DSP56KCC User s Manual MOTOROLA backtrace n bt n Similar but print only the outermost n frames The names where and info stack are additional aliases for backtrace Every line in the backtrace shows the frame number the function name and the program counter value If the function is in a source file whose symbol table data has been fully read the back trace shows the source file name and line number as well as the arguments to the func tion The program counter value is omitted if it is at the beginning of the code for that line number If the source file s symbol data has not been fully read just scanned this extra informa tion is replaced with an ellipsis You can force the symbol data for that frame s source file to be read by selecting the frame See section Selection Here is an example of a backtrace It was made with the command bt 3 so it shows the innermost three frames 0 rtx_equal_p x rtx Ox8e58c y rtx 0x1086c4 gp rms cc rtlanal c line 337 1 Ox246b0 in expand call 2 Ox21cfc in expand expr More stack frames follow The functions expand call and expand expr are in a fil
65. a single relocatable code module If the L option is encountered the linker treats the accompanying pathname as a library file and searches the file for any outstanding unresolved references If a module is found in the library that resolves an outstanding external ref erence the module is read from the library and included in the load file out put The linker continues to search a library until all external references are resolved or no more references can be satisfied within the current library The linker searches a library only once when it is encountered on the com mand line Therefore the position of the L option on the command line is significant M lt mapfil gt This option specifies that a map file is to be created mapfil can be any le gal operating system file name including an optional pathname If a pathname is not given the file will be created in the current directory If no file name is supplied the linker will use the basename file name without extension of the first file name encountered in the link input file list The re sulting output file will have an extension of map The linker will not gener ate a map file if the M option is not specified The M option should be specified only once N Indicates that the linker should ignore case in symbol names Ordinarily the linker is sensitive to upper and lower case letters in symbol names If the N option is supplied the linker maps all symbol characters to
66. a wide character wchar_t At most n and never more than MB_CUR_MAX characters from s will be examined and converted If s is a NULL pointer mbtowc returns zero If s is not NULL mbtowc returns 1 zero if s points to a NULL character 2 the number of characters that comprise the multibyte character or 3 1 if an invalid multibyte character is formed In no case will the return value exceed n or the MB CUR MAX macro SEE ALSO mblen Determine the length of a multibyte character mbstowcs Convert a multibyte string into a wide character string wctomb Convert a wide character into a multibyte character SPECIAL NOTE The DSP56000 DSP56001 does not provide byte addressing thus characters always require an entire word of memory each One way to better utilize data memory with a run time cost is to combine the ANSI data type wchar_t and the special ANSI multibyte and wide character library routines eee l MOTOROLA DSP56KCC User s Manual A 79 mbtowc mbtowc EXAMPLE include lt stdio h gt include lt stdlib h gt void main wchar_t wide 0 char mbstr abcde int convert convert mbtowc wchar_t NULL mbstr 2 printf d chars packed wide 0 6x n convert wide convert mbtowc amp wide mbstr strlen mbstr printf d chars packed wide 0 6x n convert wide convert mbtowc amp wide mbstr 2 printf d chars packed wide 0 6x n convert wide pri
67. aO O F 44 DSP56KCC User s Manual MOTOROLA Symbols Nel OM asm asm reg save Cc sig goto dispatch c sig handlers _ DATE _ DSP56K e FILER _ fp shift _ INCLUDE LEVEL _ LINE mem limit _ receive send _ Sig dfl sig drop count _ Sig err Sig ign _ Stack safety _ STDC__ MOTOROLA G56KCC User s Manual 804806 aida GA 2 1 A ACI MUNI ONDES EE RTT T CP 2 5 EDOM 4 co a pt a esae de dtu dem ino A 7 zi CREDE A 8 Accumulator Registers 4 8 AOS Ana A 9 Address ALU 1 Sewer RR 4 8 Address Offset Registers 4 8 Address Registers 4 8 affine arithmetic o tt bole ee oe ed 4 7 lO ta 3 3 3 19 4 20 A Sed dows 3 2 3 19 4 20 ANS se oe sewer tote erect UH9 1 1 A A ST A 10 asm Option s bic eene beris 3 3 3 30 asm56000 o ccc zx acsi aor cac ates C 2 Ala see td hacen Cae eae ee A 11 Up PEPPER E A 12 Itext d aei A tatu d de o A 13 zi MEN SVO SEPT A 14 cic NER MES A E TEE A 15 o A O See ee diit A 16 A A 2 1 2 3 B B option stat ed 3 3 3 4 b option isa 3 3 3 4 o MM ET 2 4 DIKO oieee tuc tee astare Ee my 6 8 Dseat abr scere dod tote So apes mach A 17 C option seee 3 3 3 6 CODO x1 irte td 3 3 3 30 CANOE 0 a ds 6 8 A 19 CBll 23 44 4 95 tania A 21 A 22 ehai Sada pos ac dac e e OS 4 2 4 8 GICIIDIO 6 126 Poor i UR Potes C 7 e PEDE C 8 esser C 9 COPE Come En eben harte 1 3 3 1 compiler s dsp directory tree
68. address should be the memory address at which the file has been loaded GDB cannot figure this out for itself The symbol table of the file filename is added to the symbol table originally read EEE E 14 DSP56KCC User s Manual MOTOROLA with the symbol file command You can use the add file command any number of times the new symbol data thus read keeps adding to the old The symbol file command forgets all the symbol data GDB has read that is the only time symbol data is forgotten in GDB info files Print the names of the executable and core dump files currently in use by GDB and the file from which symbols were loaded While all three file specifying commands allow both absolute and relative file names as arguments GDB always converts the file name to an absolute one and remembers it that way The symbol file command causes GDB to forget the contents of its convenience variables the value history and all breakpoints and auto display expressions This is because they may contain pointers to the internal data recording symbols and data types which are part of the old symbol table data being discarded inside GDB A A AAA O MM MOTOROLA DSP56KCC User s Manual E 15 AA E 44m A A A A A or EU E 16 DSP56KCC User s Manual MOTOROLA D 3 Compiling Your Program for Debugging In order to debug a program effectively you need to ask for debugging information when you compile it This information in t
69. are not selected an environment variable named DSPLOC must be set in the autoexec bat file The install program will provide directions The lines to be added to the autoexec bat file follow A ____ _________ gt gt _ _____ MOTOROLA DSP56KCC User s Manual 2 1 a TERMCAP must be set to the current location of lt compiler s dsp directory tree gt dsp etc termcap SET TERMCAP lt DSP location gt DSP ETC TERMCAP for example if the directory lt compiler s dsp directory tree gt is d usr mydir then the line to be added is SET TERMCAP D USR MYDIR DSP ETC TERMCAP b TERM must be set to indicate the type of display to be used probably nansi mono SET TERM NANSI MONO c DSPLOC need only be set if the default output drive or the default location is not chosen If DSPLOC is set it must be set to the location of the dsp directory tree For example if the user installed the compiler s directory tree dsp in the directory d usr mydir then DSPLOC would need to be set as d usr mydir SET DSPLOC lt compiler s dsp directory tree if the directory compiler s dsp directory tree is d usr mydir then SET DSPLOC D NUSRMMYDIR 5 Make sure that lt compiler s dsp directory tree gt dsp bin is included in the path instruction This is needed by command com if it is to find g56k If the default drive and path were chosen then the path c dsp bin would need to be added as fol lows PATH C DSP BIN
70. at least one instruction has been executed If it did not do this you would be unable to proceed past a breakpoint without first disabling the breakpoint This rule applies whether or not the breakpoint already existed when the program stopped break if cond Set a breakpoint with condition cond evaluate the expression cond each time the breakpoint is reached and stop only if the value is nonzero stands for one of the possible arguments described above or no argument specifying where to break See section Conditions for more information on breakpoint conditions tbreak args Set a breakpoint enabled only for one stop args are the same as in the break command and the breakpoint is set in the same way but the breakpoint is auto matically disabled the first time it is hit See section Disabling GDB allows you to set any number of breakpoints at the same place in the pro gram There is nothing silly or meaningless about this When the breakpoints are conditional this is even useful See section Conditions 3 10 2 Deleting Breakpoints It is often necessary to eliminate a breakpoint once it has done its job and you no longer want the program to stop there This is called deleting the breakpoint A breakpoint that has been deleted no longer exists in any sense it is forgotten q z _ ____ _ gt z__ z z__ ____ gt _ _ _____ 1 E 28 DSP56KCC User s Manual MOTOROLA With the clear
71. atof String to double atol String to long integer striod String to double strtol String to long integer strtoul String to unsigned long integer EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf atoi 709 d n atoi 709 prints to standard output atoi 709 709 AAA A A A A A U E MOTOROLA DSP56KCC User s Manual A 15 atol atol NAME atol String to long integer SYNOPSIS include lt stdlib h gt long atol const char nptr DESCRIPTION The atol function converts the string pointed to by nptr to a long integer If the result can not be represented the behavior is undefined This is exactly equivalent to strtol nptr char NULL 10 SEE ALSO atof String to double atoi String to long integer striod String to double strtol String to long integer strtoul String to unsigned long integer EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf atol 709 ld n atol 709 prints to standard output atol 709 709 r H o X O A 16 DSP56KCC User s Manual MOTOROLA bsearch bsearch NAME bsearch Perform binary search SYNOPSIS include lt stdlib h gt void bsearch const void key const void base size_tnmemb size_t size int compare const void const void DESCRIPTION The bsearc
72. bar cln to the library foo Because interactive input is taken from the standard input channel of the host environment it is possible to create a batch of librarian commands and feed them to the program for execution via redirection For more infor mation on interactive commands invoke the librarian without any argu ments and enter help OPTIONS Only one of the following command line options may be given for each invo cation of the librarian Option letters may be entered in either upper or low er case If no option is given the librarian operates as if the U option were specified EES C 10 DSP56KCC User s Manual MOTOROLA dsplib dsplib a This option adds the modules in the file list to the named library The library file must exist and the modules must not already be in the library C Create a new library file and add any specified modules to it If the library file already exists an error is issued d Delete named modules from the library If the module is not in the library an error is issued f lt argfil gt This option indicates that an external file should be read for further com mand arguments It is useful in host environments where the command line length is restricted argfil must be present on the command line but can be any legal operating system file name including an optional pathname argfil is a text file containing module names to be passed to the librarian The names need be separated only by wh
73. cancel execution of a function call with the return command This command has the effect of discarding the selected stack frame and all frames within it so that control moves to the caller of that function You can think of this as making the discarded frame return prematurely First select the stack frame that you wish to return from see section Selection Then type the return command If you wish to specify the value to be returned give that as an argument This pops the selected stack frame and any other frames inside of it leaving its caller as the innermost remaining frame That frame becomes selected The specified value is stored in the registers used for returning values of functions The return command does not resume execution it leaves the program stopped in the state that would exist if the function had just returned Contrast this with the finish com mand see section Stepping which resumes execution until the selected stack frame re turns naturally AA A A A AA A A MM O MOTOROLA DSP56KCC User s Manual E 63 pe eee O T U E 64 DSP56KCC User s Manual MOTOROLA D 11 Canned Sequences of Commands GDB provides two ways to store sequences of commands for execution as a unit us er defined commands and command files 3 33 User Defined Commands A user defined command is a sequence of GDB commands to which you assign a new name as a command This is done with the define command defin
74. char c return isgraph int c amp amp isalnum int c isspace c char c switch c case case f case n case r case t case v List F 12 The list of ctype functions eS EEE MOTOROLA DSP56KCC User s Manual F 35 return 1 return 0 isxdigit c char c return isdigit c 0x40 int c amp amp 0x47 gt int c 0x60 lt int c amp amp 0x67 gt int c tolower c char c return isupper c char int c 0x20 c toupper c char c 1 return islower c char int c 0x20 c pe ae O F 36 DSP56KCC User s Manual MOTOROLA project asm Main program to perform the special audio effects which is a simple IIR filter operation for an exercise section project xdef PROJECT xref SSI_RCV_DO SSI_XMT_DO VOLUME COEF_PTR xref DATA include save_restore mac org P PROJECT the beginning of your special audio effect program SAVE_REG ori 8 mr scaling up mode and bf cer clear limit bit move DATA r4 filter states move x COEF_PTR r0 filter coefficients move x VOLUME y1 gain move y lt SSI_RCV_DO yO input audio signal mpy yO yl a x r0 x0 y r4 y0 input yl x0 w n 2 y0 a12 2 mac x0 y0 a x r0 x1 y r4 y0 xl w n 1 y0 a11 2 macr xl y0 a x1 x r0 y r4 y0 w n 1 goes to w n 2 y0 b12 2 mac x0 y0 a a x r0 y r4 y0 w
75. complement normalized fractional mantissa This gives a precision of approximately 7 decimal digits A hidden leading 1 is not implemented in this format see Fig ure 4 1 Largest Positive Mantissa 7FFFFF Smallest Positive Mantissa 400000 Floating point Zero Mantissa 000000 Smallest Negative Mantissa BFFFFF Largest Negative Mantissa 800000 Reserved Mantissas 000001 through 3FFFFF and C00000 through FFFFFF exponent 14 bit exponent unsigned integer biased by ebias 1FFF Stored as a 24 bit unsigned integer with 10 leading zeros The 14 bit exponent used by DSP56KCC provides a larger dynamic range than IEEE double precision format Largest exponent biased 003FFF 2 8192 Smallest exponent biased 000000 2 819 Reserved exponents 004000 through FFFFFF Notes 1 No distinct exponents are reserved for plus infinity minus infinity Not a Number IEEE NaN minus zero or denormalized numbers as is done in IEEE format 2 All reserved mantissas are illegal since they represent denormalized mantissas 3 If the 15 bit is set exponent overflow has occurred 4 Ifthe 16 bit is set exponent underflow has occurred _ _ _ _ ________ ____ _ __ _ _ _ _ __ Q_ _ _ lt A AAA MOTOROLA DSP56KCC User s Manual 4 5 Table 4 6 Comparison of DSP56KCC and IEEE 754 1985 CHARACTERISTIC DSP56KCC FORMAT IEEE FORMAT Mantissa Precision 23 bits 24 bits Hidden Lea
76. control B ssi control register B int status ssi status register int data ssi data register y struct B C ports t int B control port B control register int C control port C control register int B direction port B data direction register int C direction port C data direction register int B data port B data register int C data port C data register y Definitions of global pointers to on chip peripherals amp control registers extern struct sci port sci global pointer to sci port extern struct ssi port ssi global pointer to ssi port extern struct B C ports ports global pointer to B and C ports ee F 12 DSP56KCC User s Manual MOTOROLA extern int int_priority pointer to interrupt priority register extern int A_control pointer to port A control register extern char ungetcbuf Definitions of global pointers containing current project effect settings extern int status array of current project effect settings rn M MOTOROLA DSP56KCC User s Manual F 13 main c This file contains the declarations for global variables the main function and initialization functions The function main initializes global variables and calls the routines to initialize the I O ports and the special audio effects model The definitions of data types are inc
77. copy is done by first placing the n words into a temporary buffer and then moving the temporary buffer into the final location this allows the source and destination areas to overlap SEE ALSO memcpy Copy one memory area to another EXAMPLE include lt stdio h gt include lt string h gt struct test char cartoon 20 int value g1 g2 flintstones 709 void main memmove amp g1 amp g2 sizeof struct test printf watch the 96s n g1 cartoon prints to standard output watch the flintstones i A 86 DSP56KCC User s Manual MOTOROLA memset memset NAME memset Initialize memory area SYNOPSIS include lt string h gt int memset void s int c size tn DESCRIPTION The memset function copies the value c converted to an unsigned char into the first n words of the object pointed to by s SEE ALSO memcpy Copy one memory area to another SPECIAL NOTE Due to the word orientation of the DSP56000 DSP56001 the memory model version of memset may not act as expected when attempting to initialize double size elements the x memory portion is unaffected eeaeee M MOTOROLA DSP56KCC User s Manual A 87 memset memset EXAMPLE include lt stdio h gt include lt string h gt struct test char cartoon 20 int value void main struct test local auto struct local is initialized to all nines memset amp local 9 sizeo
78. definition of the constant DELAY Without any option the include file should be located in the currently working directory since it is not in the standard include directory Assuming that the include file myinclude h is desired to be in the directory inc the following sequence of the commands explains how the I option is used to include the file myinclude h in the inc directory with the control line include myinclude h in the foo c program ee ate cue AIr foo c inc ON dir ing myinclude h C gt type foo c include myinc h this is the control line to include it main b int cnt cnt DELAY while cnt D 3 10 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options C gt type inc myinc h define DELAY 100 C gt g56k I inc foo c ON ALE a cld foo c inc I This option is always used in conjunction with the IDIR option and limits the file search to look for file inclusions include filename whereas IDIR alone directs C compiler to search the directory DIR for both file inclusion lt filename gt and filename Any directories specified with I options before the l option are searched only for the case of include filename they are not searched for include lt filename gt If additional directories are specified with I options after the I option these direc tories are searched for both include filename and include lt filename gt direc ti
79. family architecture before attempting to program it in C The following sections provide important information on data types storage classes memory and register usage and other topics which will be useful to the DSP56000 application developer programming in C 4 2 Identifiers An identifier is defined as a sequence of letters digits and underscore characters _ The first character must be a letter or underscore DSP56KCC identifier length limits are listed in Table 4 1 Table 4 1 Identifier Length Limits Identifier Storage Class Length Global Static External Linkage 255 Auto unlimited 4 3 Predefined Preprocessor Macro Names DSP56KCC supports and expands all ANSI defined macros and three additional non ANSI predefined macro names Table 4 2 lists the macros and their explanation 4 4 Data Types and Sizes Due to the word orientation of the DSP56000 family 24 bit words all data types are I BR EK MOTOROLA DSP56KCC User s Manual 4 1 aligned on word boundaries This has several side effects one of which is that sizeof char is equal to sizeof int Table 4 2 Predefined Macro List and Explanation MACRO ANSI Explanation J LINE YES The line number of the current source line a decimal constant OFILE _ YES The name of the source file a character string _ DATE YES The compilation date a character string of the form Mmm dd yyyy
80. floating point lib 1799 fpinit asm 2 0 Library initialization subroutine 2329 fpadd asm 2 0 Floating point add 3860 fpsub asm 2 1 Floating point subtract 3072 fpcmp asm 2 1 Floating point compare 2605 fpmpy asm 2 0 Floating point multiply 2250 fpmac asm 2 1 Floating point multiply accumulate 2712 fpdiv asm 2 0 Floating point divide 3835 fpsqrt asm 2 0 Floating point square root 2873 fpneg asm 2 0 Floating point negate 2026 fpabs asm 2 0 Floating point absolute value 1953 fpscale asm 2 0 Floating point scaling 2127 fpfix asm 2 0 Floating to fixed point conversion 3953 fpfloat asm 2 0 Fixed to floating point conversion 2053 fpceil asm 2 0 Floating point CEIL subroutine 1771 fpfloor asm 2 0 Floating point FLOOR subroutine 2119 durbin asm 1 0 Solution for LPC coefficients 5615 durbin hlp 1 0 Help file for DURBIN ASM 2904 fpfrac asm 2 0 Floating point FRACTION subroutine 1862 Functions log2 asm 1 0 Log base 2 by polynomial 1118 approximation u OQ M MOTOROLA DSP56KCC User s Manual D 9 DSP56KCC User s Manual Document ID Version Synopsis Size log2 hlp Help for log2 asm 719 log2t asm 1 0 Test program for log2 asm 1018 log2nrm asm 1 0 Normalizing base 2 logarithm macro 2262 log2nrm hlp Help for log2nrm asm 676 log2nrmt asm 1 0 Test program for log2nrm asm 1084 exp2 asm 1 0 Exponential base 2 by polynomial 926 a
81. foo int rnr M 3 26 DSP56KCC User s Manual MOTOROLA Compile Phase Options main Int I foo i int foo a if a gt 0 return a CoNo g56k W foo c foo c In function main foo c 4 warning i may be used uninitialized in this function foo c In function foo foo c 11 warning this function may return with or without a value Wimplicit Warn whenever a function is implicitly declared Example 3 28 The function foo is declared implicitly in the program foo c the Wimplicit option will generate a warning message for this situation ENS foo c C gt type foo c main foo int foo C gt qook Wimplicit foo c foo c In function main foo c 3 warning implicit declaration of function foo CN LE a cld foo c Wreturn type Warn whenever a function is defined with a return type that defaults to int Also warn about any return statement with no return value in a function whose re turn type is not void A 1 MOTOROLA DSP56KCC User s Manual 3 27 Compile Phase Options Example 3 29 The function foo is declared as a function that should return an integer but in this case does not return an integer The Wreturn type option generates a warning message in this situation EN dir foo c
82. formats described in the previous section x is followed by a slash and an output format specification followed by an expression for an address The expression need not have a pointer value though it may it is used as an integer as the address of a byte of memory See section Expressions for more infor mation on expressions For example x 4xw sp prints the four words of memory above the stack pointer in hexadecimal The output format in this case specifies both how big a unit of memory to examine and how to print the contents of that unit It is done with one or two of the following letters These letters specify just the size of unit to examine b Examine individual bytes h Examine halfwords two bytes each w Examine words four bytes each Many assemblers and cpu designers still use word for a 16 bit quantity as a holdover from specific predecessor machines of the 1970 s that really did use two byte words But more generally the term word has always referred to the size of quantity that a machine normally operates on and stores in its registers This is 32 bits for all the machines that GDB runs on g Examine giant words 8 bytes SEES MOTOROLA DSP56KCC User s Manual E 51 These letters specify just the way to print the contents Print as integers in unsigned hexadecimal qd Print as integers in signed decimal Print as integers in unsigned decimal Print as integers in
83. function function break offset break offset Set a breakpoint some number of lines forward or back from the position at which execution stopped in the currently selected frame break linenum Set a breakpoint at line linenum in the current source file That file is the last file whose source text was printed This breakpoint will stop the program just before it executes any of the code on that line break filename linenum Set a breakpoint at line linenum in source file filename A zz _ I AAA MOTOROLA DSP56KCC User s Manual E 27 break filename function Set a breakpoint at entry to function function found in file filename Specifying a file name as well as a function name is superfluous except when multiple files contain similarly named functions break address Set a breakpoint at address address You can use this to set breakpoints in parts of the program which do not have debugging information or source files break Set a breakpoint at the next instruction to be executed in the selected stack frame see section Stack In any selected frame but the innermost this will cause the program to stop as soon as control returns to that frame This is equivalent to a finish command in the frame inside the selected frame If this is done in the inner most frame GDB will stop the next time it reaches the current location this may be useful inside of loops GDB normally ignores breakpoints when it resumes execution until
84. g1 11 compiled by GNU C version 1 37 1 default target switches mdsp mlinv plus biv promotion mdo loop genera tion my memory mcall overhead reduction mrep mreload cleanup mnormalization reduction c dsp bin asm56000 c B foo cln cca00527 asm c dsp bin dspInk c B acld cidsplibicrtOB6y cln foo cln L c dsp lib lib56cy clb Caos adit a cld foo c A _ _ z _ gt AAA MOTOROLA DSP56KCC User s Manual 3 17 Preprocessor Phase Options UMACRO Undefine macro MACRO Example 3 20 An application program test c is being tested and some portions of the code need to be debugged The flag DEBUG may be turned on or off through the command line with the D and U options respectively This flag can then be used inside the program to enable disable debugging features within the program d dar debug c C gt type debug sc include lt stdio h gt main ifdef DEBUG printf debug a message n endif printf normal operation n C gt g56k UDEBUG debug c Qr TUNS 6 a La normal operation Wcomment Warn the user whenever the comment start sequence appears within a comment Example 3 21 A comment is enclosed with and and therefore is ignored by the preprocessor Any number of leading s are permitted within the comment and will not be reported however a warning message can be enabled by using the Wcomment option exces ai
85. gt lt opt gt lt opt gt The X option directs the linker to perform a little bit of different operation than standard operation of the linker The options are described below with ESE MOTOROLA DSP56KCC User s Manual C 15 dsplnk dsplnk their different operations performed All options may be preceded by NO to reverse their meaning The X lt opt gt sequence can be repeated for as many options as desired Option Meaning XC Relative terms from different sections used in an expression cause an error RSV Reserve special target processor memory areas e g DSP96000 DMA AEC Check form of address expressions RO Allow region overlap ESO Do not allocate memory below ordered sections ASC Enable absolute section bounds checking Z The linker strips source file line number and symbol information from the in put file Symbol information normally is retained for debugging purposes This options has no effect if incremental linking is being done see the I op tion C 16 DSP56KCC User s Manual MOTOROLA gdb56 gdb56 NAME gdb56 GNU Source level Debugger for DSP56000 DSP56001 SYNOPSIS gdb56 s SYMFILE e EXECFILE se FILE c COREFILE x FILE d directory nx q batch fullname help tty TTY cd DIR lt name gt lt core gt DESCRIPTION gdb56 is a source level symbolic debugger for C programs created by Ri chard Stallman for the GNU Project and distributed by
86. gt run56 a cld 5 2 5 4 Referencing Global C Variables from Assembly Language One DSP56KCC feature is that global data in a C program is available to assembly lan guage programs This feature is particularly useful when the data to be processed by an assembly language program is generated by the C program Example 5 29 provides co efficients that are used in Example 5 30 Example 5 29 Generate data with C Data file data c is generated by a C language program and contains the coefficients of an average filter which takes the average of the last four input data eea M UU MOTOROLA DSP56KCC User s Manual 5 19 cat data c data c int Cwaddr asm waddr int Ccadd _ _asm caddr int NTAP asm N 1 int Cwaddr 4 int Ccaddr 0x200000 0x200000 0x200000 0x200000 int NTAP 4 Example 5 30 4 tap FIR filter Access data with assembly language This FIR filter reads an input sample from memory location Y input and writes the filtered output to memory location y output The input data array is stored in X memory starting at waddr and the FIR coefficients are stored in Y memory starting at caddr Notice that the memory space for waddr and caddr is allocated in the C routine described in Example 5 29 cat fir asm org p move waddr r0 move caddr r4 move y N 1 mO move m0 m4 movep y input x rO cir a x r0 x0 y r4 y0 rep n 1 mac x0 y0 a x r0 x0 y r4 y0 macr x0 x0
87. handler and 2 the rti instruction is executed by the c sig dispatch function i 6 10 DSP56KCC User s Manual MOTOROLA Caution The signal handler must not contain the rti instruction at the end of the program regardless which language is used to program the interrupt The signal handler does not need to save or restore any context or registers The function _ c sig dispatch will not act like a normal C function because it never returns to its caller Instead it will return to the code that was executing when the interrupt happened by executing the rti instruction Assembly language interrupt handlers can coexist with C signal handlers The code in the signal file will not alter any interrupt vector except the one specified by the signal number passed to the signal function see the first of the three steps above The C signal inter face could be used with an assembly routine but would be unnecessarily slow To use an assembly language interrupt handler alter the vector e g interrupt 08 with a jsr to it e g jsr interrupt 08 or use a fast interrupt routine 6 4 2 Raise The raise function is used to simulate an interrupt The code in raise simply calls the entry in c sig goto dispatch that is matched to the interrupt vector specified by the signal number passed The ANSI standard signal handlers SIG DFL SIG ERR and SIG IGN are implemented by the hand coded functions __ sig df
88. heap This may be important when writing code for embedded applications When if a stack collision occurs the execution device such as run56 will report that the collision occurred Note All run time libraries provided have been compiled assembled without the stack checking option Thus it is possible to have a run time stack heap collision during execution of library routines 4 11 Optimization Techniques Implemented This section provides a brief overview of the optimization techniques currently implemented by DSP56KCC DSP56KCC implements most machine independent C language optimization techniques as well as machine specific optimizations By default the control program g56k enables all levels of optimization see chapter 3 Compiler Operation for command line options to disable all or part of the optimizer 4 11 1 Register Promotion and Lifetime Analysis The compiler automatically identifies all variables that are candidates for promotion to the register storage class Using standard data flow techniques lifetime analysis is performed to determine the best variables for promotion When variable lifetimes do not overlap more than one variable may be promoted to a single register 4 11 2 Common Sub expression Elimination A Common Sub Expression or CSE is created when two or more statements compute the same value When CSEs are detected during data flow analysis the compiler eliminates all but one of the computations and propa
89. indicates the type of the stream and how the stream may be accessed ES text type read only w text type write only a text type append only write after end of current file rb binary type read only wb binary type write only ab binary type append only write after end of current file re text type read and write W text type read and write any pre existing file is destroyed ar text type append only read write after end of current file rb binary type read and write wb binary type read and write any pre existing file is destroyed ab binary type append only read write after end of current file Note that opening a file that does not exist will fail if r is the first character in the mode string When opened the stream is initially line buffered SEE ALSO fputs Tz Write a string to a stream fgets Read a string from a stream fprintf Used to write formatted output to a stream eo A 38 DSP56KCC User s Manual MOTOROLA fopen fopen EXAMPLE include lt stdio h gt void main FILE stream fopen file new w char data 64 fprintf stream verify thisin fclose stream stream fopen file new r fgets data 64 stream fputs data stdout This example opens an new text file writes to the associated stream
90. instructions Move instructions Program control instructions Or Oh eee NS B 2 1 Arithmetic Instructions The instructions used for arithmetic operations are ABS Absolute value ADC Add long with carry ADD Add ADDL Shift left then add ADDR Shift right then add ASL Arithmetic shift accumulator left ASR Arithmetic shift accumulator right MOTOROLA DSP56KCC User s Manual B 1 CLR Clear accumulator CMP Compare CMPM Compare magnitude DIV Divide iteration MAC Signed multiply accumulate MACR Signed multiply accumulate and round MPY Signed multiply MPYR Signed multiply and round NEG Negate accumulator NORM Normalize accumulator iteration RND Round accumulator SUB Subtract SUBL Shift left then subtract SUBR Shift right then subtract Tcc Transfer conditionally TFR Transfer data ALU register TST Test B 2 2 Logical Instructions The instructions used for logical operations are AND Logical AND ANDI AND Immediate with control register EOR Logical exclusive OR LSL Logical shift accumulator left LSR Logical shift accumulator right NOT Logical complement on accumulator OR Logical inclusive OR ORI OR immediate with control register ROL Rotate accumulator left ROR Rotate accumulator right B 2 3 Bit Manipulation Instructions The instructions used for bit manipulation are
91. is invoked with the shell command gdb Once started it reads commands from the terminal until you tell it to exit A GDB command is a single line of input There is no limit on how long it can be It starts with a command name which is followed by arguments whose meaning depends on the command name For example the command step accepts an argument which is the number of times to step as in step 5 You can also use the step command with no argu ments Some command names do not allow any arguments GDB command names may always be abbreviated if the abbreviation is unambiguous Sometimes even ambiguous abbreviations are allowed for example s is specially de fined as equivalent to step even though there are other commands whose names start with s Possible command abbreviations are often stated in the documentation of the in dividual commands A blank line as input to GDB means to repeat the previous command verbatim Certain commands do not allow themselves to be repeated this way these are commands for which unintentional repetition might cause trouble and which you are unlikely to want to repeat Certain others list and x act differently when repeated because that is more useful A line of input starting with is a comment it does nothing This is useful mainly in com mand files See section Command Files GDB indicates its readiness to read a command by printing a string called the prompt This strin
92. is the process id of the process you want to debug The usual way to find out the process id of the process is with the ps util ity The first thing GDB does after arranging to debug the process is to stop it You can exam ine and modify an attached process with all the GDB commands that ordinarily available when you start processes with run You can insert breakpoints you can step and contin ue you can modify storage If you would rather the process continue running you may use the continue command after attaching GDB to the process When you have finished debugging the attached process you can use the detach com mand to release it from GDB s control Detaching the process continues its execution Af ter the detach command that process and GDB become completely independent once more and you are ready to attach another process or start one with run If you exit GDB or use the run command while you have an attached process you kill that process You will be asked for confirmation if you try to do either of these things The attach command is also used to debug a remote machine via a serial connection See section Attach for more info 3 8 Killing the Child Process kill Kill the child process in which the program being debugged is running under GDB This command is useful if you wish to debug a core dump instead GDB ignores any core dump file if it is actually running the program so the kill
93. library code can produces non deterministic results as the libraries have been written to utilize the complete set of registers g Produce COFF debugging information for gdb56 the GDB cross debugger for the DSP56000 DSP56001 A key feature afforded by the use of the GNU C compiler g56k teamed with the GNU source level debugger gdb56 is that the programmer is allowed to generate optimized code with debug information select options g O making it possible for the programmer to debug optimized code directly Due to the optimizations per formed it is possible that variables will not be defined unused variable elimination statements may not be executed dead code elimination and code may be execut ed early code motion This is a partial list of the oddities that may be encountered when debugging optimized code However the improved code performance due to optimization normally out weighs the problems encountered Example 3 23 The program foo c has a bug In this application the line i 2 should be i 2 In order to use the symbolic debugger gdb56 to locate this problem the g option is used when foo c is compiled This causes the compiler to generate additional information used by the debugger Cas IS foo c Edo type foo c main int i 100 2 C gt g56k g foo c CoNo dir a cld foo c C gt gdb56 a eld A A A __ e AAA 3 22 DSP56KCC User s Manual MOTOROLA Compile Phase Op
94. long int offset int whence DESCRIPTION The function fseek will set the file position indicator associated with the specified stream according to the values of offset plus an initial value indicated by whence Initial values derived of whence values are as follows SEEK_SET The initial value is the beginning of the file SEEK_CUR The initial value is the current position in the file SEEK_END The initial value is the end of the file The value of offset must either be zero or the value returned by a call to ftell SEE ALSO fopen Open a disk file and associate it with a stream fgetc Read a single character from a stream fclose Close a stream EXAMPLES The following function will read the last character in a text file specified by the parameter name include lt stdio h gt char last_in_file char name FILE tmp fopen name r char return_value void fseek tmp 1L SEEK_END return_value char fgetc tmp fclose tmp return return_value __ ___ _ gt gt _____ lt A AAA AAA MOTOROLA DSP56KCC User s Manual A 49 fsetpos fsetpos NAME fsetpos Set the file position indicator associated with a stream SYNOPSIS include lt stdio h gt int fsetpos FILE stream const fpos t pos DESCRIPTION The function fsetpos will change the file position indicator associated with the specified stream The value of pos must be the return v
95. maco01 arg calculates arg 0 01 mac02 arg calculates arg 0 02 mactwo arg1 arg2 calculates argi arg2 Note that multiplication on the DSP56000 DSP56001 treats data as fractions however the C programming environment does not support a fractional data type Therefore data will be passed as integers from the C programming environment and will be treated as fractional data in the DSP56000 DSP56001 This can be an advantage if fractional arith metic is desired since this is normally difficult to accomplish in C Note that the calling routine must ensure arg is in range to prevent overflow The following function declarations ANSI standard can be used to declare functions which are known to perform fractional arithmetic Internally the size of integers is the same as the size of fractions int macO1 int int macO2 int int mactwo int int These three functions can be called as follows int fractvalue fractvalue mac01 0x123456 the value 0x123456 is 0 142222166 in fractional fractvalue mactwo 0x123456 0x0147ae 0x0147ae is 0 001 The conversion between fractional data and integer data in hex form can be performed using the evaluate command in the DSP56000 simulator Example 5 31 General Template for Out of line Assembly Code The two sections of this out of line assembly code are mod1 and mod2 The first section implements 1 macO1 arg which takes a fractional argument and returns 0 01 times the argumen
96. number sequence srand 1638 spew out random numbers in the range 0 to 709 for printf 96d rand 709 prints to standard output 545 174 307 657 220 267 66 47 651 268 284 338 35 615 403 etc r O EOS MOTOROLA DSP56KCC User s Manual A 103 realloc realloc NAME realloc Change size of dynamically allocated storage area SYNOPSIS include lt stdlib h gt int realloc void ptr size_t size DESCRIPTION The realloc function changes the size of the storage area pointed to by ptr to size The contents of the storage area are unchanged If the new storage area is larger the value of the new area is indeterminate If ptr is null realloc acts like malloc If ptr was not dynamically allocated or the area was previously deallocated by a call to free the behavior is undefined If realloc is unable to allocate the new size storage area a null pointer is returned and the original storage area is unchanged SEE ALSO alloca Allocate storage in the stack frame calloc Dynamically allocate zero initialized storage free Free dynamically allocated storage malloc Dynamically allocate uninitialized storage pe eO O A 104 DSP56KCC User s Manual MOTOROLA realloc realloc EXAMPLE include lt stdio h gt void main char str if str char malloc size t 15 NULL error malloc failed exit 8 strc
97. othe r s 6 11 Signal A a e US Ea ao af n at 6 1 A 114 signal file 6 9 jme PORE A 116 SIPIPl cue A oar O Or eae A 117 A duit doi e Ret ud 4 2 can FEES A 118 SUID cxnea tte sawn dar A 120 A 121 A A Ee M eee C 20 stack pointer 4 9 4 11 6 2 standard directory search list 3 2 standard include directory 3 10 SUCAL zs ies ted Acer uds A 122 A 123 INDEX 5 SIC e ta A 124 LM SITCITIDI cima aches tn bo Pot Byers Baa A 125 y ODUOD idas 3 3 3 5 3 16 SECO ta ANM eerie A 127 WIRTUALSIZE 2 3 Juo o ce AVES AAA 3 26 5 21 SUCSPN cera cd ad A 129 SISMO arras a tas A 130 W SINE A 131 Woption 3 3 3 18 3 25 sida DID A 132 W option ooo 3 25 SIremp ee eer us A 133 Wall option 3 3 3 29 SUMO DY Ls Va A oes do ato doe A 134 Weast qual option 3 3 3 29 91 sinerien bat A 135 A 137 westombs A 154 A 155 A 156 A 157 A A O esse A 138 158 o Mc E A 139 wctomb s sssss A 160 SIOK Aa A 141 Wid clash LEN option 3 3 3 29 SHOP MPO E rU A 143 Wimplicit option 3 3 3 27 Strlo l A Oe ee A 145 Wpointer arith option 3 3 3 29 SUM a O A 147 Wreturn type option 3 3 3 27 SWAPNAME ssss 2 3 Wshadow option 3 3 3 29 Wswitch option 3 3 3 29 T Wunused option 3 3 3 28 lallus ced nue Soak EV ER
98. overflow checking and defining referencing of absolute memory locations Additionally this chapter covers implementation issues such as data type sizes Chapter 5 Mixing C and Assembly Language discusses the methods for using assembly language in conjunction with C language programs It covers the inclusion of assembly language within a C source file and also describes linking assembly language modules with C modules and linking C modules with assembly language modules Chapter 6 Software Hardware Integration describes how to modify a program s run time environment how to write software to handle interrupts and the setjmp longjmp ANSI library routines Appendix A Programming Support provides a complete description and brief example for every ANSI library subroutine distributed with the C compiler Appendix B DSP56000 1 Instruction Set and Assembler Directive Summary provides a brief overview of the assembly language instructions and assembler directives Appendix C Utilities provides DSP56000 1 Assembler manual pages for each of the supporting programming utilities provided with the compiler Appendix D Additional Support provides a description of software hardware support telephone numbers and suggested reading for the C language and various areas of DSP Appendix E Debugger provides a reproduction of the GNU debugger manual A _____ _ ____ _ gt _ _ _ _ _ _ lt A AAA MOTOROLA DSP56
99. precision specifies the minimum number of digits to appear if the value can be represented in fewer digits it will be expanded with leading zeros The default precision is 1 The result of printing a zero with precision zero is no characters this is independent of padding specified by field width x X The unsigned int argument is printed as an unsigned hexadecimal number Hexadecimal alpha characters a b c d e f will be printed in lower case when x is used and in upper case when X is used When used in association with the flag 0x will be prefixed to the result 0X in the X case Precision specifies the minimum number of digits to appear if the value can be represented in fewer digits it will be expanded with leading zeros The default precision is 1 The result of printing a zero with precision zero is no characters this is independent of padding specified by field width f The double argument is printed out in decimal notation of the form ddd ddd where precision specifies the number of digits to follow the decimal point The default precision 6 When precision is 0 and the flag is not specified no decimal point character will be printed A decimal digit will always follow at least one digit The value printed is rounded to the appropriate number of digits e E The double argument is printed out in the form d ddde dd where precision specifies the number of digits to follow the decimal point The default precis
100. record is pushed onto the stack and a new activation record is built with a dynamic link to the old frame pointer When the function returns the function s activation record is popped and the original activation record is restored to its original place on the stack gt 4 10 DSP56KCC User s Manual MOTOROLA X or Y Memory Option Selected L X Y Memory Option Selected TOP_OF_MEMORY FFFF Max Run Time Stack Run Time Stack Dsize Global Static Data Global Static Data F__y_size 1 word F__break 1 word F__mem_limit 1 word F stack safety 1 word abad Ferrno 1 word F fp shift 23 words data memory F time 1 word Figure 4 4 Default Data Memory Configuration main func_1 Sample C code func_1 activation record old frame pointer main activation record main activation record dynamic main link activation record new frame pointer Execution Begins func_1 called func_1 complete Figure 4 5 Run time Stack Growth A MOTOROLA DSP56KCC User s Manual 4 11 4 6 2 Global Static Data By default global and static data elements are located below the run time stack and each element is referenced by a unique label that is known at compile time see Chapter 6 Software Hardware Integration for additional information 4 7 Compiler Naming Conventions The compiler uses five different internal label
101. redirect the output listing to the standard output if it is not redirected via the L command line option described below Error mes sages will always appear on the standard output regardless of any option settings Note that some options B and L allow a hyphen as an optional argument which indicates that the corresponding output should be sent to the standard output stream Unpredictable results may occur if for exam ple the object file is explicitly routed to standard output while the listing file is allowed to default to the same output stream OPTIONS Any of the following command line options may be specified These can be in any order but must precede the list of source file names Option letters may be entered in either upper or lower case A ________ _ _______ ____ 222 C 2 DSP56KCC User s Manual MOTOROLA asm56000 asm56000 Option arguments may immediately follow the option letter or may be sepa rated from the option letter by blanks or tabs However an ambiguity arises if an option takes an optional argument Consider the following command line asm56000 b main io In this example it is not clear whether the file main is a source file or is meant to be an argument to the B option If the ambiguity is not resolved the assembler will assume that main is a source file and attempt to open it for reading This may not be what the programmer intended There are several ways to avoid this ambiguity If mai
102. register nx associated with the corresponding address registers rx Since the offset register is paired with the address register the allocat ed offset register has the same index as the address register see Example 5 4 in Section 5 2 4 e al or b1 upper word of the destination registers a or b see Example 5 5 in Section 5 2 4 h a0 or b0 lower word of the destination registers a or b see Example 5 6 in Section 5 2 4 k a2 or b2 extension register of the destination register a or b see Example 5 7 in Section 5 2 4 g Select the 24 bit portion of the 48 bit ALU register x or y that is not occu pied by data pointed to by the operand id e g if the operand id points to x0 then x1 is selected and similarly x1 gt x0 y0 gt y1 y1 gt y0 see Example 5 8 and Example 5 9 in Section 5 2 4 i strip the 0 or 1 from the allocated register name i e al gt a a0 a b1 b b0 gt b see Example 5 10 in Section 5 2 4 f insert the memory space identifier x or y for the memory location see Ex ample 5 11 in Section 5 2 4 p generate an immediate 16 bit constant without sign see Example 5 12 in Section 5 2 4 q generate an immediate 24 bit constant without sign see Section Example 5 12 in Section 5 2 4 2 operand id number specifies the operand location in the operand descriptor list see Example 5 3 in Section 5 2 4 The operand descriptor list is a concatenation of the o
103. run time counter string will only affect the run time address and the pragma directive load time counter string will only affect the load time a _ ___ _________ ____ ____ gt gt gt 2424222 5 22 DSP56KCC User s Manual MOTOROLA address As a simple example assuming that y memory model or default memory model is used see Chapter 3 to change the memory model to be used the following C segment pragma y_load x 100 int coeff 5 0x19999a 0x200000 0x266666 0x2ccccd 0x333333 pragma y_load produces the following assembly language code global Fcoeff org y x 100 Fcoeff dc 1677722 dc 2097152 dc 2516582 dc 2936013 dc 3355443 Notice that the second pragma directive will remove the affect of the first memory specification i e pragma y load x 100 and the rest of the code generated by the C compiler will be in the default memory area see Chapter 3 in order to change this default memory model The above example code will be loaded in the X memory location 100 and it should be copied to the Y memory space upon system start up When burning a PROM only one memory space is desired to be used as an example P memory space so that only one PROM is enough for both data and program In such case both the data and the program will be burned in the PROM and the data should be moved to the data memory space either X Y or L memory space depending on the program upon system start up Let s assum
104. s amp amp radix HEX or skip hex symbol Stt while c s amp amp endcondition if isdigit c amp amp digit c 0 radix valid DEC OCT or BIN digit num radix shift left one digit num digit add new digit else if isxdigit c amp amp radix HEX valid HEX digit num radix shift left one digit num toupper c A 10 add new digit else endcondition 1 invalid character if neg return 1 num return int num itoa x Custom integer to ASCII conversion function Returns a string representing the integer x in the base indicated by radix The radix x may be DECIMAL or HEX or OCTAL or BINARY The integers may be positive x or negative char itoa x radix string int x int radix char string char sl s2 List F 11 The list of I O function io atoi c Ee SEE MOTOROLA DSP56KCC User s Manual F 33 char temp int neg remainder i neg 0 if x lt 0 amp amp radix DEC if neg decimal set negative flag then treat as a positive number neg 1 x 1 fill string with characters from least to most significant i 0 while x 0 amp amp x 1 end loop when x is 0 for positive or 1 for negative numbers remainder x radix grab lowest digit remainder ABS remainder get abs value if rema
105. shows the fast interrupt vectors of the routines which utilize the register r7 The option mx memory on page F 4 allows the C program to access the DSP56000 family peripheral control and status registers which are located in the upper 64 locations of on chip X memory space As an example the function init_sci on page F 15 uses this feature to initialize the SCI Clock Register and SCI Control Register Notice that the variables sci ssi ports A_control and int_priority are set by referencing these X memory locations see global h and the main function on page F 11 and page F 14 respectively _ _ _ _ _____ gt z gt A M 1 F 2 DSP56KCC User s Manual MOTOROLA The C compiler option r mem ctl is the Memory Control File Option used to allocate the memory space for the assembly and C program segments The makefile on page F 4 contains the option r mem ctl which uses the Memory Control File mem ctl to assign or allocate the memory space for the sections of C program or assembly programs The file project map shows the exact memory map for all programs Specification of the Memory Control File requires knowledge of the DSP56000 family linker see the DSP56000 CLAS package The directive region collects sections as one module and each different module can be assigned to different starting address In the mem ctl control file the regions FAST PRG MAIN PRG MENU PRG and IO PRG are assigned to the memory locati
106. size used before nop wait until n6 is available to operate on r6 move r6 n6 deallocate the run time stack There are many ways to do this one simple optimization would be to advance the n6 load instruction in the program to eliminate the nop 5 4 4 Calling C Routines C routines are routines that are callable by a C program and may be written in either C or assembly language When writing assembly language subroutines it may be necessary to call library routines that have been provided or that have been written by the program mer e g a call to sin or printf In order to do this the programmer must follow 3 steps 1 Push arguments onto the run time stack in reverse order 2 Make the subroutine call 3 Restore the stack pointer The following example assumes that the four parameters to be passed to the C function foo are located in registers a1 b1 x0 and x1 respectively The first four lines of assem bly code push the arguments onto the run time stack in reverse order The jsr statement makes the subroutine call and the last two statements restore the stack pointer Example 5 37 Calling C Routines The C function foo is called from the following assembly code Function foo is declared as int foo int int int int move xl1 y r6 4 pushing arguments onto move x0 y r6 run time stack in reverse move b1 y r6 order move al y r6 jsr Ffoo subroutine call move 4 n6 the stack size restor
107. special effects digital signal processing The parameter set up is done through C programs and the special effects digital signal process system is programmed in assembly language In order to set up the parameters a set of predefined global variables is used so that they can be set through C programs and used as parameters in the assembly language program The global variables are named by following the naming convention of the C compiler to allow access by both assembly routines and C routines see section 4 7 of this manual Iu O X O MOTOROLA DSP56KCC User s Manual F 1 The section v_bles contains the global variables which are set up in the C program in addition to data control parameters which are only utilized in the assembly program to perform the special effects digital signal processing The C programs are provided in this appendix as an example of C programming techniques the special effects assembly language routines are not needed to meet the intent of this appendix The file var asm on page F 38 contains the section v_bles Notice that some of the variables are assigned to the same location This multiple label of an address assignment is sometimes very helpful in the mixed language environment For example the label F GAIN and VOLUME point to the same memory location The label F GAIN creates the C variable _GAIN for a C array The subsequent variab
108. specification with Ipath and searches the newly formed directory pathname for the file The directories will be searched in the order given on the command line R lt ctlfil gt This option indicates that a memory control file is to be read to determine the absolute placement of sections in DSP memory ctlfil can be any legal operating system file name including an optional pathname If a pathname is not given an attempt will be made to open the file in the current directory If no file name is supplied the linker will use the base name file name without extension of the first file name encountered in the link input file list appending an extension of ctl If the R option is not spec ified then the linker will not use a memory map file The R option should be specified only once U lt symbol gt Causes symbol to be entered into the unresolved external reference table This is useful when the initial or only link file is a library Since there are no external references when the linker is invoked the U option may be used to force inclusion of a library module that resolves the undefined reference The U option may be specified as often as desired V Indicates that the linker should be verbose during processing displaying a progress report as it links the input files The linker will show the beginning of each pass and when files are opened and closed The information is sent to the standard error output stream X lt opt
109. string abcdef709 hexstr stopped 709709709 decstr stopped 12341234 octstr stopped r s A 144 DSP56KCC User s Manual MOTOROLA strtoul strtoul NAME strtoul String to unsigned long integer SYNOPSIS include lt stdlib h gt unsigned long int strtoul const char nptr char endptr int base DESCRIPTION The strtoul function converts and returns the string pointed to by nptr to a long integer First strtoul decomposes nptr into three sections an initial possibly empty sequence of white space characters a subject in the form of an integer constant and a final string of one or more unrecognized characters including the terminating null character of the input string If the first unrecognized character is not NULL a pointer to that character is stored in to the object that endptr points to If the string is empty or the subject contains no floating point constant description zero is returned If base is between 2 and 36 the expected form of the long integer subject is a sequence of letters and digits with the radix specified by base The letters a or A through z or Z are ascribed values 10 to 35 only letters whose value is less than base are valid If base is 16 Ox or OX may optionally proceed the long integer subject If base is zero the long integer subject determines its own base Leading Ox or OX base 16 Leading 0 base 8 otherwise base
110. the function atexit are called in the order in which they where registered status is returned to the environment gdb56 run56 If more than one call is made to exit the result is undefined SEE ALSO abort Cause a program to terminate abnormally atexit Register functions to be called at normal termination EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf exit test n exit 0 return with O status printf Error exit made this unreachable n prints to standard output exit test r m O A 26 DSP56KCC User s Manual MOTOROLA exp exp NAME exp Exponential e SYNOPSIS include lt math h gt double exp double x DESCRIPTION The exp function computes and returns e If the value of x is too large a range error occurs with errno being set to ERANGE and exp returns HUGE_VAL If the value of x is too small a range error will also occur with errno being set to ERANGE and exp returns 0 0 SEE ALSO Idexp Multiplying a number by a power of two pow Raising a number to a power EXAMPLE include lt stdio h gt include lt math h gt void main printf exp 7 09 f n exp 7 09 prints to standard output exp 7 09 22 1199 907686 rn H O H I 001 MOTOROLA DSP56KCC User s Manual A 27 fabs fabs NAME
111. the operand list leaving us with the empty list of output operands The operand syntax is Joperand_constraint C_expression where 1 differentiates input and output operands All output operands must use this char acter first 2 operand constraint is a single character that describes the type of resource memory or register that an operand is to be loaded into or read from Each oper and constraint has an optional set of modifiers that may be applied in the instruction template 3 C_expression is any valid C expression defined by the ANSI C standard The C expression can be either l value or r value Any output operand should use the l value to specify the memory location to store the data The available operand constraints are A D R S i and m All of these con straints originate from the DSP56000 family architecture therefore a full understanding of these constraints requires that the programmer understand this architecture The con straints are A One of the Address Registers rx where x z 0 through 7 see Section 5 of the DSP56000 Family User s Manual will be allocated to the C expression see Example 5 4 The C expression will be promoted to this register Typi cally the C expression should be a pointer to be assigned to an address reg ister The OES modifier j can only be associated with operand constraint A A c e f MOT
112. the program is to be executed by hardware 5 Host I O stub functions send and _ receive are defined in crtO and are called by the standard l O library functions The provided certo file only has stub functions as both gdb56 and run56 watch these addresses and perform all I O di rectly 6 Floating point shift table _ fp shift is a pointer used by floating point library functions This pointer may be removed if the application does not use float ing point All of these variables constants functions and pointers are related to the run time envi ronments that are used by C library functions and must be properly set 6 4 Signal File The hardware level interrupt mechanism see section 8 3 of the DSP56000 DSP56001 User s Manual is more efficient than the signal function However in many cases inter rupts can be handled in the C environment and it is often more preferable to do so There are two functions signal and raise used to support programming interrupt service routines in C These functions are not associated with the crto file Although they are more complicated than the simple hardware interrupt vector table discussed in Section 6 3 3 see section 8 2 of the DSP56000 DSP56001 User s Manual they provide very handy tools for the C programmer A thorough knowledge of the signal function and the C en vironment is needed in order to modify the signal function This section describes how the signal function is cu
113. the program to terminate when the user selects the EXIT option from the menu oo E 0 menu t extern char getc extern void putc extern void putstr extern void setscreen char prompt void show main menu void inputs on off void set volume void set tone void set model void set delay void set gain void set lpf List F 7 The list of menu program gt _ __ __ _______ S E MOTOROLA DSP56KCC User s Manual F 17 void effects on off void mute void equalization int loop 1 char yorn char selection while loop show main menu selection prompt Enter Selection gt gt gt switch selection case A inputs on off break case B effects on off break case C set volume break case D set model break case E set lpf break case F mute break case G putc BEEP yorn prompt EXIT PROGRAM y n gt gt gt if yorn Y loop 0 else putc BEEP break default putc BEEP break show_main_menu Calls functions to display the main menu and also the current status of all settings void show main menu t void show menu void show status show menu main menu 6 1 show status prompt E Displays a prompt message on the bottom of the screen for the user and x returns the uppercase versi
114. them sequentially in memory starting with the location pointed to by s gets will not read past a newline character or past the end of the file The characters are stored in memory starting at the location pointed to by s gets returns s if it was successful NULL otherwise gets will update the file position indicator for any characters read lf gets encounters the end of file on its first read of standard input NULL is returned gets does not append a 0 to the array of characters read SEE ALSO fgets Read a string from a stream puts Read a string from a stream EXAMPLE include lt stdio h gt void main char line buffer BUFSIZ puts gets line buffer will echo a newline terminated line of input from standard input onto standard output Note that gets doesn t read past the newline puts supplies one by definition eee l MOTOROLA DSP56KCC User s Manual A 55 isalnum isalnum NAME isalnum Test for alphanumeric character SYNOPSIS include lt ctype h gt int isalnum int c DESCRIPTION The isalnum function returns a nonzero value for any alphabetic or numeric character zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if
115. this General Public License except that you may choose to grant warranty protec tion to some or all third parties at your option e If the modified program normally reads commands interactively when run you must cause it when started running for such interactive use in the simplest and most usual way to print or display an announcement including an appro priate copyright notice and a notice that there is no warranty or else saying that you provide a warranty and that users may redistribute the program under these conditions and telling the user how to view a copy of this General Public License e You may charge a fee for the physical act of transferring a copy and you may at your option offer warranty protection in exchange for a fee Mere aggregation of another independent work with the Program or its deriva tive on a volume of a storage or distribution medium does not bring the other work under the scope of these terms Sees MOTOROLA DSP56KCC User s Manual E 5 4 You may copy and distribute the Program or a portion or derivative of it under Paragraph 2 in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following accompany it with the complete corresponding machine readable source code which must be distributed under the terms of Paragraphs 1 and 2 above or accompany it with a written offer valid for at least three years to give any third part
116. unless you specify one In addition to the standard C escape sequences a backslash followed by a space stands for a space This is useful for outputting a string with spaces at the beginning or the end since leading and trailing spaces are trimmed from all arguments Thus to print and foo use the command echo V and foo A __ OO E 66 DSP56KCC User s Manual MOTOROLA A backslash at the end of text can be used as in C to continue the command onto subsequent lines For example echo This is some text n which is continued n onto several lines n produces the same output as echo This is some textin echo which is continuedin echo onto several lines n output expression Print the value of expression and nothing but that value no newlines no nn The value is not entered in the value history either See section Expressions for more information on expressions output fmt expression Print the value of expression in format fmt See section Output formats for more information printf string expressions Print the values of the expressions under the control of string The expressions are separated by commas and may be either numbers or pointers Their values are printed as specified by string exactly as if the program were to execute printf string expressions For example you can print two values in hex like this printf foo bar foo 0x x 0x x n foo bar foo only backslash esca
117. unsigned octal a Print as an address both absolute in hex and then relative to a symbol defined as an address below it Print as character constants T Print as floating point This works only with sizes w and g S Print a null terminated string of characters The specified unit size is ignored in stead the unit is however many bytes it takes to reach a null character including the null character Print a machine instruction in assembler syntax or nearly The specified unit size is ignored the number of bytes in an instruction varies depending on the type of machine the opcode and the addressing modes used If either the manner of printing or the size of unit fails to be specified the default is to use the same one that was used last If you don t want to use any letters after the slash you can omit the slash as well You can also omit the address to examine Then the address used is just after the last unit examined This is why string and instruction formats actually compute a unit size based on the data so that the next string or instruction examined will start in the right place The print command sometimes sets the default address for the x command when the value printed resides in memory the default is set to examine the same location info line also sets the default for x to the address of the start of the machine code for the specified line and info breakpoints sets it to the ad
118. user to select a wide variety of control options which affect the four compilation phases preprocessing compiling assembling and linking The control program parses the command line options and invokes the required sub programs on the specified files Note Object files are stored using the COFF format COFF stands for Common Object File Format Utilities such as cldinfo and cldlod may be used to gain visibility into object files 1 Given a list of C source files from the user see Figure 1 1 and options to apply to those files the control program runs each file through the C preprocessor and the C compiler The compiler creates individual assembly language source files for each C source file provided on the command line 2 The control program then sends the compiler output from these files to the assembler in addition to any assembly language files specified by the user on the g56k command line 3 The assembler output is routed to the linker for final processing The linker tries to resolve all unresolved link time symbols with the standard and any explicitly requested C libraries The COFF linker object file output may then be directed to any of several execution devices Notice that the assembler can also be used to create library files which can be included in a user defined library 4 The execution devices shown in Figure 1 1 are a run56 which allows the DSP56000 1 code in COFF format to be executed on the host comp
119. using GDB normally except for two things All terminal input and output goes through the Emacs buffer This applies both to GDB commands and their output and to the input and output done by the program you are debugging This is useful because it means that you can copy the text of previous com mands and input them again you can even use parts of the output in this way All the facilities of Emacs s Shell mode are available for this purpose e GDB displays source code through Emacs Each time GDB displays a stack frame Emacs automatically finds the source file for that frame and puts an ar row gt at the left margin of the current line Explicit GDB list or search commands still produce output as usual but you probably will have no reason to use them In the GDB I O buffer you can use these special Emacs commands M s Execute to another source line like the GDB step command M n Execute to next source line in this function skipping all function calls like the GDB next command M i Execute one instruction like the GDB stepi command C c C f Execute until exit from the selected stack frame like the GDB finish command SS J X 1 MOTOROLA DSP56KCC User s Manual E 71 M c Continue execution of the program like the GDB cont command M u Go up the number of frames indicated by the numeric argument see section Ar guments Numeric Arguments emacs The GNU Emacs Manua
120. 1 fflush fflush NAME fflush Flush all pending output associated with a stream SYNOPSIS Hinclude lt stdio h gt void fflush FILE DESCRIPTION The function fflush causes any pending output associated with the specified stream to be written to the output device SEE ALSO fprintf Used to write formatted output to a stream EXAMPLE include lt stdio h gt void main fprintf stdout see me second fprintf stderr see me firstin fflush stdout prints to combined standard error and standard output see me first see me second Note that stdout is by default line buffered while stderr is not The call to fflush causes the pending output on stdout to be flushed pe EO A 32 DSP56KCC User s Manual MOTOROLA fgetc fgetc NAME fgetc Read a character from the specified stream SYNOPSIS include lt stdio h gt int fgetc FILE stream DESCRIPTION The function fgetc will retrieve the next input character from the specified stream If the stream is associated with a file on the disk then the file position indicator is advanced On error fgetc returns EOF SEE ALSO fputc Write a character to a stream EXAMPLE include lt stdio h gt void main char value char fgetc stdin while EOF value fputc value stdout value char fgetc stdin will echo all characters from standard input to standard output until the input is
121. 2 2 zero de 1 987912472141 2 b11 2 dc 0 993992555209 2 b10 2 1000 Hz Notch Filter COEF 7 dc 0 99999130912 2 a12 2 pole dc 1 99991577597 2 a11 2 dc 0 99999565456 2 b12 2 zero dc 1 99991577597 2 b11 2 dc 0 99999565456 2 b10 2 2000 Hz Notch Filter COEF 8 dc 0 9737313764 2 a12 2 pole dc 1 890296349 2 al1 2 de 0 9999992341 2 b12 2 zero de 1 913315823 2 b11 2 dc 1 0 2 b10 2 1000 Hz Band Pass Filter COEF BAND dc 0 867418587882 2 a12 2 pole dc 1 848496918854 2 a11 2 de 0 066290706059 2 b12 2 zero de 0 0 2 b11 2 dc 0 066290706059 2 b10 2 endsec ON CHIP peripheral memory space section io vars org X FFEO EE MOTOROLA DSP56KCC User s Manual F 39 xdef PBC PCC PBDDR PCDDR PBD PCD HCR HSR HRX HTX xdef CRA CRB TSR RX TX SCR SSR SCCR STXA xdef SRX_LO STX_LO SRX_MID STX_MID SRX_HI STX_HI xdef BCR IPR SSISR PBC ds 1 Port B Control Register PCC ds 1 Port C Control Register PBDDR ds 1 Port B Data Direction Register PCDDR ds 1 Port C Data Direction Register PBD ds 1 Port B Data Register PCD ds 1 Port C Data Register ds 1 ds 1 HCR ds 1 Host Control Register HSR ds 1 Host Status Register ds 1 HRX HTX ds 1 Host Rcv Xmt Data Registers CRA ds 1 SSI Control Register A CRB ds 1 SSI Control Register B SSISR TSR ds 1 SSI Status Time Slot Register RX TX ds 1 SSI Rcv Xmt Data Registers SCR ds 1 SCI Interface Cont
122. 2 2 Comparison with IEEE STD 754 1985 Standard 4 3 4 4 3 Point r Why DOS oos Po Eae ect ee e ee ae Pr oats 4 8 4 5 Register co RET T LE I isos 4 8 4 6 Memory Sade ecran ud ext met tur oos br avo td OR ues a 4 9 4 6 1 Activation Record s so et Lt ra a E S e E o lr a Ca 4 10 4 6 2 Global Staule Data s ou curd utn rez pgs Dort te Panties one es 4 13 4 7 Compiler Naming Conventions llli 4 13 4 8 Subroutine Call Sequence 22 29 irrita baaa 4 13 4 8 1 Caller SCQUSnTE da uci pa repu Ra rq de oe Rae ds ob Pe ane 4 14 4 8 2 Calle SedgiuenBe z uu mu dure A ai aac 4 14 4 8 3 Return Sequence oocccooccoc lere 4 14 4 9 Software Support for Arithmetic Routines oooooo 4 14 4 10 RUNAS Sally is enh otc sida DA A E 4 15 4 10 1 Memory Allocation Checks 000 0c cece eee eee 4 15 4 10 2 Run time Stack Cnecks 22s tao Nea eee ee 4 16 4 11 Optimization Techniques Implemented 00 2000 eee 4 16 4 11 1 Register Promotion and Lifetime AnalysiS 4 16 4 11 2 Common Sub expression Elimination 00 0085 4 16 4 11 3 Constant Propagation Folding 0000e eee eee eee 4 16 4 11 4 Dead Code EImibaofie tou fst Sik aes as 4 17 4 11 5 Tal IMBEOITIO 5m test mere Se oe pr eed ema Gee Sues 4 17 4 11 6 Strength Reduction Ls e ae cl fe see ia Ba 4 18 4 11 7 Loop Invariant Code Motion cocino eR ERE 4 18 4 11 8 Hardware DO Loop Instruction ooooccoccco
123. 6KCC User s Manual A 59 isgraph isgraph NAME isgraph Test for printing character excluding space and tab SYNOPSIS include lt ctype h gt int isgraph int c DESCRIPTION The isgraph function returns a nonzero value for any printable character excluding space and tab t zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main check the beep character if isgraph printf space not graph character n if isgraph T printf f graph character n prints to standard output space not graph character f graph character A A 60 DSP56KCC User s Manual MOTOROLA islower islower NAME islower Test for lower case alphabetic characters SYNOPSIS include lt ctype h gt int islower int c DESCRIPTION The islower function returns a nonzero value for any lower case alphabetic character zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt c
124. 80000 these data should be set according to project asm _GAIN STAGE_3G 0x400000 see vars asm on page F 38 and globals h on page F 11 status FILTER 2 Sample Notch Filter 10Hz band stop filter coef_ptr _coef_4 putstr Project initialized for special audio effects putstr CRLF an F 16 DSP56KCC User s Manual MOTOROLA menu c This file contains all the functions required to display a menu for the user and to call the corresponding routines Also included are global arrays containing option labels 0X 009 0906 OOF include globals h see page F 11 char main_menu main menu options MAIN MENU OPTIONS Inputs on off Special Audio Effects on off Adjust volume Set model Select sample filter Mute y char model_menu audio effect model menu options Special Audio Effects Models Audio Effectl Audio Effect2 Audio Effect3 Audio Effect4 Audio Effect5 y char lpf_menu sample filter menu options Sample Filters a test filter 10Hz Notch Filter 200Hz Notch Filter 707Hz Notch Filter 1000Hz Notch Filter 2000Hz Notch Filter 1000Hz Band Pass Filter y menu Presents the user with the main menu prompts for a selection and calls the appropriate function based on the selection Upon return the main menu is redisplayed and a new prompts given MENU returns which causes
125. 9 data lod 1 0 421 det asm 1 0 Subroutine used in IIR DTMF 5923 dtmf asm 1 0 Main routine used in IIR DTMF 10685 dtmf mem 1 0 Memory for DTMF routine 48 dtmfmstr asm 1 0 Main routine for multichannel DTMF 7409 dtmfmstr mem 1 0 Memory for multichannel DTMF routine 41 dtmftwo asm 1 0 10256 ex56 bat 1 0 94 genxd lod 1 0 Data file 183 genyd lod 1 0 Data file 180 goertzel asm 1 0 Goertzel routine 4393 goertzel Ink 1 0 Link file for Goertzel routine 6954 goertzel Ist 1 0 List file for Goertzel routine 11600 load cmd 1 0 46 tstgoert mem 1 0 Memory for Goertzel routine 384 sub asm 1 0 Subroutine linked for use in IIR DTMF 2491 EES D 6 DSP56KCC User s Manual MOTOROLA DSP56KCC User s Manual Document ID Version Synopsis Size read me 1 0 Instructions 738 Fast Fourier Transforms sincos asm 1 2 Sine Cosine Table Generator for FFTs 1185 sincos hlp Help for sincos asm 887 sinewave asm 1 1 Full Cycle Sine wave Table Generator 1029 Generator Macro sinewave hlp for sinewave asm 1395 fftr2a asm 1 1 Radix 2 In Place DIT FFT smallest 3386 fftr2a hlp Help for fftr2a asm 2693 fftr2at asm 1 1 Test Program for FFTs fftr2a asm 999 fftr2at hlp Help for fftr2at asm 563 fftr2b asm 1 1 Radix 2 In Place DIT FFT faster 4290 fftr2b hlp Help for fftr2b asm 3680 fftr2c asm 1 2 Radix 2 In Place DIT FFT even faster 5991 fftr2c hlp Help for fftr2c asm 3231 fftr2d asm 1 0 Radix 2 In Place DIT FFT using 3727 DSP56001 sine cosine ROM tabl
126. A gt E 5 36 DSP56KCC User s Manual MOTOROLA Example 5 38 ReadX ReadY Routines This out of line assembly program called memread asm reads the contents of x or y memory and returns the data to the caller The ReadX subroutine returns the x memory space contents pointed to by the input argument and the ReadY subroutine returns the y memory contents section memread org p global ReadX prologue ReadX move _r0 y r6 i lua r6 r0 move r1 y r6 save register r1 move 3 n0 the first parameter move x r0 n0 r1 move x r1 a main program restore register amp epi logue move y r6 r1 Note r6 decrement can tst a y r6 ro be a parallel move in the rts main program global ReadY prologue ReadY move 10 y r6 lua r6 r0 move r1 y r6 save register r1 move 3 n0 the first parameter move y rO nO r1 move y r1 a main program restore register amp epi logue move y r6 r1 Note r6 decrement can tst a y r6 r0 be a parallel move in the rts main program endsec AAA AAA A A A AAA AAA AAA A A A A A A A AA O MOTOROLA DSP56KCC User s Manual 5 37 pe aO O 5 38 DSP56KCC User s Manual MOTOROLA Chapter 6 Software Hardware Integration 6 1 Overview This chapter explains how the run time environment may be changed and provides exam ples of some changes and their effects The run time environment provided with the com piler assumes as a default that the simulato
127. A AA A M MOTOROLA DSP56KCC User s Manual D 21 eee EO O D 22 DSP56KCC User s Manual MOTOROLA Appendix F C Programming Project F 1 Introduction This appendix is intended to assist C programmers in understanding how to utilize the C programming tools as well as assembly programming tools available with this compiler for a digital signal processing project This appendix contains a simple digital audio special effects application program to illustrate the use of the tools The special effects program is written in assembly language and consists of a simple filter example The example is incomplete and will not run The intent of the programs listed in this appendix is to give insight into how to organize the memory space for a C program project Additionally this project also illustrates the ability of the C compiler to intermix C and assembly language programs utilization of the make tool for a complex program project and DSP56000 family serial interfacing techniques A strong C programming background and familiarity with the DSP56000 family architecture is required to understand this appendix The information on the DSP56000 family architecture can be found in the DSP56000 DSP560001 Users Manual DSP56000 family CLAS package provides full documentation for the DSP56000 assembly programming environment F 2 Program Organization The program consists of two parts one is to set up all the system parameters and the other is to execute the
128. Assembly code int foo __asm move ffffff e0 D foo Assembly Code Generated move ffffff a1 Example 5 6 OES modifier h The h modifier can be used to generate the following assembly code because a0 is the lower part of register A In line Assembly code int foo __asm move ffffff h0 D foo Assembly Code Generated move ffffff a0 Example 5 7 OES modifier k The k modifier can be used to generate the following assembly code because a2 is the extension portion of register A In line Assembly code int foo _ _asm move ff k0 D foo Assembly Code Generated move ff a2 Example 5 8 OES modifier g Swap the most significant 24 bit portion and the least significant 24 bit portion of 48 bit registers x and y to allow the OR instruction to operate on an entire 48 bit register A EES 5 10 DSP56KCC User s Manual MOTOROLA ie The following assembly code could be generated note that the optimizer may vary the code actually generated move x1 a1 move x0 x1 move a1 x0 The variable foo can be allocated to either x0 x1 yO or y1 by using the operand constraint S The swap operation can be applied to the register allocated to the variable foo by using the following in line assembly code main int foo _ asm volatile move g0 a1 S foo _ asm volatile move 0 g0 S foo 0 foo _ asm volatile move a1 0 S foo
129. B commands Comments lines starting with may also be included An empty line in a command file does nothing it does not mean to repeat the last command as it would from the terminal When GDB starts it automatically executes its init files command files named gdbinit GDB reads the init file if any in your home directory and then the init file if any in the current working directory The init files are not executed if the nx option is given You can also request the execution of a command file with the source command source filename Execute the command file filename The lines in a command file are executed sequentially They are not printed as they are executed An error in any command terminates execution of the com mand file Commands that would ask for confirmation if used interactively proceed without asking when used in a command file Many GDB commands that normally print messages to say what they are doing omit the messages when used in a com mand file 3 35 Commands for Controlled Output During the execution of a command file or a user defined command the only output that appears is what is explicitly printed by the commands of the definition This section de scribes three commands useful for generating exactly the output you want echo text Print text Non printing characters can be included in text using C escape se quences such as n to print a newline No newline will be printed
130. C gt dir mysys stdio h C gt type file include lt stdio h gt include cnt h main int delay COUNT FILE fp fp fopen myfile w while delay C gt type inc cnt h define COUNT 25 C gt type mysys stdio h typedef struct FILE FILE data structure to develop char name 10 char X buffer 1024 FILE FILE fopen char char new function to develop C gt g56k I inc I I mysys E file c 14 file c 1 Amysysistdio h 1 typedef struct FILE char name 10 char X buffer 1024 AAA A _ _z gt gt 0 ET 3 12 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options FILE FILE fopen char char 1 filec 2 1 Aincienth 1 2 file c 2 main int delay 25 FILE fp fp fopen myfile w while delay Notice that the file inclusion cnt h is from the directory inc as shown in the line 1 inc cnt h 1 and the file inclusion lt stdio h gt is from the directory myinc as shown in the line 1 myinc stdio h 1 i FILE Process FILE as an input discarding the resulting output before processing the regular input file Because the output generated from FILE is discarded the only ef fect of i FILE is to make the macros defined in FILE available for use in the main in put Example 3 15 The program greeting c prints a simple message using the macro MESSA
131. CRIPTION If buf is NULL the specified stream will be unbuffered If buf is non NULL then the stream will be fully buffered with a buffer of size BUFSIZ Note that setbuf must be used only before any other operations are performed on the specified stream and that the stream argument must be associated with an opened file Calling setbuf is equivalent to calling setvbuf using _lOBUF for the mode argument and BUFSIZ for the size argument SEE ALSO setvbuf Read formatted input from a stream a O A 112 DSP56KCC User s Manual MOTOROLA setvbuf setvbuf NAME setvbuf Alter stream buffering SYNOPSIS include lt stdio h gt int setvbuf FILE stream char buf int mode size_t size DESCRIPTION The function setvbuf is used to alter the way a specified stream is buffered It must only be used before any other operation is performed on the specified stream The argument mode determines the buffering policy _IOFBF Use the full size of the buffer in the most efficient way _IOLBF Use a line buffering policy flush on newlines _IONBF Do not buffer the stream at all The argument size specified the buffer size for this stream The pointer buf if non NULL may be used for stream buffering If buf is NULL then setvbuf will allocate any needed buffer SEE ALSO setbuf A restricted form of setvbuf AAA A A AA A A M MOTOROLA DSP56KCC User s Manual A 113 signal signal NAME signal Set up signal handler
132. DATA dsm 3 State variables for IIR filter SOMEOTHERS ds 10 global F GAIN xdef VOLUME STG 1G STG 2G STG 3G F GAIN C array GAIN VOLUME ds 1 Volume coef STG 1G ds 1 The gain of the first stage STG 2G ds 1 The gain of the second stage STG 3G ds 1 The gain of the third stage i Internal Y Memory Space for filter coefficients i org Y 0010 xdef SSI_RCV_D0 SSI_XMT_DO xdef COEF_3 COEF_4 COEF_5 COEF_6 xdef COEF_7 COEF_8 COEF_BAND List F 14 The list of the file vars asm Ee F 38 DSP56KCC User s Manual MOTOROLA SSI_RCV_DO ds 1 SSI RCV data SSI_XMT_DO ds 1 SSI XMT data for the special audio effects Filter Coefficients should be determined with the program listed in the project program project asm and the following are just examples of the coefficients a test filter COEF 3 dc 0 9934475422 2 a12 2 pole dc 1 9934010506 2 al11 2 dc 1 0 2 b12 2 zero dc 2 0 2 b11 2 dc 1 0 2 b10 2 10 Hz Notch Filter COEF 4 dc 0 99957266896 2 a12 2 pole dc 1 99949960729 2 al1 2 de 0 99978633448 2 b12 2 zero de 1 99949960729 2 b11 2 dc 0 99978633448 2 b10 2 200 Hz Notch Filter COEF 5 dc 0 2872109013 2 a12 2 pole dc 1 121427892 2 al1 2 de 0 2368309214 2 b12 2 zero de 1 122362455 2 b11 2 dc 1 0 2 b10 2 707 Hz Notch Filter COEF 6 dc 0 987985110418 2 a12 2 pole dc 1 987912472141 2 al1 2 de 0 993992555209 2 b1
133. END OF TERMS AND CONDITIONS cig 1 3549 VR a Re RR S E 8 D 1 Input and Output ConNventi0NS ocoocccccc ee E 11 D 2 Specifying GDB s Files cord Seis hee Bane Ue ate eR EVE E 13 3 1 Specifying Files with Arguments 0 200 eee eee E 13 3 2 Specifying Files with Commands 0000 0e ee eens E 13 D 3 Compiling Your Program for Debugging 00 eeee eee E 17 D 4 Running Your Program Under GDB 00000 cece eee E 19 3 3 Your Program s Arguments 0 0 2c eee eee eee eee E 20 3 4 Your Program s Environment 2 lt ci 4002320008 A os E 20 3 5 Your Program s Working Directory 00 000 0c ee eeee E 21 3 6 Your Programs Inputand OU PUE iii de be ea E 21 3 7 Debugging an Already Running Process o oooooooooo E 22 3 8 Killing the Child Process xum e toe td RR E 22 D 5 Stopping and ohh vou ded dos de Su sn tee teet a Rid E 25 3 9 A epe Bourse a eO We wis pb INS E 25 3 10 A se mide Sa REP e EE EIE E 26 3 10 1 Setting BreakpolhIs oem ood dw e wt Re e Ea E 27 3 10 2 Deleting Breakpoints 00 0 eee eee eee E 28 3 10 3 Disabling Breakpoints 04 citas idee oiwtededad das E 29 3 10 4 Break Conditions ado daos Sew esis bee Ede Caw ate Rue E E 30 3 10 5 Commands Executed on Breaking 0ooo o oooo E 32 3 10 6 Cannot Insert Breakpoints Error oooocooooooo o E 33 3 11 CONAM ed Mte M E 34 3 12 SPP A T E 34 D 6 E
134. GE The file macros c contains the macro definition i e the actual message The only role of the file macros c is to provide the macro definitions and will not affect any other code or data segments QVE macros c greeting c C gt type macros c define MESSAGE Hello world C gt type greeting c include lt stdio h gt main printf Greeting s n MESSAGE Cr gt g56k i macros c greeting c Qr NPonPUur6 dcld A _ _ gt ___Q_ gt gt E gt E A A lt MOTOROLA DSP56KCC User s Manual 3 13 Preprocessor Phase Options Greeting Hello world M Cause the preprocessor to output the makefile rules to describe the dependencies of each source file For each source file the preprocessor outputs one make rule whose target is the object file name for that source file and whose dependencies are all the files needed to generate the object target file This rule may be a single line or may be continued with newline if it is long M implies E with makefile rules Example 3 16 The program big c which prints the larger of two integers uses the macro greater x y which is defined in the file greater h A command line output using the M option can be used for makefile utilities For more information on how to use this dependency check the make utility information in any UNIX utility manual CoN QE big c greater h C gt type big c include lt stdio h gt include greater h main
135. IPTION The tanh function computes and returns the hyperbolic tanget of x tanh x sinh x cosh x If the value of x is too large errno is set to ERANGE and the value HUGE_VAL is returned with the sign of x SEE ALSO cosh Compute the hyperbolic cosine sinh Compute the hyperbolic sine EXAMPLE include lt stdio h gt include lt math h gt void main printf tanh 45 f n tanh 45 prints to standard output tanh 45 1 000000 AAA AAA A A A A A M MOTOROLA DSP56KCC User s Manual A 149 tmpfile tmpfile NAME tmpfile Create a temporary binary file SYNOPSIS include lt stdio h gt FILE tmpfile void DESCRIPTION The function tmpfile will create a temporary file on the disk The file will be automatically removed when the program terminates The file will be opened with the mode wb If tmpfile fails it returns a NULL pointer SEE ALSO tmpnam Generate a valid temporary file name eee EO O A 150 DSP56KCC User s Manual MOTOROLA tmpnam tmpnam NAME tmpnam Create a temporary file name SYNOPSIS include lt stdio h gt char tmpnam char s DESCRIPTION The function tmpnam will create a string that could be used as a unique temporary file name This function may be called as many as TMP_MAX times Each time it will return a different string If the argument s is NULL then tmpnam will return an internal static buffer that may be clobbered by su
136. IS include lt stdlib h gt void calloc size t nmemb size t size DESCRIPTION The calloc function allocates space for an array of nmemb objects each of whose size is size The space is initialized to all bits equal zero If space can not be allocated calloc returns a NULL pointer SEE ALSO alloca Allocate storage in the stack frame free Free dynamically allocated storage malloc Dynamically allocate uninitialized storage realloc Alter size of previously dynamically allocated storage AAA A A AA A M MOTOROLA DSP56KCC User s Manual A 19 calloc calloc EXAMPLE include lt stdio h gt include lt stdlib h gt int iptr allocate space for 709 integers void main iptr int calloc 709 sizeof int if iptr NULL check first entry for zero initialization if iptr 0 printf error calloc failed to initialize n j else printf success calloc ok n else printf error calloc failed n prints to standard output success calloc ok i A 20 DSP56KCC User s Manual MOTOROLA ceil ceil NAME ceil Ceiling function SYNOPSIS include lt math h gt double ceil double x DESCRIPTION The ceil function returns the smallest integer greater than or equal to x When the header file math h is included the default case will be in line see section A 3 Forcing Library Routines Out of line SEE ALSO floor Floor funct
137. In leaf functions the return address is not needed and does not have to be saved Similarly the epilogue can be optimized in the same way as the prologue For any leaf function or non parameter C function the epilogue size can be reduced by eliminating move y r6 ssh for a leaf C function or move y r6 rO for a non parameter C function The test statement tst a in the epilogue can be eliminated if the function does not return any values The test statement may be required due to the C compiler s optimization fea tures since it provides condition flags for an if statement in a function call For example if the out of line assembly function foo is used in the statement if foo then the C compiler will not generate code to test the return value when a jcc statement is issued This is primarily because the C compiler uses the condition flags which were executed at the end of the epilogue of foo A variety of optimizations can be achieved by combining the move instructions and main program code to utilize parallel moves see Section 5 4 5 and Example 5 38 which point out possible optimizations in the comments These and other DSP56000 specific optimi zations can dramatically improve the quality of the application specific library routines A careful review of the DSP56000 DSP56001 User s Manual will be worthwhile for efficient library development _ _ lt __ _ _ _ _ _ _ __ _____zEz
138. In lining When explicitly requested via the command line option finline function the compiler will replace calls to subroutines with an in line copy of the subroutine if the subroutine meets these requirements 1 the subroutine must be a non volatile leaf function 2 the subroutine must be in the same module 3 the definition must precede use of the subroutine Function in lining eliminates the overhead associated with subroutine calls and provides additional opportunities for the optimizer and register allocator to further increase code quality Function in lining can also be performed explicitly by the programmer by utilizing the additional non ANSI function type specifier _ inline By default many run time libraries are in lined by the compiler Note The function in lining method can cause program memory requirements to grow significantly See Appendix A Programming Support for instructions on disabling library routine in lining 4 11 14 Instruction Scheduling Microcode Compaction The command line switch alo causes an assembly language optimizer alo56 to be run using the assembly code emitted by the compiler as input This optimizer attempts to compact multiple operations into a single instruction word while simultaneously avoiding the pipeline hazards exposed by the address generation unit Because this optimizer mixes together instructions from different C language statements debugging code compiled with alo may be more
139. KCC User s Manual 1 5 pe eO O 1 6 DSP56KCC User s Manual MOTOROLA Chapter 2 Installation Guide 2 1 Introduction This chapter describes installation on MS DOS and Sun computers Two installation pro cedures are detailed for the Sun The first procedure uses the default location for the files The second procedure allows the user to select the directory where the compiler s files will be located Only one procedure is needed for MS DOS machines The various parts of the compiler reside in a directory tree named dsp The default loca tion for the dsp directory tree is usr local on UNIX systems If this default location is ac ceptable then perform the standard installation if it is not acceptable then perform the alternate installation The alternate installation procedure allows the user to install the dsp directory tree anywhere 2 2 Installation On An MS DOS Machine 80386 or 80486 1 Insert the supplied floppy labeled Disk 1 into floppy drive A 2 Change to floppy drive A with the command A 3 Run the install program install exe This installation program will ask questions about the computer being used and about where the compiler s directory tree dsp is to reside 4 Add all new lines of code specified by install into the autoexec bat file The only difference between the standard and alternate installation procedure on the PC is whether or not the default output drive or default location is selected If the defaults
140. Library Routines Out of line SEE ALSO ceil Ceiling function EXAMPLE include lt stdio h gt include lt math h gt void main printf floor 7 09 f n floor 7 09 prints to standard output floor 7 09 7 000000 pe ee O A 36 DSP56KCC User s Manual MOTOROLA fmod fmod NAME fmod Floating point remainder SYNOPSIS include lt math h gt double fmod double x double y DESCRIPTION The fmod function computes and returns the floating point remainder r of x y The remainder r has the same sign as x and x i y r where r lt y If x and y can not be represented the result is undefined When the header file math h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt math h gt void main printf fmod 10 0 3 0 f n fmod 10 0 3 0 prints to standard output fmod 10 0 3 0 1 00000000 AAA A A A A A MoO MOTOROLA DSP56KCC User s Manual A 37 fopen fopen NAME fopen Open a named file on the host s disk SYNOPSIS include lt stdio h gt void fopen const char filename const char mode DESCRIPTION The fopen function attempts to open a named file for access via a stream If fopen is able to open the specified file then the new stream associated with that file is returned If fopen fails then it returns NULL The mode argument
141. Notice that the section main_c of the program main c is located at the memory address p 3000 and the section of data_c of the data data c is located at the memory address y 5000 See chapter 5 for detailed information on the in line assembly code _ asmY C gt type map ctl section main c p 3000 section data c y 5000 IL M E MOTOROLA DSP56KCC User s Manual 3 31 Link Phase Options C gt type data c int data 0x1 test value C gt type main c extern int data main int i for i 0 i lt 10 i asm rol 960 D data 0 data C gt g56k j mmap map r map ctl main c data c C gt type map map Y Memory default Start End Length Section 5000 5000 1 data_c P Memory default Start End Length Section 3000 3008 9 main_c 3 32 DSP56KCC User s Manual MOTOROLA Chapter 4 About g56k 4 1 Introduction The DSP56000 digital signal processors are designed to execute DSP oriented calculations as fast as possible As a by product they have an architecture that is somewhat unconventional for C programming Because of this architecture there are characteristics of the compiler and the code generated by the compiler that the programmer must understand in order to take full advantage of the DSP56KCC programming environment All programmers whether they are familiar with DSP or not should understand the DSP56000
142. OPTS vectors asm crt0 cln crt0 asm CC AOPTS crt0 asm eeaeee M MOTOROLA DSP56KCC User s Manual F 5 mem ctl Memory Control File The following Memory Control File is used to map a single external memory space DSP56001 board The P X and Y memory spaces above 0200 are mapped to a single memory space and so the program and data space share same physical memory space even though they are accessed differently in the program The internal memory spaces P 0000 P 01ff X 0000 X 01ff Y 0000 Y 01ff however are separate as they are on chip P X Y io vars ffe0 7fff j heap stack A DSIZE c globals 3000 io ctype c io atoi c a io_host_c io_scrn_c io sci c 1a00 menu c 1400 f main_c 1000 i P memor X memor Y memor 0200 Y Y PROJECT v bles v bles External Memory H 0040 0010 i VECTORS L_INTERNAL 0000 zs f On Chip Memory base p 1000 x 3000 y 3000 region FAST_PRG base p 40 1 0000 x 0010 y 0010 section L_internal section v_bles section project endr region MAIN_PRG base p 1000 x 3000 y 3000 section main_c endr List F 2 Memory Control File ea UMME F 6 DSP56KCC User s Manual MOTOROLA region MENU_PRG base p 1000 400 x 3000 300 y 3000 300 section menu_c endr region IO_PRG base p 1000 400 600 x 3000
143. OROLA DSP56KCC User s Manual 5 5 see Section 5 2 1 D One of the 56 bit accumulators a or b which are referred to as Destination Registers see Section 4 of the DSP56000 DSP56001 User s Manual will be allocated to the C expression see Example 5 5 through Example 5 7 The C expression will be promoted to this register Care must be exercised to make sure the size of the C expression is consistent with the accumulator length The OES modifiers e h and K can be associated with operand constraint D see Section 5 2 1 R One of the Input Registers x0 or yO which are also called Multiplier Regis ters see Section 4 of the DSP56000 DSP56001 User s Manual will be allo cated to the C expression see Example 5 10 The C expression will be promoted to this register The OES modifiers g and i can only be associated with operand constraint R see Section 5 2 1 S One of the Input Registers x0 x1 yO or y1 which are also called Source Registers see Section 4 of the DSP56000 DSP56001 User s Manual will be allocated to the C expression see Example 5 13 through Example 5 17 The C expression will be promoted to this register The OES modifiers g and i can only be associated with operand constraint S see Section 5 2 1 i Animmediate constant a constant is generated in the form of constant if no modifier is specified With p or q modifier the value is generated without the sign
144. Options for full information on options and arguments for invoking GDB 3 2 Specifying Files with Commands Usually you specify the files for GDB to work with by giving arguments when you invoke GDB But occasionally it is necessary to change to a different file during a GDB session Or you may run GDB and forget to specify the files you want to use In these situations the GDB commands to specify new files are useful exec file filename Specify that the program to be run is found in filename If you do not specify a di rectory and the file is not found in GDB s working directory GDB will use the envi ronment variable PATH as a list of directories to search just as the shell does when looking for a program to run symbol file filename Read symbol table information from file filename PATH is searched when neces ESS MOTOROLA DSP56KCC User s Manual E 13 sary Most of the time you will use both the exec file and symbol file commands on the same file symbol file with no argument clears out GDB s symbol table The symbol file command does not actually read the symbol table in full right away Instead it scans the symbol table quickly to find which source files and which symbols are present The details are read later one source file at a time when they are needed The purpose of this two stage reading strategy is to make GDB start up faster For the most part it is invisible except for occasional m
145. PEG A 148 Wwrite strings option 3 3 3 29 A a aS ink ated Sige ana dS A 149 TERM A nner eeene neces 2 2 X TERMEAP resta ci iets o 98d EE EE 5 22 toloWer s A 150 A 151 A 152 GIU esock veille ee bu da 5 22 toupper 1 6 eee eee eee A 153 XDEF assembler directive 5 32 XREF assembler directive 5 32 U U option usos PEDE ES ERIS 3 3 3 18 Y udiv_ba A O BEM BENGE E Me ie es Beno ce led aa uns 5 22 unsigned char 4 2 MEET ERR 5 22 unsigned int uus eae ed abus 4 2 4 8 unsigned long uude eens 4 2 4 8 unsigned short 4 2 4 8 q __________ za A A AA A AAA INDEX 6 G56KCC User s Manual MOTOROLA
146. Polled I O Adaptive Filter Flowchart 10361 p5 1 0 C code implementation of p4 24806 p6 1 1 Interrupt Driven Dual FIR Filter Flowchart 9535 p7 1 0 C code implementation of p6 28489 p8 1 0 Polled I O Dual FIR Filter Flowchart 9656 p9 1 0 C code implementation of p8 28525 Motorola DSP News The Motorola DSP News is a quarterly newsletter providing information on new products application briefs questions and answers DSP product information third party product news etc This newsletter is free and is available upon request by calling the marketing information phone number listed below Motorola Field Application Engineers Information and assistance for DSP applications is available through the local Motorola field office See your local telephone directory for telephone numbers or call 512 891 2030 Design Hotline 1 800 521 6274 This is the Motorola number for information pertaining to any Motorola product DSP Applications Helpline 512 891 3230 Design assistance for specific DSP applications is available by calling this number DSP Marketing Information 512 891 2030 Marketing information including brochures application notes manuals price quotes etc for Motorola DSP related products are available by calling this number u D O X M M 1 MOTOROLA DSP56KCC User s Manual D 13 DSP Third Party Support Inf
147. RY MODEL Figure 5 1 C Environment Memory Configuration As indicated in Figure 5 1 global and static data reside at the bottom of the available data memory and the top address of the global and static data area which is called DSIZE is set by the linker The constant TOP OF MEMORY is defined to indicate the top of the en tire available memory The two data segments heap and stack are located as shown Figure 5 1 The stack is located so that it can grow up and the heap is located so that it can grow down There are two locations used to indicate the initial values for the heap pointer and stack pointer SEES 6 4 DSP56KCC User s Manual MOTOROLA These locations are _ _y_size and break and are initialized in the crtO file as DSIZE and TOP_OF_MEMORY respectively In summary two variables __y_size and break and the constant TOP OF MEMORY are used to configure the data segment The program segment is configured using the org statement in the crto file The variable y size should be initialized with the initial stack pointer and the variable _ break should be initialized with the initial heap pointer Caution The stack and heap regions must not contain on chip peripheral memory or the static or global data regions Also no region may be reconfigured after the C main function is called Variables y size and _ break should not be altered by an arbitrary function since they are utilized by system level libraries such as malloc a
148. SP56000 family whereas the in line assembly code must follow the C programming environment rules Writing out of line assembly code requires a complete understanding of the C Cross Compiler and the DSP56000 family architecture For out of line assembly code to be callable from a C program the following five basic elements should be included in the as sembly source file in sequence C subroutine entry code prologue code Save all registers to be used Main program Restore all registers used 5 C subroutine exit code epilogue code Each of these steps can be programmed as a macro however using generic macros can unnecessarily increase the size of the resulting assembly code program The DSP s abil ity to move data in parallel with arithmetic operations provides opportunities to signifi E See _ _ _ __ gt A AAA 5 24 DSP56KCC User s Manual MOTOROLA cantly optimize the assembly code by combining steps within a macro and by combining the code of two or more macros In order to illustrate the steps listed above the out of line assembly code template is de scribed first and each element of the template is then explained in detail After reviewing the five elements some optimization techniques are discussed 5 4 1 General Template The following template is a generic form used to make the C function foo There are five distinct elements in the template which are numbered as above The actual code for the prologue
149. SP56KCC floating point format differs from the IEEE standard primarily in its handling of floating point exceptions Other differences are noted in Table 4 6 Conversion between the IEEE standard format and DSP56KCC format is straightforward As shown in Table 4 6 the DSP56KCC mantissa precision is one bit less than the IEEE single precision format This is the result of using two s complement arithmetic in the DSP56000 DSP56001 The DSP56KCC exponent width is three bits more than the IEEE double precision format This provides an extremely large approximately 100 000 dB dynamic range which eliminates exponent overflow for most applications If exponent overflow occurs the result is limited to the maximum representable floating point number of the correct sign If exponent underflow occurs the result is limited to the minimum representable floating point number which is zero Although the DSP56KCC format does I 227 M MOTOROLA DSP56KCC User s Manual 4 3 Floating Point Data pp Exponent addr Mantissa addr 1 a Floating point Data Arrangement in Memory Negative Mantissa Reserved Reserved Positive Mantissa al eee aa ami pa lt a al eo 2 Blo lm RO Go olo eoo oO o E lo alo eoo DO o o alo ooo oo o 3050 olo ajo O oo o sae no 5212 218 3 aic Se ooo oo o 2 LL LL LL LL Exs LS S2 LS m Goo Lo Loo Lo LL 2ro Lo
150. TABLE OF CONTENTS Paragraph Page Number Title Number Chapter 1 Introduction 1 1 DVT VIC pM 1 1 1 2 Error COS st o e TA E A pute sese Be astu 1 4 1 3 A A A A T Sate 1 4 1 4 Manual Organiza O uu 25s kr aso aseo sde ct ee ek E ACD 1 5 Chapter 2 Installation Guide 2 1 TOUS ET cess A AA A xx 2 1 2 2 Installation On An MS DOS Machine 80386 or 80486 2 1 2 3 Standard Installation On A SUN 0ooccccccccccco eee 2 3 2 4 Alternate Installation On A SUN 00 00 eee 2 4 2 5 O 2 5 Chapter 3 Control Program Options 3 1 pua pP Ah a A She e a it det Manta rd tot te 3 1 3 2 g56k Command Line Options cia os bs 3 3 3 2 1 Preprocessor Phase Opti0NS o ooooccoocccccnn ooo 3 5 3 2 2 Compile Phase Opllons xem ive Es ira tabla 3 19 3 2 3 Assemble Phase Options oooccccococcoo eee ee eee 3 29 3 2 4 Link Phase Options a s Eee PR SERE oa 3 30 Chapter 4 About g56k 4 1 WATROGUICUION TT TC A Bit tae LO a toy ts a al 4 1 4 2 TUS a btn a eke ein thee aden RR a hallo ASA 4 1 4 3 Predefined Preprocessor Macro Names 000eeeeeeeee 4 1 4 4 Data TVp6S and Sizes orase aoe ie Sekt ee teen meee ke es 4 1 4 4 1 Integral Data PyDBS a scavenge ten a 4 2 4 4 2 Floating point Types state tei REN WERE EVE EN Ghee E 4 2 PP PDD MOTOROLA DSP56KCC User s Manual i Table of Contents Continued Paragraph Page Number Title Number 4 4 2 1 Floating point Format Descripti0N o ooooo oooo 4 3 4 4
151. UCH DAMAGES SEES MOTOROLA DSP56KCC User s Manual E 7 END OF TERMS AND CONDITIONS Appendix How to Apply These Terms to Your New Programs If you develop a new program and you want it to be of the greatest possible use to hu manity the best way to achieve this is to make it free software which everyone can redis tribute and change under these terms To do so attach the following notices to the program It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty and each file should have at least the copyright line and a pointer to where the full notice is found one line to give the program s name and a brief idea of what it does Copyright C 19yy name of author This program is free software you can redistribute it and or modify it under the terms of the GNU General Public License as published by the Free Software Foundation either version 1 or at your option any later version This program is distributed in the hope that it will be useful but WITHOUT ANY WAR RANTY without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the GNU General Public License for more details You should have received a copy of the GNU General Public License along with this pro gram if not write to the Free Software Foundation Inc 675 Mass Ave Cambridge MA 02139 USA Also add information on how to contact you by electronic and paper mail
152. V Preprocessor Phase Options Compile Phase Options alo fno opt fno peephole fno strength reduce fno defer pop fforce addr finline functions C fcaller saves DMACRO NM fkeep inline functions DMACRO DEFN E fwritable strings fcond mismatch IDIR i fvolatile ES ffixed REG i FILE 4 dii 2 i m56002 nostdinc mno dsp SPORE mno do loop generation mno linv plus biv promotion Di mp mem switchtable UMACRO mstack check Wcomment mx memory Wtrigraphs HIVER y memory ml memory Assemble Phase Options pedantic asm string Q C S W Link Phase Options W Wimplicit ert fle Wreturn type j string Wunused ILIBRARY Wswitch r MAPFILE Wall Wshadow Wid clash LEN Wpointer arith Wcast qual Wwrite strings often preferable to trade memory space for speed but in cases where the extra memory space is not available this particular optimization could not be used The various compiler phases will report errors however the user has the option to turn off all warnings using w and can enable additional warnings individually or as a group using Wall The warnings which are not enabled by Wall are those listed below Wall in Table 3 1 3 2 g56k Command Line Options The default options are 1 use strict ANSI syntax L LLC e OL LLzAZzZ X 1ZXZAAALALLAAAAADOnhi MIDI ALL id MOTOROLA DSP56KCC User s Manual 3 3 2 perform all machine dependent and indep
153. Write a string to standard output SYNOPSIS include lt stdio h gt int puts const char s DESCRIPTION The puts function prints a string to standard output appending a newline character The puts function returns a zero if operation is successful and a non zero value on failure SEE ALSO getchar Get a character from standard input gets Get a line of text from standard input putchar Write a char to standard output EXAMPLE include lt stdio h gt char str bald feet void main puts str prints to standard output bald feet AAA AAA A A A A A Mo MOTOROLA DSP56KCC User s Manual A 99 qsort qsort NAME qsort Quick sort SYNOPSIS include lt stdlib h gt void qsort void base size t nmemb size_t size int compar const void const void DESCRIPTION The qsort function sorts an array of nmemb objects of size size pointed to by base The array is sorted in ascending order according to a comparison function pointed to by compar which is called with two pointers to the array members The compar function must return an integer less than equal to or greater than zero if the first argument is considered to be respectively less than equal to or greater than the second argument A AAA AAA AAA A A O A 100 DSP56KCC User s Manual MOTOROLA qsort qsort EXAMPLE include lt stdio h gt include lt stdlib h gt include lt string h gt char stuff fred flintston
154. __________ ___ ___ MOTOROLA DSP56KCC User s Manual 5 13 Example 5 19 Multiple Instruction Multiple Line The two lines of in line assembly code in this example have the same effect as the one line in Example 5 18 Notice that using two lines increases the in line assembly code readability The line continuation character Y used at the end of the in line assembly codes first line makes this possible __asm move 709 A n neg A Example 5 20 Multiple use of _ asm This example and Example 5 21 are done in line with the compiler performing all register allocation and all operands are referenced via C expressions This in line program is a single memory space version of the Dr BuB IIR filter program iir1 asm The method used to write this in line assembly program is to use an _ asm statement for each assembly language instruction int iir1 int data int sptr int cptr int state1 state2 coef __asm move y 1 0 R state1 A sptr __asm move y 1 0 R coef A cptr __asm mac 2 3 0 ty 4 1 D data R coef R state1 1 coef A cptr 0 data __asm move y 1 0 S state2 A sptr asm macr 1 2 0 t 3 y 4 D data S state2 R coef R state1 A sptr asm move 0 y 1 D data A sptr
155. a rO movep a y output end C gt g56k S data c CA gt g56k c fir asm C gt g56k c data asm C gt g56k fir cln data cln 5 20 DSP56KCC User s Manual MOTOROLA 5 2 6 Specifying Registers for Variables DSP56KCC allows the programmer to identify a specific register for local and global vari ables but due to the limited number of registers available this may not have a positive ef fect on run time performance With this in mind this feature should be used sparingly Both global and local variables are candidates for promotion to specific registers and syntactically they look the same register int ptr __asm r5 By specifying a specific register for a local or global variable the programmer is reserv ing the register for the variable s entire scope global for the entire program local for the function in which they are declared This means that the compiler will not use the regis ter for any other purpose and the register will not be saved and restored by the C func tion call 5 2 7 Optimizer Effects on Code All in line assembly code is visible to the optimizer and as such it is possible that the op timizer will convert it into a new form or eliminate it entirely if it is determined to be un reachable or dead In order to guarantee that code is not removed by the optimizer the ANSI keyword volatile must be used __asm volatile 5 3 pragma Directive The purpose of this section is to explain t
156. a single source line all the kinds of linespec linenum Specifies line linenum of the current source file When a list command has two linespecs this refers to the same source file as the first linespec roffset Specifies the line offset lines after the last line printed When used as the second linespec in a list command that has two this specifies the line offset lines down from the first linespec offset Specifies the line offset lines before the last line printed filename linenum Specifies line linenum in the source file filename ee SS A AAA E 44 DSP56KCC User s Manual MOTOROLA function Specifies the line of the open brace that begins the body of the function function filename function Specifies the line of the open brace that begins the body of the function function in the file filename The file name is needed with a function name only for disambig uation of identically named functions in different source files address Specifies the line containing the program address address address may be any expression One other command is used to map source lines to program addresses info line linenum Print the starting and ending addresses of the compiled code for source line line num The default examine address for the x command is changed to the starting ad dress of the line so that x i is sufficient to begin examining the machine code see section Memory Also this address is saved as the v
157. a00 y 3000 a00 section io_sci_c section io_scrn_c section io_host_c section io_atoi_c section io ctype c endr section io vars x fe0 AAA A A A A A A A AAA MOTOROLA DSP56KCC User s Manual F 7 Motorola DSP Linker Version 4 1 9 92 08 26 17 03 24 project map Page 1 Section Link Map by Address X Memory default Start End Length Section 0010 001B 12 v_bles Abs 001C 001E 3 v_bles Abs Mod 001F 002C 14 v bles Abs 3000 30DE 223 main c 30DF 30E2 4 crto 3300 351A 539 menu_c 3A00 3A02 3 io_scrn_c FFEO FFFF 32 io_vars Abs X Memory low Start End Length Section No sections X Memory high Start End Length Section No sections Y Memory default Start End Length Section 0010 0034 37 v_bles Abs Y Memory low Start End Length Section No sections Y Memory high Start End Length Section No sections L Memory default Start End Length Section 0000 000A 11 L_internal Abs L Memory low Start End Length Section Motorola DSP Linker Version 4 1 9 92 08 26 17 03 24 project map Page 2 No sections List F 3 Memory Map File _ _ _ _____ gt _ _ E F 8 DSP56KCC User s Manual MOTOROLA L Memory high Start End Length Section No sections P Memory default Start End Length Section 0000 003F 64 vectors Abs 0040 0070 49 project 1000 10F7 248 main_c 10F8 1101 10 crto 1400 1994 1429 menu_c 1400 1B72 371 io_sci_c 1B73 1C3E 204 io_scrn_c
158. ached specify a count of zero cont count Continue execution of the program setting the ignore count of the breakpoint that the program stopped at to count minus one Thus the program will not stop at this breakpoint until the count th time it is reached This command is allowed only when the program stopped due to a breakpoint At other times the argument to cont is ignored Ss EEEEEEEEEEEeeeeeeeeeseSeSeSe MOTOROLA DSP56KCC User s Manual E 31 If a breakpoint has a positive ignore count and a condition the condition is not checked Once the ignore count reaches zero the condition will start to be checked Note that you could achieve the effect of the ignore count with a condition such as foo lt 0 using a debugger convenience variable that is decremented each time See section Convenience Vars 3 10 5 Commands Executed on Breaking You can give any breakpoint a series of commands to execute when the program stops due to that breakpoint For example you might want to print the values of certain expres sions or enable other breakpoints commands bnum Specify commands for breakpoint number bnum The commands themselves ap pear on the following lines Type a line containing just end to terminate the com mands To remove all commands from a breakpoint use the command commands and follow it immediately by end that is give no commands With no arguments commands refers to the
159. aining Courses 602 994 6900 cc eee D 14 Reference Books and Manuals 00 2 cece eee eee eee D 14 General DSP cei da dubetohe vbi Pau RD bb EDh e oes ties Peas D 15 Digital Audio and Filters cuneta edat IB e hos ro DU Ebo ap D 16 C Programming Language sessi AV e RA EPA D 17 AS OTN OO PPP A A PROP AE D 17 Graphis ads 208 tests gh enc voc D 18 limage Processing E T PE D 19 Motorola BSPMArlals x 5 92 1 E TEES 441 phu IP ROET EP S RU D 19 N tmerical Methods x2 29 mito End E a eri ater DI CE ERG egets D 19 Pattern Recognition E En D 20 jolie M RR Sek canine re ee Sead a o Ue D 20 Telecommunicaltions isses be eae A wee e mm ERE REA ERE D 21 eau UME MOTOROLA DSP56KCC User s Manual vii Chapter 1 Introduction 1 1 Overview The DSP56KCC GNU based C cross compiler is the latest high level language development system for the Motorola DSP56000 family of digital signal processors DSP It includes anintegrated control program g56k an ANSI compliant C language preprocessor mcpp e an ANSI optimizing C compiler g56 cc1 e aDSP56000 common object file format COFF assembler asm56000 aCOFF linker dsplnk aCOFF librarian dsplib asource level debugger for C gdb56 asimulator based execution program run56 various object file manipulation tools srec cldlod cofdmp This integrated software system runs on a variety of machines and operating systems inclu
160. alue from a prior call to fgetpos Note that a successful call to fsetpos will undo any effect of an immediately preceding ungetc on the same stream If it is successful fsetpos returns zero SEE ALSO fgetpos Obtain the file position indicator value associated with a stream EXAMPLES include lt stdio h gt void main FILE preexisting fopen already here r fpos_t pos void fgetpos preexisting amp pos void fseek preexisting OL SEEK_END void fsetpos preexisting amp pos will open a hypothetical pre existing file on the disk record the initial position in pos seek to the end of the file and finally restore the initial value of the file position indicator pe ae E A 50 DSP56KCC User s Manual MOTOROLA ftell ftell NAME ftell Get the file position indicator associated with a stream SYNOPSIS include lt stdio h gt long int ftell FILE stream DESCRIPTION The function ftell will return the value of the file position indicator for the specified stream The return value is usable only by the function fseek ftell returns 1L SEE ALSO fopen Open a file and associate it with a stream fread Read data from a stream putchar Send character data to standard output fseek Change the file position indicator associated with a stream EXAMPLE include lt stdio h gt main FILE stream fopen file abc r long int beg
161. alue of the convenience variable see section Convenience Vars 3 18 Searching Source Files There are two commands for searching through the current source file for a regu lar expression The command forward search regexp checks each line starting with the one fol lowing the last line listed for a match for regexp It lists the line that is found You can abbreviate the command name as fo The command reverse search regexp checks each line starting with the one be fore the last line listed and going backward for a match for regexp It lists the line that is found You can abbreviate this command with as little as rev 3 19 Specifying Source Directories Executable programs do not record the directories of the source files from which they were compiled just the names GDB remembers a list of directories to search for source files this is called the source path Each time GDB wants a source file it tries all the di rectories in the list in the order they are present in the list until it finds a file with the de sired name Note that the executable search path is not used for this purpose Neither is the current working directory unless it happens to be in the source path A O AAA MOTOROLA DSP56KCC User s Manual E 45 When you start GDB its source path contains just the current working directory To add other directories use the directory command directory dirnames Add directory dirna
162. ames suffixed with c ANSI C source files i preprocessed C source files asm DSP56000 DSP56001 assembly code and cln COFF link files The control program processes each file according to this suffix The g56k output is controlled by the specific set of command line options provided For instance if no command line arguments are provided the compiler will generate a COFF load file a cld If the c option is invoked the compiler will generate a COFF link file suffixed with cln A complete description of the command line options with examples is provided in Section 3 2 Note It is strongly recommended that g56k always be used to invoke the C com piler utilities rather than individually executing them _ __ ______ _ __ gt gt gt gt gt gt A X A A MOTOROLA DSP56KCC User s Manual 3 1 A standard directory search list is consulted by g56k for 1 Each of the four executables a mcpp the C compiler preprocessor b g56 cc1 the C compiler optimizer c alo56 the assembly language optimizer d asm56000 the DSP56000 DSP56001 assembler e dspink the DSP56000 DSP56001 linker 2 Start up file crt056 cln Where is a single character x y or I i e x data memory y data memory or long data memory to denote the memory model 3 ANSI C library lib56c clb Where is a single character x y or I to denote the memory model This stan
163. ameters is done through the activa tion record which has been pushed onto the stack The activation record frame pointer is pointed to by rO and the first parameter is placed 3 locations below the frame pointer see Section 4 6 1 The parameters are arranged in reversed order For example the fol lowing statement should be used to move the first single word parameter to register r3 move 3 n0 the first parameter location move y r0 n0 r3 load it to r3 gt _ _ _ _ _ ___ _ __ _ __________ _____ 2 5 26 DSP56KCC User s Manual MOTOROLA Assuming the first three parameters are one word long the following statements move the second and third parameters to registers r4 and r5 respectively move 4 n0 move y r0 n0 r4 move 5 n0 move y r0 n0 r5 5 4 1 4 Restore all registers The stack pointer r2 is needed to restore the registers The following code will restore one register At this point in the function s execution the stack pointer points to the loca tion above the last saved register hence the pre decrement move y r2 x0 restore The restoring procedure can be simplified if more than one register is to be restored Re storing registers x0 x1 yO and y1 can be done by the statements below move r2 move y r2 x0 move y r2 x1 move y r2 yO move y r2 y1 After the function has finished a return value can be passed to the caller Any 32 bit or 16 bit value must be returned through regist
164. and closes that stream It then reopens the file and displays the first line of that file on standard output verify this eeaeee Mo MOTOROLA DSP56KCC User s Manual A 39 fprintf fprintf NAME fprintf Write formatted output to a stream SYNOPSIS include lt stdio h gt int fprintf FILE stream const char format DESCRIPTION The function fprintf functions exactly like the function printf except that the output is directed to the specified stream rather than being automatically directed to standard output Please use the description of argument values in the description of the printf function SEE ALSO printf Used to write formatted output to a standard output EXAMPLE include lt stdio h gt void main fprintf stdout hello world Will cause the following output to be printed to standard output hello world pe ee O A 40 DSP56KCC User s Manual MOTOROLA fputc fputc NAME fputc Write a single character to a stream SYNOPSIS include lt stdio h gt int fputc int c FILE stream DESCRIPTION The function fputc writes the character c to the specified stream EXAMPLE include lt stdio h gt void main fputc int S stdout fputc int h stdout fputc int a stdout fputc int d stdout fputc int r stdout fputc int a stdout fputc int c stdout fputc int k std
165. and epilogue is shown but the Save all registers to be used Main Program and Restore all registers used are listed as comments because their actual code de pends on the main program global Ffoo prologue Ffoo sets up entry point C function address move r0 y r6 updates frame pointer r0 and saves lua r6 r0 return address move ssh y r6 Save all registers to be used Main Program Restore all registers used move y r6 ssh_ epilogue restores return address updates move y r6 rO restores return address updates tst a frame pointer r0 and updates the SR with the contents of register A rts 5 4 1 1 Prologue The first two lines of the prologue make the assembly program visible to the C program so that the subroutine or function is callable from the C program In this case any one of the following C statements can be used to access out of line assembly code foo x foo x foo arg1 arg2 arg3 The first function call assumes that the C function does not use any arguments and does not return any values The second only returns a value which is the same data type as EES MOTOROLA DSP56KCC User s Manual 5 25 the variable x The last call assumes that the C function uses the three arguments arg1 arg2 and arg3 and then returns the value x The rest of the prologue saves the old frame pointer updates the current frame pointer and saves the return address The r
166. and or stepping command to execute at address 0x485 rather than at the address where the program stopped See section Stepping The most common occasion to use the jump command is when you have stepped across a function call with next and found that the return value is incorrect If all the rele vant data appeared correct before the function call the error is probably in the function that just returned In general your next step would now be to rerun the program and execute up to this func u E 0nm 1 E 62 DSP56KCC User s Manual MOTOROLA tion call and then step into it to see where it goes astray But this may be time consum ing lf the function did not have significant side effects you could get the same information by resuming execution just before the function call and stepping through it To do this first put a breakpoint on that function then use the jump command to continue on the line with the function call 3 31 Giving the Program a Signal signal signalnum Resume execution where the program stopped but give it immediately the signal number signalnum Alternatively if signalnum is zero continue execution without giving a signal This is useful when the program stopped on account of a signal and would ordinary see the signal when resumed with the cont command signal 0 causes it to re sume without a signal 3 32 Returning from a Function You can
167. and thence to the program run with no arguments uses the same arguments used by the previous run The command set args can be used to specify the arguments to be used the next time the program is run If set args has no arguments it means to use no arguments the next time the program is run If you have run your program with arguments and want to run it again with no arguments this is the only way to do so 3 4 Your Program s Environment The environment consists of a set of environment variables and their values Environ ment variables conventionally record such things as your user name your home directo ry your terminal type and your search path for programs to run Usually you set up environment variables with the shell and they are inherited by all the other programs you run When debugging it can be useful to try running the program with different environ ments without having to start the debugger over again info environment varname Print the value of environment variable varname to be given to your program when itis started This command can be abbreviated i env varname info environment Print the names and values of all environment variables to be given to your pro gram when it is started This command can be abbreviated i env set environment varname value set environment varname value Sets environment variable varname to value for your program only not for GDB it self val
168. ard output random characters fghijkl eee EO O A 136 DSP56KCC User s Manual MOTOROLA strrchr strrchr NAME strrchr Find the last occurrence of a character from one string in another SYNOPSIS include lt string h gt char strpbrk char s1 const char s2 DESCRIPTION The strrchr function locates the last occurrence of c converted to a char in the string pointed to by s The terminating null character is considered part of the string strrchr returns a pointer to the located character or a null pointer if the character is not found in the string SEE ALSO memchr Find a character in a memory area strchr Find the first occurrence of a character in a string strcspn Compute the length of the prefix of a string not containing any characters contained in another string strpbrk Find the first occurrence of a character from one string in another string strspn Compute the length of the prefix of a string contained in another string EXAMPLE include lt stdio h gt include lt string h gt void main char string fred flintstone driving on bald feet char found found strrchr string f puts found prints to standard output feet _ ______________ M EA MOTOROLA DSP56KCC User s Manual A 137 Strstr strstr NAME strstr Find the first occurrence of one string in another SYNOPSIS include lt str
169. are built upon two simple commu nication functions __ send and receive __ send sends a message to the I O driver code residing on the host receive retrieves a message from that same driver Implementing these two functions is all that need be done on the DSP in order to support standard I O on custom hardware It is assumed that some sort of hardware communication channel exists between the host and the DSP send and __receive implement a simple message passing mecha nism on top of such a channel send accepts two arguments the address of the buff er to send and the number of words to draw from that buffer _ receive accepts the address of a buffer in which to place the received message as its single argument All of the interactions between the host and DSP are driven by the library code running on the DSP because the DSP is in control it knows the size of return messages from the host rendering a count argument to the function __ receive superfluous __ send and IEEE 6 12 DSP56KCC User s Manual MOTOROLA receive are as simple as they seem the complexity of the standard I O package is embedded in the host side driver and the lib56c xyl clb library routines 6 6 2 The Host Side l O Driver The application running on the host must have the provided I O driver embedded in it The driver is written in C and uses typically available library routines such as open close read and write to per
170. assembly Structured programming Sh Oe du NS B 3 1 Assembly Control The directives used for assembly control are COMMENT Comment line s DEFINE Define substitution strings END End of source program FAIL Programmer generated error message INCLUDE Include secondary file MSG Program generated message ORG Initialize memory space and location counters RADIX Change input radix for constants RDIRECT Remove directive mnemonic from assembler table UNDEF Undefine DEFINE symbol WARN Programmer generated warning message B 3 2 Symbol Definition The directives used to control symbol definition are ENDSEC End section EQU Equate symbol to a value SET Set symbol to a value SECTION Start section XDEF External section symbol definition XREF External section symbol reference B 4 DSP56KCC User s Manual MOTOROLA B 3 3 Data Definition Storage Allocation The directives used to control constant data definition and storage allocation are BSC Block storage of a constant DC Define constant DS Define storage DSM Define modulo storage DSR Define reverse carry storage B 3 4 Listing Control and Options The directives used to control the output listing are LIST List the assembly LSTCOL Set listing field widths NOLIST Stop assembly listing OPT Assembler options PAGE Top of page define page size PRCTL Send c
171. attice filters matrix algebra routines companding routines floating point routines a software debug monitor and others In addition the latest product information and documentation including information on new products and improvements on existing products is posted Questions concerning Motorola DSP products posted on Dr BuB are answered promptly Access to Dr BuB is through the following phone numbers 212A 300 1200 Baud 0 00 0 esses b12 891 DSP1 V 02 3900 Balid Qu eacus abies eni eae enee 512 891 DSP2 V 22bis 2400 BO deceat rado 512 891 DSP3 Format 7 data bits even parity 1 stop bit User ID guest The following is a partial list of the software available on Dr BuB AAA A A A A A UM 01 MOTOROLA DSP56KCC User s Manual D 5 Document ID Version Synopsis Size Audio rvb1 asm 1 0 Easy to read reverberation routine 17056 rvb2 asm 1 0 Same as RVB1 ASM but optimized 15442 stereo asm 1 0 Code for C QUAM AM stereo decoder 4830 stereo hlp 1 0 Help file for STEREO ASM 620 dge asm 1 0 Digital Graphic Equalizer code from 14880 Codec Routines loglin asm 1 0 Companded CODEC to linear PCM data 4572 conversion loglin hlp Help for loglin asm 1479 loglint asm 1 0 Test program for loglin asm 2184 loglint hlp Help for loglint asm 1993 linlog asm 1 1 Linear PCM to companded CODEC data 4847 conversion linlog hlp Help for linlog asm 1714 DTMF Routines clear cmd 1 0 Explained in read me file 11
172. be mixed i e only one of mx memory my memory or ml memory may be se lected A w 7 r X A 1 MOTOROLA DSP56KCC User s Manual 3 23 Compile Phase Options Example 3 24 An application is programmed to utilize only the DSP56001 X data memory space and therefore must be compiled using the mx memory option C gt ls X C Qr Vp SC oc void function int a int b int X main int arg1 arg2 function arg1 arg2 void function int a int b X a b C gt g56k S mx memory x c C gt dir x asm x C my memory Direct the compiler to locate data in the Y data memory space This is the default memory mode Memory modes cannot be mixed i e only one of mx memory my memory or ml memory may be selected ml memory Direct the compiler to locate data in the L data memory space This has 2 side ef fects 1 A performance increase for 48 bit data code long float and double 2 This requires that the X and Y memory spaces be evenly populated Memory modes cannot be mixed i e only one of mx memory my memory or ml memory may be selected pedantic Issue all the warnings demanded by strict ANSI standard C reject all programs that use forbidden extensions Without this option certain GNU extensions and traditional C features are support ed With this option they are rejected Valid ANSI standard C programs will co
173. biguity arises if an option takes an optional argument Consider the following command line dspink b main io In this example it is not clear whether the file main is a link file or is meant a _ _ _ 2 _ _ _ _ __ __ AAA ee C 12 DSP56KCC User s Manual MOTOROLA dsplnk dsplnk to be an argument to the B option If the ambiguity is not resolved the link er will assume that main is a link file and attempt to open it for reading This may not be what the programmer intended There are several ways to avoid this ambiguity If main is supposed to be an argument to the B option it can be placed immediately after the option let ter without intervening white space dspink bmain io If there are other options on the command line besides those that take op tional arguments the other options can be placed between the ambiguous option and the list of link file names dspink b main v io Alternatively two successive hyphens may be used to indicate the end of the option list dspink b main io In this case the linker interprets main as a link file name and uses the de fault naming conventions for the B option B lt objfil gt This option specifies a name for the object file generated by the linker obj fil can be any legal operating system file name including an optional path name A hyphen may also be used as an argument to indicate that the object file should be sen
174. ble with the DSP56KCC Rev g1 11 compiler They are asm56000 cldinfo cldlod cofdmp dsplib dsplnk gdb56 run56 9 srec These programs are described in detail in the following pages ONOaAR WD AAA AAA A AAA A A M MOTOROLA DSP56KCC User s Manual C 1 asm56000 asm56000 NAME asm56000 Motorola DSP56000 DSP56001 COFF Assembler SYNOPSIS asm56000 A B lt objfil gt D symbol lt string gt F lt argfil gt G 4 lt ipath gt L lt Istfil gt M lt mpath gt O lt opt gt opt R lt rev gt lt rev gt V LZ files DESCRIPTION asm56000 is a program that processes source program statements written in DSP56000 assembly language translating these source statements into object programs compatible with other DSP56000 software and hardware products files is a list of operating system compatible file names including optional pathnames If no extension is supplied for a given file the assembler will first attempt to open the file using the file name as supplied If that is not successful the assembler appends asm to the file name and tries to open the file again If no path is given for a particular file the assembler will look for that file in the current directory The list of files will be processed se quentially in the order given and all files will be used to generate the output listing and object file The assembler will
175. bnums Enable the specified breakpoints to work once and then die Each of the break points will be deleted the next time it stops the program unless you have used one of these commands to specify a different state before that time comes Aside from the automatic disablement or deletion of a breakpoint when it stops the program which happens only in certain states the state of enablement of a breakpoint changes only when one of the commands above is used 3 10 4 Break Conditions The simplest sort of breakpoint breaks every time the program reaches a specified place You can also specify a condition for a breakpoint A condition is just a boolean expres sion in your programming language See section Expressions A breakpoint with a con dition evaluates the expression each time the program reaches it and the program stops only if the condition is true Break conditions may have side effects and may even call functions in your program These may sound like strange things to do but their effects are completely predictable unless there is another enabled breakpoint at the same address In that case GDB a _ _ __ _ _z _ gt A SE Eee E 30 DSP56KCC User s Manual MOTOROLA might see the other breakpoint first and stop the program without checking the condition of this one Note that breakpoint commands are usually more convenient and flexible for the purpose of performing side effects when a breakpoint is reached see section Brea
176. bootstrap code labeled at F start in ctr0 Remember that the mode select pins on the chip control the chip operating mode when leaving reset which in turn controls the reset vector address see the Motorola DSP56000 DSP56001 User s Manual for more details 2 Configure all hardware registers needed i e omr host port etc This is also a proper place to initialize any non C related data structures or peripheral hardware such as the bcr Port B and Port C 3 Load the Stack Pointer r6 with a pointer to the base of the stack Remember that the stack grows up the value in the stack pointer gets greater as data is pushed The value of DSIZE is generated by the linker and is the first address above the statically allocated data C global and static variables By default this value is used as the initial stack pointer 4 Optional Initialize the frame pointer r0 This may be of use to some debuggers when stack back traces are performed Program execution will not be affected if this initialization is omitted 5 Call main with instruction jsr Fmain Notice that the label is Fmain and there are no parameters passed to the main function The normal C compiler start up passes two arguments but g56k does not pass any arguments because DSP56KCC does not support a particular hosted environment _ gt _ _ ___ _ gt E_ __ ____ A AAA 6 2 DSP56KCC User s Manual MOTOROLA The bootstrap code is followed with the
177. both the exponent and mantissa are zero SEE ALSO modf Decomposing a double into mantissa and exponent EXAMPLE include lt stdio h gt include lt stdlib h gt void main int exp double mant mantissa frexp 70 9 amp exponent printf mantissa f texponent d n mant exp prints to standard output mantissa 0 553906exponent A AA AAA A A O A 46 DSP56KCC User s Manual MOTOROLA fscanf fscanf NAME fscanf Read formatted input from a stream SYNOPSIS include lt stdio h gt int fscanf FILE stream const char format DESCRIPTION The function fscanf reads input from the specified stream It uses the string format as a guide for interpreting the input and storing values in memory Subsequent arguments to fscanf are used as pointers to objects in memory that will receive the input values read from the stream The format string is composed of directives These are parsed from left to right from the format string and indicate how the input from the specified stream should be processed If fscanf fails to apply a directive then it returns Directives are composed of either white space characters or normal characters White space character sequences indicate that fscanf should read input from the specified stream up to the first non white space character Directives that consist of non white space characters are processed in the following manner input is read from the spec
178. bsequent calls If s is non NULL then it must point to a writable buffer of at least L_tmpnam characters SEE ALSO tmpfile Create a temporary binary file EXAMPLE include lt stdio h gt void main char buffer L_tmpnam void fopen tmpnam buffer w will create a temporary text file on the disk Note that unlike when tmpfile is called one must remove any files created using fopen and tmpnam r M MOTOROLA DSP56KCC User s Manual A 151 tolower tolower NAME tolower Convert uppercase character to lowercase SYNOPSIS include lt ctype h gt int tolower int c DESCRIPTION The tolower function converts uppercase to lowercase If c is an uppercase letter return the corresponding lowercase letter otherwise return c When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main printf tolower A c n tolower A printf tolower z c n tolower z printf tolower c n tolower i prints to standard output tolower A a tolower z Z tolower 4 r O A 152 DSP56KCC User s Manual MOTOROLA toupper toupper NAME toupper Convert
179. c 1987 INTRODUCTION TO DIGITAL SIGNAL PROCESSING Roman Kuc New York NY McGraw Hill Company Inc 1988 _______ ____ gt gt gt _ __ ______ E D 16 DSP56KCC User s Manual MOTOROLA INTRODUCTION TO ADAPTIVE FILTERS Simon Haykin New York NY MacMillan Publishing Company 1984 MUSICAL APPLICATIONS OF MICROPROCESSORS Second Edition H Chamberlin Hasbrouck Heights NJ Hayden Book Co 1985 C Programming Language C A REFERENCE MANUAL Samuel P Harbison and Guy L Steele Prentice Hall Software Series 1987 PROGRAMMING LANGUAGE C American National Standards Institute ANSI Document X3 159 1989 American National Standards Institute inc 1990 THE C PROGRAMMING LANGUAGE Brian W Kernighan and Dennis M Ritchie Prentice Hall Inc 1978 Controls ADAPTIVE CONTROL K Astrom and B Wittenmark New York NY Addison Welsey Publishing Company Inc 1989 ADAPTIVE FILTERING PREDICTION 8 CONTROL G Goodwin and K Sin Englewood Cliffs NJ Prentice Hall Inc 1984 AUTOMATIC CONTROL SYSTEMS B C Kuo Englewood Cliffs NJ Prentice Hall Inc 1987 COMPUTER CONTROLLED SYSTEMS THEORY amp DESIGN K Astrom and B Wittenmark Englewood Cliffs NJ Prentice Hall Inc 1984 DIGITAL CONTROL SYSTEMS B C Kuo New York NY Holt Reinholt and Winston Inc 1980 DIGITAL CONTROL SYSTEM ANALYSIS amp DESIGN C Phillips and H Nagle Englewood Cliffs NJ Prentice Hall Inc 1984 MOTOROLA DSP56KCC U
180. ccon ooo 4 18 4 11 9 Loop Rotation 252020522 dab 2 ber ciar tda bobas 4 18 4 11 10 Jump Optimizations weenie es eee oe ee be x oce e 4 19 4 11 11 Instruction GOombpInallON 2 ira a Be sens 4 19 4 11 12 Leaf Routine Detection 0 0 00 oo 4 19 4 11 13 PUNCHOR AMIA st ed sta OS Sal tee oa ols ae dba ae 4 20 4 11 14 Instruction Scheduling Microcode Compaction 4 20 Chapter 5 Mixing C and Assembly Language 5 1 OVODIDW elas acosa teams dos toS etiara Sx VE EPA PA EP 5 1 5 2 In line Assembly Code 5 2 ol nce Ieremias 5 1 5 2 1 Instruction Template sued eer eu aa uoce ot 5 3 5 2 2 Output Input Operands x axem S ii Pad edm arias 5 5 5 2 3 Explicit Register Saving aeann irradia ESO UAE 5 7 5 2 4 In line Assembly Code Examples 0 2000 0 eee 5 8 5 2 5 Controlling Labels Generated by the Compiler 5 16 u M ii DSP56KCC User s Manual MOTOROLA Table of Contents Continued Paragraph Page Number Title Number 5 2 5 1 Calling Assembly Subroutines ooooccooooooooo 5 16 5 2 5 2 Calling C Subroutines from Assembly Code 5 17 5 2 5 3 Referencing Assembly Global Variables fromC 5 18 5 2 5 4 Referencing Global C Variables from Assembly Language 5 19 5 2 6 Specifying Registers for VariablesS oooooooooo 5 21 5 2 7 Optimizer Effects on Code
181. cently n defaults to one All of these commands end by printing some information on the frame that has been selected the frame number the function name the arguments the source file and line number of execution in that frame and the text of that source line For example 3 main argc 3 argv env at main c line 67 67 read input file argv i After such a printout the list command with no arguments will print ten lines cen tered on the point of execution in the frame See section List 3 16 Information on a Frame There are several other commands to print information about the selected stack frame frame This command prints a brief description of the selected stack frame It can be ab breviated f With an argument this command is used to select a stack frame with no argument it does not change which frame is selected but still prints the same information info frame This command prints a verbose description of the selected stack frame including the address of the frame the addresses of the next frame in called by this frame and the next frame out caller of this frame the address of the frame s arguments the program counter saved in it the address of execution in the caller frame and which registers were saved in the frame The verbose description is useful when something has gone wrong that has made the stack format fail to fit the usual con ventions _ ________ _z_ gt _ gt EQ
182. cessed via the specified stream SYNOPSIS include lt stdio h gt FILE freopen const char filename const char mode FILE stream DESCRIPTION The function freopen opens the named disk file in the same manner as fopen However freopen associates that file with the specified stream If successful freopen returns its argument stream and if unsuccessful it returns NULL The range of acceptable values for the mode argument are the same as those for fopen SEE ALSO printf Used to write formatted output to standard output EXAMPLE include lt stdio h gt void main freopen diskfile w stdout printf hello world This example redirects standard output to a file on the disk via freopen The hello world output will not appear on the normal standard output device but rather in the file diskfile eee l o MOTOROLA DSP56KCC User s Manual A 45 frexp frexp NAME frexp Break a floating point number into mantissa and exponent SYNOPSIS include lt math h gt double frexp double value int exp DESCRIPTION The frexp function breaks a floating point number into a normalized fraction the mantissa and an integral power of 2 the exponent The frexp function returns the mantissa and stores the exponent in the integer object pointed to by exp The mantissa is returned with a magnitude in the range 1 2 1 or zero such that value equals the mantissa times 2 P If value is zero
183. clared with the appropriate prototype in a header whose contents are made available by the include preprocessing directive In addition to function prototypes the header also defines all type and MACRO definitions required for ANSI conformance The ANSI standard header files provided are lt assert h gt lt locale h gt lt stddef h gt lt ctype h gt lt math h gt lt stdio h gt lt errno h gt lt setjmp h gt lt stdlib h gt lt float h gt lt signal h gt lt string h gt lt limits h gt lt stdarg h gt lt time h gt In general header files may be included in any order and as often as desired with no negative side effects The one exception occurs when including lt assert h gt The definition of the assert macro depends on the definition of the macro NDEBUG The contents of the standard header files provided are exactly as described by the ANSI document X3 159 1989 dated December 14 1989 A 2 ANSI C Library Sub routines There are three library images provided with each compiler e libb6cx clb x memory model e libb6cy clb y memory model e lib56cl clb memory model M ME MOTOROLA DSP56KCC User s Manual A 1 Each library contains all of the ANSI defined sub routines compiled and or assembled for the specific memory model The C and assembly language source for each library routine is distributed free of charge with the compiler A 2 1 Hosted vs Non Hosted Library Routines Some of the stan
184. clrend Clear from cursor position to end of line by issuing the escape sequence ESC t void clrend clear from cursor to end of line void putc putc ESCAPE putc t cur_pos ii Move the cursor to the row and column of the screen specified by r and c respectively by issuing the escape sequence ESC R C where R is the rth character after ascii 31 and c is the cth character after ascii character 31 void cur pos r c int r int c void putc List F 9 The list of I O function io scrn c _ ___ MMM E F 28 DSP56KCC User s Manual MOTOROLA void putint putc ESCAPE putc putc char SPACE 14r output ascii character 31 r putc char SPACE 14c output ascii character 31 c screen_attr Send escape sequence to set a new screen attribute format is ESC G ATTR where ATTR is the attribute code void screen_attr attr char attr putc ESCAPE putc G putc attr MOTOROLA DSP56KCC User s Manual F 29 io_host c This file contains the low level functions to support the communication between port B and Host Interface of DSP56001 s The functions includes the configuration of port B for general purpose I O reading and writing registers of Host Interface and downloading data to the Host interface of a target The following hardware interconnections between Port B of the Host and the Host Inte
185. command you can delete breakpoints according to where they are in the program With the delete command you can delete individual breakpoints by specifying their breakpoint numbers It is not necessary to delete a breakpoint to proceed past it GDB automatically ig nores breakpoints in the first instruction to be executed when you continue execution without changing the execution address clear Delete any breakpoints at the next instruction to be executed in the selected stack frame see section Selection When the innermost frame is selected this is a good way to delete a breakpoint that the program just stopped at clear function clear filename function Delete any breakpoints set at entry to the function function clear linenum clear filename linenum Delete any breakpoints set at or within the code of the specified line delete bnums Delete the breakpoints of the numbers specified as arguments 3 10 3 Disabling Breakpoints Rather than deleting a breakpoint you might prefer to disable it This makes the break point inoperative as if it had been deleted but remembers the information on the break point so that you can enable it again later You disable and enable breakpoints with the enable and disable commands specifying one or more breakpoint numbers as arguments Use info break to print a list of break points if you don t know which breakpoint numbers to use A breakpoint can have any of
186. completion of longjmp program execution continues as if the corresponding call to setjmp had returned with a value val if val is zero 1 is returned Global and volatile type variables have values as of the time longjmp was called all register and non volatile automatic variables will have indeterminate values For more information see Chapter 6 SEE ALSO setimp Save a reference of the current calling environment for later use by longjmp EXAMPLE include lt stdio h gt include lt setjmp h gt jmp buf env void func void longjmp env 709 main if setimp env 0 printf longjmp has been called n eHO A 72 DSP56KCC User s Manual MOTOROLA longjmp longjmp exit 1 printf setjmp called n func prints to standard output setimp called longjmp called AAA A A AA A A Ml MOTOROLA DSP56KCC User s Manual A 73 malloc malloc NAME malloc Dynamically allocate uninitialized storage SYNOPSIS include lt stdlib h gt void malloc size_t size DESCRIPTION The malloc function returns a pointer to the lowest word of a size word block of storage when size exceeds the amount of memory available malloc returns NULL SEE ALSO alloca Allocate storage in the stack frame calloc Dynamically allocate zero initialized storage free Free dynamically allocated memory realloc Alter size of dynamically allocated storage EXAMPLE
187. concerned with To find the code number type info signal which prints a table of signal names and numbers The keywords allowed by the handle command can be abbreviated Their full names are stop GDB should stop the program when this signal happens This implies the print keyword as well print GDB should print a message when this signal happens nostop GDB should not stop the program when this signal happens It may still print a message telling you that the signal has come in noprint GDB should not mention the occurrence of the signal at all This implies the nostop keyword as well pass GDB should allow the program to see this signal the program will be able to han dle the signal or may be terminated if the signal is fatal and not handled nopass GDB should not allow the program to see this signal When a signal has been set to stop the program the program cannot see the sig nal until you continue It will see the signal then if pass is in effect for the signal in question at that time In other words after GDB reports a signal you can use the handle command with pass or nopass to control whether that signal will be seen by the program when you later continue it You can also use the signal command to prevent the program from seeing a sig nal or cause it to see a signal it normally would not see or to give it any signal at any time See section Signaling 3 10 Breakpoi
188. ction SEE ALSO fscanf Read formatted input from a stream EXAMPLES See the manual entry for fscanf for examples The only difference between scanf and fscanf is that scanf does not require a FILE argument stdin is implied rn o Mo MOTOROLA DSP56KCC User s Manual A 109 setjmp setjmp NAME setimp Save a reference of the current calling environment for later use by longjmp SYNOPSIS include lt setjmp h gt int setimp jmp buf env DESCRIPTION The setjmp function saves its calling environment in env for later use by longjmp If the return is direct from setjmp the value zero is returned If the return is from the longjmp function the value returned is non zero For more information see Chapter 6 SEE ALSO longjmp Execute a non local jump a O A 110 DSP56KCC User s Manual MOTOROLA setimp setjmp EXAMPLE include lt stdio h gt include lt setjmp h gt jmp buf env void func void longjmp env 709 void main if setimp env 0 printf longjmp has been called n exit 1 j printf setimp called n func prints to standard output setjmp called longjmp called A ee A M MOTOROLA DSP56KCC User s Manual A 111 setbuf setbuf NAME setbuf Read formatted input from standard input SYNOPSIS include lt stdio h gt void setbuf FILE stream char buf DES
189. ction uses the argument as a seed for a new sequence of pseudo random numbers to be returned by rand When srand is called with the same argument the sequence of pseudo random numbers will be repeated If srand is not called the default seed is 1 SEE ALSO rand Generate a pseudo random number sequence EXAMPLE include lt stdio h gt void main seed the random number sequence srand 1638 spew out random numbers in the range 0 to 709 for 55 printf d rand 709 prints to standard output 545 174 307 657 220 267 66 47 651 268 284 338 35 615 403 etc _ ____________ A AAA MOTOROLA DSP56KCC User s Manual A 121 sscanf sscanf NAME sscanf Read formatted input from a string SYNOPSIS include lt stdio h gt int sscanf const char s const char format DESCRIPTION The function sscanf reads formatted input from the string argument s according to the format string format The operation of sscanf is identical to fscanf except that input is read from a string SEE ALSO fscanf Read formatted input from a string a OO O A 122 DSP56KCC User s Manual MOTOROLA strcat strcat NAME strcat Concatenate two strings SYNOPSIS include lt string h gt char strcat char s1 const char s2 DESCRIPTION The strcat function appends a copy of the string pointed to by s2 including the terminating null character to the end of the strin
190. d in the value history by the print command remains 4 even though the value of x has changed info values Print the last ten values in the value history with their item numbers This is like p 9 repeated ten times except that info values does not change the history info values n Print ten history values centered on history item number n info values Print ten history values just after the values last printed eau MOTOROLA DSP56KCC User s Manual E 55 3 27 Convenience Variables GDB provides convenience variables that you can use within GDB to hold on to a value and refer to it later These variables exist entirely within GDB they are not part of your program and setting a convenience variable has no effect on further execution of your program That s why you can use them freely Convenience variables have names starting with Any name starting with can be used for a convenience variable unless it is one of the predefined set of register names see section Registers You can save a value in a convenience variable with an assignment expression just as you would set a variable in your program Example set foo object_ptr would save in foo the value contained in the object pointed to by object_ptr Using a convenience variable for the first time creates it but its value is void until you as sign a new value You can alter the value with another assignment at any time Convenience variables have
191. d with the cont command so that the pro gram does not stop and start with the silent command so that no output is produced Here is an example break 403 commands silent setx y 4 cont end One deficiency in the operation of automatically continuing breakpoints under Unix ap pears when your program uses raw mode for the terminal GDB switches back to its own terminal modes not raw before executing commands and then must switch back to raw mode when your program is continued This causes any pending terminal input to be lost In the GNU system this will be fixed by changing the behavior of terminal modes Under Unix when you have this problem you might be able to get around it by putting your actions into the breakpoint condition instead of commands For example condition 5 x y 4 0 specifies a condition expression See section Expressions that will change x as needed then always have the value 0 so the program will not stop Loss of input is avoided here because break conditions are evaluated without changing the terminal modes When you want to have nontrivial conditions for performing the side effects the operators amp amp and may be useful 3 10 6 Cannot Insert Breakpoints Error Under some operating systems breakpoints cannot be used in a program if any other process is running that program Attempting to run or continue the program with a break point in this case w
192. dard ANSI defined routines perform I O Programs that use these functions will not encounter problems when run using gdb56 or run56 Extra work may be needed to port hosted I O routines to custom hardware configurations Non hosted routines will not encounter any problems on custom hardware For a description of run56 see Appendix C A 3 Forcing Library Routines Out of line For performance reasons several run time library routines have been created to be used in line by the compiler The compiler in lines a sub routine by replacing the occurrence of the sub routine call with the body of the sub routine itself This provides execution time benefits 1 Eliminates sub routine call overhead This is a substantial portion of the run time for small library routines 2 Exposes more optimization opportunities to the optimizer The following library routines are automatically in lined by the compiler when their header file is included header ctype h isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit e tolower e toupper header math h ceil fabs floor e fmod header stdlib h e abs e labs header string h strcmp strcpy u ccO A 2 DSP56KCC User s Manual MOTOROLA When it is necessary to disable this feature possibly for debugging or decreasing program size simply do one of the following
193. dard directory search list for UNIX systems is 1 usr local dsp bin 2 usr local dsp lib 3 lib 4 usr lib 5 ail The standard MS DOS directory search list for the path set up in Section 2 2 is cAdsp bin c dsp lib C cidos 5 other directories in the path name Note that if the environment variable DSPLOC is set the value of DSPLOC will be substituted for 1 and 2 above pe ee A Table 3 1 lists all the user selectable options used by g56k They are grouped to show what program uses each option All of these options are described in detail later in this chapter however these lists provide an overview of what options are available Notice that there is a v option listed under both g56k Command Options and Preprocessor Phase Options This is actually the same option but it is used by these two programs in different ways see Section 3 2 and Section 3 2 1 Under compile phase options there is a group of f options these are the machine inde pendent optimization options whereas the m options below are the optimization options specific to the DSP56000 1 Although these various methods of optimization are all ef fective they may have side effects which are undesirable in specific cases e g an opti mization option may increase code speed at the cost of increased memory usage It is Ea KC 3 2 DSP56KCC User s Manual MOTOROLA Table 3 1 DSP56KCC Options g56k Command Line Options Bdirectory bPREFIX o FILE
194. de The F start label is the program address of the C program bootstrap code which calls the C main function after execution Interrupt vectors that are to be used must be reprogrammed to point to the interrupt ser vice routines instead of the abort function Initialization of the interrupt vectors in the crto file reduces the size of the resulting application program and may increase its speed The following crt0 code segment called section reset is the default interrupt vector table initialization u M n 6 6 DSP56KCC User s Manual MOTOROLA section reset org p 0 jmp F_start org p 2 dup 31 jsr Fabort endm endsec The interrupt vector table can be changed to point to user provided interrupt service rou tines instead of the abort routine in this portion of crt0 Example 6 5 illustrates how to initialize pointers to these user provided interrupt service routines Example 6 5 User defined Interrupt Vector Table Assume the hardware supports all interrupts and each interrupt service routine is located at the address labeled interruptXX where XX is the value of the interrupt vector The following code initializes the interrupt vector table Each service routine starting at interruptXX can be programmed in assembly language as shown in Example 6 6 section reset org p 0 jmp F_ start jsr interrupt02 jsr interrupt04 jsr interrupt06 jsr inte
195. de lt stdio h gt include lt stdlib h gt void main int neg 709 printf abs d d n neg abs neg prints to standard output abs 709 709 r r d EEE A 8 DSP56KCC User s Manual MOTOROLA acos acos NAME acos Arc cosine SYNOPSIS include lt math h gt double acos double x DESCRIPTION The acos function computes the principle value of the arc cosine of x in the range 0 0 x where x is in radians If x is not in the range 1 1 a domain error occurs errno is set to EDOM and a value of 0 0 is returned SEE ALSO cos Cosine EXAMPLE include lt stdio h gt include lt math h gt void main double point for point 0 8 point lt 1 0 point 0 2 printf f acos point if point gt 0 0 printf n prints to standard output 2 498090 2 214290 1 982310 1 772150 1 570790 1 369430 1 159270 0 927295 0 643501 0 000345 es _ _ OEA MOTOROLA DSP56KCC User s Manual A 9 asin asin NAME asin Arc sine SYNOPSIS include lt math h gt double asin double x DESCRIPTION The asin function computes the principle value of the arc sine of x in the range 1 2 7 2 where x is in radians If x is not in the range 1 1 a domain error occurs errno is set to EDOM and a value of 0 0 is returned SEE ALSO sin Sine EXAMPLE inc
196. difficult eeaeee Moo MOTOROLA DSP56KCC User s Manual 4 19 pe eO O 4 20 DSP56KCC User s Manual MOTOROLA Chapter 5 Mixing C and Assembly Language 5 1 Overview In cases where the DSP56000 DSP56001 programmer requires direct access to the hardware or greater performance at the inner loop of an algorithm C programs can be mixed with assembly programs This chapter describes two methods for combining C and assembly language source code The first is the in line method which is a convenient way to put assembly code into the compiler output via the non ANSI C directive _ _asm The second is the out of line method a generic method of combining C and assembly language source files Caution Before mixing C and assembly read and understand Chapter 4 About g56k and the DSP56000 Family Manual Attempting to write programs for this DSP without knowledge of the chip and how the compiler utilizes registers memory defines labels etc may generate unsatisfactory results However with an understanding of the DSP architecture and how this implementation of C uses it programming should be straightforward Note Labels which begin with a double underline e g _ asm in this manual have a space between the double underlines to visually separate them Do not separate the leading double underlines with a space when coding them i e code __asm as __asm 5 2 In line Assembly Code In line assembly code is assembly code that is inse
197. ding One No Yes Mantissa Format 24 bit Two s 23 bit Unsigned Complement Fraction Magnitude Fraction Exponent Width 16 bits 14 bits used 8 bits 11 bits Maximum Exponent 8192 127 8 bit case 1023 11 bit case Minimum Exponent 8191 127 8 bit case 1022 11 bit case Exponent Bias 8191 127 8 bit case 1023 11 bit case Format Width 48 bits 32 bits 8 bit case 64 bits 11 bit case Rounding Round to Nearest Round to Nearest Round to Infinity Round to Zero Infinity Arithmetic Saturation Limiting Affine Operations Denormalized Numbers No Forced to Zero Yes with Min Exp Exceptions Divide by Zero Invalid Operation Overflow Divide by Zero Negative Square Root Overflow Underflow Inexact Arithmetic One major difference is the use of affine arithmetic in the IEEE standard versus the use of saturation arithmetic in the DSP56KCC format Affine arithmetic gives separate identity to plus infinity minus infinity plus Zero and minus zero In operations involving these values finite quantities remain finite and infinite quantities remain infinite In contrast DSP56KCC format gives special identity only to unsigned zero This format performs saturation arithmetic such that any result out of the representable floating point range is replaced with the closest floating point representation Since the dynamic range of this format is quite large it is adequate for most applications The IEEE floating point standard provides ex
198. ding the IBM PC 80386 family and above 386sx 486 etc and Sun SPARC workstations The compiler implements the full C language as defined in American National Standard for Information Systems Programming Language C ANSI X3 159 1989 It accepts one or more C language source files as input and generates a corresponding number of assembly language source files which are suitable as inputs to the DSP56000 COFF assembler The compiler automatically implements numerous optimizations which simplifies implementing fast and efficient DSP algorithms The C language preprocessor is an implementation of the ANSI standard which includes support for arbitrary text file inclusion macro definition and expansion and conditional compilation The preprocessor exists as a separate program and may be used as a general purpose macro preprocessor The compiler control program g56k is the standard compiler interface used to control 5 lt eS MOTOROLA DSP56KCC User s Manual 1 1 User s Input Files C Source Files ANSI C Compiler Optional COFF Librarian COFF Assembler ns Rm Rm Libra User Provided PROM Programmer Execution Devices gdb56 sim56000 ads56000 AES Figure 1 1 Motorola Software Development System srec Conversion utility 1 2 DSP56KCC User s Manual MOTOROLA tthe sequence of operations required to compile a program This control program allows the
199. dress of the last breakpoint listed When you use RET to repeat an x command it does not repeat exactly the same the address specified previously if any is ignored so that the repeated command examines the successive locations in memory rather than the same ones i A A AAA E 52 DSP56KCC User s Manual MOTOROLA You can examine several consecutive units of memory with one command by writing a repeat count after the slash before the format letters if any The repeat count must be a decimal integer lt has the same effect as repeating the x command that many times ex cept that the output may be more compact with several units per line For example x 10i pc prints ten instructions starting with the one to be executed next in the selected frame Af ter doing this you could print another ten following instructions with x 10 in which the format and address are allowed to default The addresses and contents printed by the x command are not put in the value history because there is often too much of them and they would get in the way Instead GDB makes these values available for subsequent use in expressions as values of the conve nience variables and After an x command the last address examined is available for use in expressions in the convenience variable The contents of that address as examined are available in the convenience variable If the x command has a repeat count the addres
200. e driving bald on feet kh static int compare const char a1 const char a2 return strcmp a1 a2 main int i qsort stuff size_t 6 size_t sizeof char compare for i 0 1 lt 6 i printf s t stuff i printf n prints to standard output bald driving feet flintstone fred on eee U E MOTOROLA DSP56KCC User s Manual A 101 ralse ralse NAME raise Raise a signal SYNOPSIS include lt signal h gt int raise int sig DESCRIPTION The raise function sends the signal sig to the executing program and returns 0 if successful or non zero if unsuccessful See signal h for list of available signals and their default actions For more information see Chapter 6 SEE ALSO signal Set up a signal handler EXAMPLE include lt stdio h gt void main int onintr signal SIGINT onintr raise SIGINT onintr printf caught SIGINT see ya n exit 9 prints to standard output caught SIGINT see ya A HG A 102 DSP56KCC User s Manual MOTOROLA rand rand NAME rand Pseudo random number generator SYNOPSIS include lt stdlib h gt int rand void DESCRIPTION The rand function computes and returns a sequence of pseudo random integers in the range of 0 to 32767 SEE ALSO srand Seed the pseudo random number generator EXAMPLE include lt stdio h gt void main seed the random
201. e If they are used in assembly code they should only be used as local variables Explicit register saving is done through specifying the registers to be saved A string is used to specify each register The valid register names are listed in Table 5 2 _ _____ gt gt gt gt _ M 1 MOTOROLA DSP56KCC User s Manual 5 7 Table 5 2 reg_save Names Register Type Valid Names Accumulator a b Input x0 X1 yo y1 Address ro r7 An example for reg_save is a program performing an IIR filter operation which is based on the Dr BuB IIR filter program iirt asm The program data structure is the same as the Dr BuB program and data is passed through the C variable data Pointers sptr and cptr are used to point to static variables Example 5 1 reg_save This in line assembly code is converted from the Dr BuB IIR filter program using reg_save This program is based on Y Memory Model and there are other in line assembly features used here for the demonstration of the reg save Section 5 2 4 may need to be referenced for the other feature of the in line assembly iir1 int data int sptr int cptr _ asm volatile move 0 a n move 1 r1 n move 2 r4 n move y r1 x0 n move y r4 yO n mac x0 y0 a y r4 yO n move y r1 x1 n macr x1 y0 a x0 y r1 n move a y r1 no output D data A sptr A c
202. e foo c C gt type foo c foo c main begin int d 1000 delay while d main loop end C gt g56k Wcomment foo c YS AAA A AAA 3 18 DSP56KCC User s Manual MOTOROLA Compile Phase Options foo c 3 warning within comment foo c 4 warning within comment foo c 4 warning within comment C gt g56k foo c Wtrigraphs Warn if any trigraphs are encountered Trigraphs are sequences of three characters which are replaced by a single character These trigraph sequences enable the in put of characters that are not defined in the Invariant Code Set as described in ISO 646 1983 which is a subset of the seven bit ASCII code set 3 2 2 Compile Phase Options The default options are perform all machine dependent and independent optimizations do not run the assembly language optimizer alo56 do not generate debugging information and locate data only in the Y data memory space Bede DEA alo Run the assembly language optimizer on the assembly language output of g56 cc1 This improves the utilization of parallel moves fno opt Disable all optimizations fno peephole Disable the peephole portion of optimization fno strength reduce Disable the optimizations of loop strength reduction and elimination of iteration vari ables as well as DSP56000 1 specific looping optimizations DO instruction usage etc fno defer pop By default the compiler will try t
203. e lt ctype h gt void main if isspace printf space white space character n if isspace printf O not white space character n prints to standard output space white space character not white space character _zz z MMEA A 64 DSP56KCC User s Manual MOTOROLA isupper isupper NAME isupper Test for upper case alphabetic character SYNOPSIS include lt ctype h gt int isupper int c DESCRIPTION The isupper function returns a nonzero value for any upper case alphabetic character zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if isupper F printf F upper case character n if isupper f printf f not an upper case character n prints to standard output F upper case character f not an upper case character gt _ UM O MOTOROLA DSP56KCC User s Manual A 65 isxdigit isxdigit NAME isxdigit Test for hexadecimal numeric character SYNOPSIS include lt ctype h gt int isxdigit int c DESCRIPTION The isxdigit function returns a nonzero value for any h
204. e Size words Min value Max value float 2 1 175494351e 38 3 402823466e 38 double 2 1 175494351e 38 3 402823466e 38 4 4 2 1 Floating point Format Description Figure 4 1 illustrates the floating point format used in DSP56KCC Figure 4 1a shows that the exponent and mantissa occupy consecutive memory locations Figure 4 1b is in num ber line format and shows the fractional nature of the mantissa and the fact that due to the nature of a fractional arithmetic mantissa the numbers between 0 5 and 0 5 except for zero are not needed and are therefore reserved Figure 4 1c shows the range used by the exponent in this implementation Notice how this compares with the IEEE imple mentation shown in Table 4 6 Figure 4 1d is a combined number line showing the range of numbers which can be represented in DSP56KCC The mantissa C00000 0 5 is not included as the smallest negative floating point number because the normalization routine automatically detects the two leading ones and decrements the exponent which if at 003FFF will result in an underflow Therefore the smallest negative mantissa has been set to BFFFFF 0 916 Table 4 5 lists the specific floating point format information for DSP56KCC and is a tabular version of the information in Figure 4 1 4 4 2 2 Comparison with IEEE STD 754 1985 Standard Since the IEEE floating point arithmetic standard is well publicized it is useful to compare these two floating point formats The D
205. e array pointed to by s1 The transformation is such that if the stremp function is applied to the two transformed strings it returns a value greater than equal to or less than zero corresponding to the result of the strcoll function applied to the same two original strings No more than n characters are placed into s1 including the terminating null character If s1 and s2 overlap the behavior is undefined The strxfrm function returns the length of the transformed string excluding the terminating null character If the value returned is n or more the contents of s1 are indeterminate SEE ALSO strcoll Compare two strings based on current locale strcmp Compare two strings SPECIAL NOTE DSP56KCC only supports the standard locale so no transformation is done ee ae M MOTOROLA DSP56KCC User s Manual A 147 tan tan NAME tan Tangent SYNOPSIS include lt math h gt double tan double x DESCRIPTION The tan function computes and returns the tangent of x where x is in radians SEE ALSO atan Compute the arc tangent atan2 Compute the arc tangent of a point EXAMPLE include lt stdio h gt include lt math h gt void main printf tan 45 f n tan 45 prints to standard output tan 45 1 619775 pe aee O A 148 DSP56KCC User s Manual MOTOROLA tanh tanh NAME tanh Hyperbolic tangent SYNOPSIS include lt math h gt double tanh double x DESCR
206. e commandname Define a command named commandname If there is already a command by that name you are asked to confirm that you want to redefine it The definition of the command is made up of other GDB command lines which are given following the define command The end of these commands is marked by a line containing end document commandname Give documentation to the user defined command commandname The command commandname must already be defined This command reads lines of documen tation just as define reads the lines of the command definition ending with end After the document command is finished help on command commandname will print the documentation you have specified You may use the document command again to change the documentation of a command Redefining the command with define does not change the documen tation User defined commands do not take arguments When they are executed the commands of the definition are not printed An error in any command stops execu tion of the user defined command Commands that would ask for confirmation if used interactively proceed without asking when used inside a user defined command Many GDB commands that normally print messages to say what they are doing omit the messages when used in user defined command a ee MOTOROLA DSP56KCC User s Manual E 65 3 34 Command Files A command file for GDB is a file of lines that are GD
207. e files are executed after all the command options and argu ments have been processed q Do not print the version number on start up OUR in batch mode Exit with code 1 after processing all the command files specified with x and gdbinit if not inhibited Exit also if due to an error gdb56 would otherwise attempt to read a command from the terminal fullname This option is used when Emacs runs GDB as a subprocess It tells GDB to produce the full file name and line number each time a stack frame is dis played which includes each time the program stops help Print command line argument summary tty TTY Use TTY for input output by the program being debugged cd DIR Change current directory to DIR SEE ALSO Appendix E GNU Debugger GDB r A O C 18 DSP56KCC User s Manual MOTOROLA runb6 runb6 NAME run56 Motorola DSP56000 DSP56001 Simulator Based Execution Device SYNOPSIS run56 b BCR VALUE s STATE FILE tx file DESCRIPTION run56 is a COFF object file execution utility that provides operating system style hooks to support hosted ANSI run time library routines such as printf file is an operating system compatible file name Only a single file name may be supplied and it must be explicit there is no default extension for the input file OPTIONS b BCR_VALUE Use BCR_VALUE to set the DSP56000 DSP56001 bus control register Default bcr valu
208. e is 0 s STATE_FILE Resume the execution of the DSP56000 DSP56001 state file STATE_FILE t Update global C variable time at each clock tick Used to benchmark code X Indicates the input file was generated from the x memory model of C com piler The C compiler may use x y or memory model for the compilation refer to the option m of the C compiler and this option directs the run56 program to use the X memory space for data buffer Without this option y memory model or L memory model is assumed eee O O MOTOROLA DSP56KCC User s Manual C 19 NAME srec Motorola DSP S Record Conversion Utility SYNOPSIS srec b w m s I r files gt DESCRIPTION srec converts Motorola DSP cld and lod format files into Motorola S record files The S record format was devised for the purpose of encod ing programs or data files in a printable form for transportation between computer systems Motorola S record format is recognized by many PROM programming systems files is a list of operating system compatible file names If no pathname is specified for a given file srec will look for that file in the current directory If the special character is used as a file name srec will read from the stan dard input stream The list of files will be processed sequentially in the or der given OPTIONS Only one of the following command line options may be given for each invo cation of the librarian Opti
209. e of a character in a string strspn Compute the length of the prefix of one string that consists only of characters from another string EXAMPLE include lt stdio h gt include lt string h gt void main int i i strcspn azbyfghjki fkjeughtrg printf prefix length d n i prints to standard output prefix length 4 en U EO MOTOROLA DSP56KCC User s Manual A 129 strerror strerror NAME strerror Map error code into an error message string SYNOPSIS include lt string h gt char strerror int errnum DESCRIPTION The strerror function maps errnum to an error message string A pointer to the string is returned The string returned should not be modified by the programmer SEE ALSO perror Print error message EXAMPLE include lt stdio h gt include lt string h gt void main int i 0 char s while s strerror i NULL printf tmessage d t s n i s prints to standard output message 1 domain error message 2 range error message 3 out of heap memory message 4 bad format for conversion string a E A 130 DSP56KCC User s Manual MOTOROLA strlen strlen NAME strlen Determine length of a string SYNOPSIS include lt string h gt size_t strlen const char s DESCRIPTION The strlen function computes and returns the number of characters proceeding the terminating character EXAMPLE include lt stdi
210. e register would contain if all stack frames farther in were exited and their saved registers restored In order to see the real contents of all reg isters you must select the innermost frame with frame 0 Some registers are never saved typically those numbered zero or one because they are used for returning function values for these registers relativization makes no difference info registers Print the names and relativized values of all registers info registers regname Print the relativized value of register regname regname may be any register name valid on the machine you are using with or without the initial 3 28 1 Examples You could print the program counter in hex with A ee MOTOROLA DSP56KCC User s Manual E 57 p x pc or print the instruction to be executed next with x i pc or add four to the stack pointer with set sp 4 The last is a way of removing one word from the stack on machines where stacks grow downward in memory most machines nowadays This assumes that the innermost stack frame is selected Setting sp is not allowed when other stack frames are selected r C n O S S E 58 DSP56KCC User s Manual MOTOROLA D 9 Examining the Symbol Table The commands described in this section allow you to make inquiries for information about the symbols names of variables functions and types defined in you
211. e string The sprintf function returns the number of characters written to the string SEE ALSO printf Print to a standard output eeaeee O A 118 DSP56KCC User s Manual MOTOROLA sprintf sprintf EXAMPLE include lt stdio h gt void main char buffer 256 char bptr buffer char str strings int i 709 count double d 7 09 bptr sprintf bptr testing sprintf within sprintf bptr tstrings t s n n str amp count bptr count bptr sprintf bptr thex digits t x n i bptr sprintf bptr tfloating point t f n d puts buffer prints to standard output testing sprintf with strings strings hex digits2c5 floating point7 090000 AAA A A A A A A A A A A A E MOTOROLA DSP56KCC User s Manual A 119 sqrt sart NAME sqrt Square root SYNOPSIS include lt math h gt double sqrt double x DESCRIPTION The sqrt function computes and returns the nonnegative square root of x If x is less than zero errno is set to EDOM and 0 0 is returned EXAMPLE include lt stdio h gt include lt math h gt void main double 50 2681 printf sqrt 50 2681 2f n sqrt d prints to standard output sqrt 50 2681 7 09 pe eee O A 120 DSP56KCC User s Manual MOTOROLA srand srand NAME srand Seed the pseudo random number generator SYNOPSIS include lt stdlib h gt void sqrt unsigned int seed DESCRIPTION The srand fun
212. e swap space Default is DOS4GVM SWP on the cur rent drive DELETESWAP Specifies that the swap file should be deleted after mem ory management VIRTUALSIZE The size of the virtual memory space Default is 16MB The value should be entered as numeric value of Kbyte As an example the following line in the autoexec bat file will enable an 8MB swap file with automatic deletion of the swap file SET DOS4GVM DELETESWAP VIRTUALSIZE 8192 The following line will use F drive for the swap space instead of the current drive SET DOSAGVM DELETESWAP SWAPNAME F BIG SWP 8 There is a READ ME file included in the package and it should be read for any re cent changes in the installation on compiler itself 2 3 Standard Installation On A SUN 1 Insert the supplied first floppy diskette into the tape drive 2 Login as root _ gt gt M AAA MOTOROLA DSP56KCC User s Manual 2 3 3 Enter the command cd usr local 4 Enter the command bar xZvf dev r fdO If the floppy drive must be accessed via a different device file than rfdO then use the appropriate device for your system 5 Logout 6 Make sure that all users add usr local dsp bin to their path This enables the shell to find the control program g56k and other programs in the DSP56KCC distribution package 2 4 Alternate Installation On A SUN 1 Insert the supplied first floppy diskette into the floppy drive 2 Login as root or as yourself if access per
213. e that the coefficients of the above example is desired to be in the program space when burning the PROM Then the following C segment pragma y load p 100 int coeff 5 0x19999a 0x200000 0x266666 Ox2ccccd 0x333333 pragma y_load YES MOTOROLA DSP56KCC User s Manual 5 23 produces the following assembly language code global Fcoeff org y p 100 Fcoeff dc 1677722 dc 2097152 dc 2516582 dc 2936013 dc 3355443 The above assembly code will be loaded into the P memory space at p 100 for the PROM burning and it should be copied to the L memory space before the actual program is executed Manipulating the assembler s run time and load time counters requires a thorough understanding of the underlying assumptions about memory layout which are made by the compiler see Chapter 6 Incorrect use of this feature may cause compile time link time and even run time errors 5 4 Out of line Assembly Code Out of line assembly code is assembly code written in a separate source file that is called from a C program Separating the assembly code and C code in this way provides a powerful and flexible interface to the DSP56000 family architecture This out of line method may be used to convert existing assembly subroutines write new subroutines completely in assembly language or access both data spaces X and Y The key advan tage of out of line assembly code is that it provides a complete assembly programming environment for the D
214. e used by debuggers to provide source level de bugging l lt ipath gt When the assembler encounters include files the current directory or the directory specified in the INCLUDE directive is first searched for the file If it is not found and the I option is supplied the assembler prefixes the file name and optional pathname specified in the INCLUDE directive with ip ath and searches the newly formed directory pathname for the file The l lt ipath gt sequence may be repeated as many times as desired The direc tories will be searched in the order given on the command line L lt lstfil gt This option specifies that a listing file is to be created for the assembler out put Istfil can be any legal operating system file name including an optional pathname A hyphen also may be used as an argument to indicate that the listing file should be sent to the standard output _ ______ gt gt z _ C 4 DSP56KCC User s Manual MOTOROLA asm56000 asm56000 If a path is not specified the file will be created in the current directory If no file name is supplied the assembler will use the basename file name with out extension of the first file name encountered in the source input file list The resulting output file will have an extension of Ist If the L option is not given then the assembler will route the listing output to the standard out put The L option should be specified only once M lt mpath gt
215. e whose symbol details have not been fully read Full detail is available for the function rtx equal p which is in the file rt lanal c Its arguments named x and y are shown with their typed values 3 15 Selecting a Frame Most commands for examining the stack and other data in the program work on whichev er stack frame is selected at the moment Here are the commands for selecting a stack frame all of them finish by printing a brief description of the stack frame just selected frame n Select frame number n Recall that frame zero is the innermost currently execut ing frame frame one is the frame that called the innermost one and so on The highest numbered frame is main s frame frame addr Select the frame at address addr This is useful mainly if the chaining of stack frames has been damaged by a bug making it impossible for GDB to assign num IEEE MOTOROLA DSP56KCC User s Manual E 39 bers properly to all frames In addition this can be useful when the program has multiple stacks and switches between them up n Select the frame n frames up from the frame previously selected For positive numbers n this advances toward the outermost frame to higher frame numbers to frames that have existed longer n defaults to one down n Select the frame n frames down from the frame previously selected For positive numbers n this advances toward the innermost frame to lower frame numbers to frames that were created more re
216. ection of an array or an array of dynamically determined size for which only a pointer exists in the program This can be done by constructing an artificial array with the binary operator The left operand of should be the first element of the desired array as an individual object The right operand should be the length of the array The result is an array value whose el ements are all of the type of the left argument The first element is actually the left argu ment the second element comes from bytes of memory immediately following those that hold the first element and so on Here is an example If a program says ICE E 48 DSP56KCC User s Manual MOTOROLA int array int malloc len sizeof int you can print the contents of array with p array len The left operand of O must reside in memory Array values made with in this way behave just like other arrays in terms of subscripting and are coerced to pointers when used in expressions It would probably appear in an expression via the value history af ter you had printed it out 3 23 Format options GDB provides a few ways to control how arrays and structures are printed info format Display the current settings for the format options set array max number of elements If GDB is printing a large array it will stop printing after it has printed the number of elements set by the set array max command This limit also applies to the di
217. ed nop move r6 n6 restore it 5 4 5 Optimization Techniques The general template for out of line assembly code provides a clean template to build C callable functions However the DSP56000 family microprocessor chips have powerful features such as multiple instruction execution multiply and accumulate and parallel data move operations that may allow additional optimization After constructing the out _ ________ E 1111 MOTOROLA DSP56KCC User s Manual 5 35 of line assembly code from the general template some hand optimization can be per formed by combining several assembly statements Information about these optimization techniques can be obtained from the DSP56000 DSP56001 User s Manual Some optimization techniques which are related to the C compiler are discussed in this section but additional optimization can be achieved using the architectural features described in the user s manual The RO register which is updated by the out of line assembly code template prologue is required only when parameters are passed to the C function If there are no parameters to be passed then the following two assembly code lines are not required and can be omitted move r0 y r6 lua r5 r0 The return address SSH was saved in the out of line assembly code prologue but it is only required when a C function calls another C function A C function is called a leaf function if it does not call any other C function
218. ed except for the A accumulator which contains the result The two routines that do not restore the registers are F uldiv and F ulmod which use the registers according the C standard shown in Table 4 9 4 10 Run time Safety DSP56KCC provides two methods for providing run time memory utilization checks The first method memory allocation check is automatic The second method run time stack probes is provided by selecting the command line argument mstack check 4 10 1 Memory Allocation Checks Memory allocation checks are provided during every call to the run time library routines malloc calloc and realloc This automatic run time check determines when the heap is about to collide with the run time stack When this occurs the library routine returns a NULL pointer and sets the global variable errno to ENOMEM _ ___ __ _ __ _ _ gt E gt gt ____ _ _ _ A 4 14 DSP56KCC User s Manual MOTOROLA 4 10 2 Run time Stack Checks If the programmer does not use malloc calloc or realloc there is no automatic run time collision check A tool is provided to allow the programmer to check the code during debugging to see if a stack collision is likely to occur when the code is executing normally By selecting the mstack check option on the command line the compiler is instructed to generate extra code to watch the stack and heap and detect when the run time stack is about to collide with the
219. ehavior is undefined Size specifies the argument size expected There are three size specifiers defined by ANSI The h specifies that the argument for the conversion characters d i o u x or X will be unsigned short The specifies that the argument for the conversion characters d i O U X or X will be long integer The L specifies that the argument for the conversion characters e E f g or G will be long double There are 16 conversion characters each is described below d i The int argument is printed as a signed decimal number The precision specifies the minimum number of digits to appear if the value being printed can be represented in fewer digits it is expanded with leading zeros The default precision is 1 The result of printing a zero with precision zero is no characters this is independent of padding specified by field width O The unsigned int argument is printed as an unsigned octal number When used in association with the flag 0 will be prefixed to non zero results The precision specifies the minimum number of digits to appear if the value can be represented in fewer digits it will be expanded with leading zeros The default precision is 1 The result of printing a zero with precision zero is no characters this is independent of padding specified by field width Ye _ _ AAA MOTOROLA DSP56KCC User s Manual A 93 printf printf u The unsigned int argument is printed as an unsigned decimal number The
220. ely The pseudo operands are used as in the OES 960 961 962 3 and 964 Table 5 3 shows which operands in Example 5 3 are input or output operands Example 5 3 Instruction template with operand_id In order to illustrate how to use output or input operands pseudo operands V W X Y and Z are used The operand id listed in this example can be used as part of an instruction template asm instruction template V W X Y Z Examples 5 3 through Example 5 12 illustrate the use of OES modifier see Section 5 2 1 Table 5 3 Output and Input Operands for Example 5 3 operand id pseudo operand operand type OES 0 V output 0 1 W output 961 2 X output 962 3 Y input 963 4 Z input 964 Example 5 4 OES modifier j The following in line assembly code is used to generate executable assembly code Notice that the actual register selection is totally dependent on the C compiler but the register selected r3 in this example is guaranteed to be related to the C expression used in this case cptr see Section 5 2 In line Assembly code IL M E E MOTOROLA DSP56KCC User s Manual 5 9 char cptr __asm move 0 j0 A cptr Assembly Code Generated move r3 n3 Example 5 5 OES modifier e The modifier e can be used to generate the assembly code below because a1 is the upper part of register A In line
221. em include options for handling separate memory spaces stack initialization chip operating modes and other issues The purpose of this manual is to 1 provide detailed installation procedures for both UNIX based systems and MS DOS based systems This manual explains how to install and operate the DSP56KCC ANSI C compiler development system in a hosted environment 2 provide an overview of the compiler operation It also includes information on combining C modules with assembly language programs and advanced topics pertaining to compiler run time characteristics 3 provide reference information on compiler options ANSI library routines and utilities This manual assumes a familiarity with the C programming language with the host machine and operating system environment lt also assumes that the programmer understands how to create and edit C language source files on this host system For more information on the C language and other DSP56000 1 development tools see the references listed in Appendix D 1 2 Error Codes The error messages generated by the compiler are intended to be complete without additional explanation Since the compiler produces a detailed description of the problem rather than an error code these error messages have not been reproduced in this manual 1 3 Notation The following notation will be used in this text 1 A prompt is indicated in this manual by CENS 2 An example of an MS DOS directory name is
222. emcmp amp g1 amp g3 sizeof struct test 0 printf flintstones are not jetsons n else printf error flintstones are NOT jetsons n prints to standard output flintstones are flintstones flintstones are not jetsons ee A AA A AAA A 84 DSP56KCC User s Manual MOTOROLA memcpy memcpy NAME memcpy Copy from one area to another SYNOPSIS include lt string h gt int memcpy void s1 const void s2 size tn DESCRIPTION The memcpy function copies n words from the area referenced by s2 into the area specified by s1 If the source and destination areas overlap the results are undefined The memopy function returns the value of s1 SEE ALSO strcpy Copy one string to another strncpy Copy a portion of one string to another EXAMPLE include lt stdio h gt include lt string h gt struct test char cartoon 20 int value g1 g2 flintstones 709 void main memopy amp g1 amp g2 sizeof struct test printf watch the 96s n g1 cartoon prints to standard output watch the flintstones _ ___ A M OE MOTOROLA DSP56KCC User s Manual A 85 memmove memmove NAME memmove Copy storage SYNOPSIS include lt string h gt int memmove void s1 const void s2 size_tn DESCRIPTION The memmove function copies n words from the area referenced by s2 into the area specified by s1 The
223. endent optimizations 3 use trigraphs 4 locate data in the Y data memory space Bdirectory Add directory to the standard search list and have it searched first This can also be accomplished by defining the environment variable G56_EXEC_PREFIX Note that only one additional directory can be specified and that the B option will override the environment variable Example 3 1 To test a new version of the ANSI C library lib56cy clb which is installed as dsp new lib56cy clb use C gt g56k B dsp new file c o file cld Example 3 2 Using the G56_EXEC_PREFIX environment variable to have the same effect as Example 3 1 include in the cshrc or login files set G56 EXEC _PREFIX C DSP NEW and then execute C gt g56k ileso o tile eld Example 3 3 To test a new version of the DSP56000 1 C preprocessor before permanent installation install a new mcpp program as c tmp new mcpp and then execute C gt g56k Be tmp new testfile c bPREFIX Direct g56k to search for compilation phases start up files and libraries whose names are prefixed with the word PREFIX Note that only one additional prefix can be specified This is very similar to the B option Example 3 4 Test a new version of the ANSI C library lib56cy clb installed as c dsp lib new lib56cy clb C gt g56k bnew file c o filescla Example 3 5 Test a new version of the DSP56KCC preprocessor before permanent installation install the new mcpp pro
224. er a If the return value is larger than 32 bits then the compiler allocates the proper amount of buffer space and register al becomes the pointer to this buffer space upon callee execution It is the callee s responsibility to copy any return values from the buffer whose address resides in register a1 This is the method used for returning structs 5 4 1 5 Epilogue The out of line template epilogue is the reverse of the prologue The epilogue restores the return address and updates the frame pointer RO Notice that the stack pointer R6 should be decremented before each move operation In addition register A is tested to update the SR register This testing is a part of the C compiler code generation feature and should be included see Section 5 4 5 for optimization _ z gt _ gt gt MOTOROLA DSP56KCC User s Manual 5 27 5 4 1 6 Out of line Assembly Code Example The following example illustrates using the general template as well as the fact that the DSP56000 DSP56001 performs fractional arithmetic Assume that section mod1 con tains two C callable subroutines mac01 and mac02 and section mod2 contains a single C callable subroutine mactwo The two functions mac01 and mac02 take one argument each and mactwo takes two arguments These functions perform multiplica tion according to the following formulas and return their results
225. er goes off which happens only if the program has requested an alarm Some signals including SIGALRM are a normal part of the functioning of the program Others such as SIGSEGV indicate errors these signals are fatal kill the program imme diately if the program has not specified in advance some other way to handle the signal SIGINT does not indicate an error in the program but it is normally fatal so it can carry out the purpose of Ctrl c to kill the program GDB has the ability to detect any occurrence of a signal in the program running under GDB s control You can tell GDB in advance what to do for each kind of signal Normally GDB is set up to ignore non erroneous signals like SIGALRM so as not to in terfere with their role in the functioning of the program but to stop the program immedi ately whenever an error signal happens You can change these settings with the handle command You must specify which signal you are talking about with its number info signal Print a table of all the kinds of signals and how GDB has been told to handle each one You can use this to see the signal numbers of all the defined types of signals handle signalnum keywords Change the way GDB handles signal signalnum The keywords say what change gt ___ _ __ _ __ _ MOTOROLA DSP56KCC User s Manual E 25 to make To use the handle command you must know the code number of the signal you are
226. er to the current stack frame and ps is used for a register that contains the processor status These standard register names may be available on your machine even though the info registers command displays them with a different name For example on the SPARC info registers displays the processor status register as psr but you can also refer to it as ps GDB always considers the contents of an ordinary register as an integer when the regis ter is examined in this way Some machines have special registers which can hold noth ing but floating point these registers are considered floating point There is no way to refer to the contents of an ordinary register as floating point value although you can print it as a floating point value with print f regname Some registers have distinct raw and virtual data formats This means that the data format in which the register contents are saved by the operating system is not the same one that your program normally sees For example the registers of the 68881 floating point coprocessor are always saved in extended format but all C programs expect to work with double format In such cases GDB normally works with the virtual format only the format that makes sense for your program but the info registers command prints the data in both formats Register values are relative to the selected stack frame see section Selection This means that you get the value that th
227. erpretation is described in Section 5 2 1 2 output operands are optional operands used to provide specific output informa tion to the compiler Each output operand string is separated by a comma and should begin with the character As an example the output operand A cp tr means the C variable cptr will get its value from this output operand which will be in an address register See Section 5 2 2 for more details 3 input operands are optional operands to provide specific input information to the compiler Each input operand is separated by a comma and may include a C vari able As an example the input operand A cptr means the value of this input operand will be taken from the C variable cptr and placed in an address register Again full descriptions of the input and output operands can be found in Section 5 2 2 4 reg save specifies registers that are to be explicitly reserved for the _ _asm statement The registers to be saved must be named as strings such as a and b Each register is separated by a comma see Section 5 2 3 for additional infor mation The compiler assumes that all data residing in the reg_save registers will be invalidated by the asm statement EES 5 2 DSP56KCC User s Manual MOTOROLA 5 2 1 Instruction Template The first argument of the __asm extension is the instruction template or assembler in struction template This instruction template is mandatory and d
228. es fftr2d hlp Help for fftr2d asm 3457 fftr2dt asm 1 0 Test program for fftr2d asm 1287 fftr2dt hlp Help for fftr2dt asm 614 fftr2e asm 1 0 1024 Point Non In Place FFT 3 39ms 8976 fftr2e hlp Help for fftr2e asm 5011 fftr2et asm 1 0 Test program for fftr2e asm 984 fftr2et hlp Help for fftr2et asm 408 dct1 asm 1 1 Discrete Cosine Transform using FFT 5493 dct1 hlp 1 1 Help file for dct1 asm 970 fftr2cc asm 1 0 Radix 2 In place Decimation in time 6524 complex FFT macro fftr2cc hlp 1 0 Help file for fftr2cc asm 3533 fftr2cn asm 1 0 Radix 2 Decimation in time Complex FFT 6584 macro with normally ordered input output fftr2cn hlp 1 0 Help file for fftr2cn asm 2468 fftr2en asm 1 0 1024 point not in place complex FFT 9723 macro with normally ordered input output fftr2en hlp 1 0 Help file for fftr2en asm 4886 u MOTOROLA D 7 Document ID Version Synopsis Size dhit1 asm 1 0 Routine to compute Hilbert transform 1851 in the frequency domain dhit1 hlp 1 0 Help file for dhit1 asm 1007 fftr2bf asm 1 0 Radix 2 decimation in time FFT with 13526 block floating point fftr2bf hlp 1 0 Help file for fftr2bf asm 1578 fftr2aa asm 1 0 FFT program for automatic scaling 3172 Filters fir asm 1 0 Direct Form FIR Filter 545 fir hlp Help for fir asm 2161 firt asm 1 0 Test program for fir asm 1164 lirt asm 1 0 Direct Form Second Order All Pole 656 IIR Filter iirt h
229. escribes the line or lines of assembly language to be placed into the compiler s assembly language output see Example 5 2 in Section 5 2 4 This template is not parsed for assembly language syntax violations and is simply written to the compiler output As a result the compiler will not detect assembly time errors These errors will be caught by the assembler More than one assembly instruction can be put into a single instruction template by using the line separator n The line separator or newline can be utilized as in a normal C statement The line continuation sequence a V followed by an immediate newline is par ticularly useful when an instruction template contains an assembly instruction that is too long to fit in one source line see Example 5 18 and Example 5 19 in Section 5 2 4 Oth er C language character constants such as t f etc can also be used in the instruction template In many situations it is desirable to use the values of C variables and or expressions di rectly in the instruction template Since all memory and register accesses are accom plished through variables manipulating memory and registers directly using assembly code requires knowledge of their locations Without optimizations the current value of a variable will be maintained in memory at a specific address However an optimizing C compiler such as DSP56KCC may retain a variable in a register and perform operations on that variable w
230. eside in another file The two assembly subroutines ReadX and Ready are written using the out of line assembly technique described in Section 5 4 The listings for ReadX and ReadY are shown in Example 5 38 in Section 5 4 5 By using the statement extern int ValOfX _ _asm ReadX ValOfY __asm ReadY all C compiler generated function labels for ValOfX and ValOfY are replaced by the la bels ReadX and Ready respectively Example 5 24 Calling assembly from C This C program called test c can be used to examine the data in x or y memory by calling assembly routines ReadX or ReadY Notice that the assembly code for ReadX and ReadY is listed in Example 5 38 of Section 5 4 5 C gt type test c ILr 1 5 16 DSP56KCC User s Manual MOTOROLA include lt stdio h gt extern int ValOfX __asm ReadX ValOfY asm ReadY unsigned Y 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 main printf lt x gt lt x gt n ValOfX 100 ValOfY Y 2 The following two command lines test Example 5 24 C gt g56k test c memread asm C gt run56 a cld 5 2 5 2 Calling C Subroutines from Assembly Code Any C program can be called from an assembly program to test the assembly program data or utilize built in standard C libraries such as floating point operations Calling a C subroutine from assembly code re
231. essages telling you that the symbol table details for a particular source file are being read The set verbose command controls whether these messages are printed see section User Inter face However you will sometimes see in backtraces lines for functions in source files whose data has not been read in these lines omit some of the information such as argument values which cannot be printed without full details of the symbol ta ble When the symbol table is stored in COFF format symbol file does read the sym bol table data in full right away We haven t bothered to implement the two stage strategy for COFF core file filename Specify the whereabouts of a core dump file to be used as the contents of memo ry Note that the core dump contains only the writable parts of memory the read only parts must come from the executable file core file with no argument specifies that no core file is to be used Note that the core file is ignored when your program is actually running under GDB So if you have been running the program and you wish to debug a core file instead you must kill the sub process in which the program is running To do this use the kill command see section Kill Process add file filename address The add file command reads additional symbol table information from the file filename You would use this when that file has been dy namically loaded into the program that is running
232. eturn address is saved when the JSR instruction pushes the hardware stack which saves the program counter in the high 16 bits of the system stack i e SSH This section of the prologue provides bookkeeping for the C com piler activation record Detailed information on the structure of the activation record can be found in Section 4 6 1 After this prologue the RO register is the frame pointer and R6 is the stack pointer 5 4 1 2 Save all registers All registers used in the main program should be saved before the main program chang es them This step is the second element of the template Save all registers to be used In order to save the registers R6 is used as a stack pointer The stack grows upward and the current stack pointer R6 points to the next element above the top of stack The fol lowing statement saves one register to the top of stack and sets the stack pointer to the next available stack location move x0 y r6 Two registers y1 and x1 can be saved with the following statements move y1 y r6 move x1 y r6 Since saving and restoring the registers are the subroutine s responsibility the order of saving the registers should be in accordance with their restoration The restore process should be exactly the reverse order of the register saving sequence 5 4 1 3 Main Program The main C function program accesses the parameters passed executes the operations on the parameters and returns a value Passing par
233. ew to the field of DSP This is a partial list of DSP references intended to help the new user find useful information in some of the many areas of DSP applications Many books could be included in several categories but are not repeated EES D 14 DSP56KCC User s Manual MOTOROLA General DSP ADVANCED TOPICS IN SIGNAL PROCESSING Jae S Lim and Alan V Oppenheim Englewood Cliffs NJ Prentice Hall Inc 1988 APPLICATIONS OF DIGITAL SIGNAL PROCESSING A V Oppenheim Englewood Cliffs NJ Prentice Hall Inc 1978 DISCRETE TIME SIGNAL PROCESSING A V Oppenheim and R W Schafer Englewood Cliffs NJ Prentice Hall Inc 1989 DIGITAL PROCESSING OF SIGNALS THEORY AND PRACTICE Maurice Bellanger New York NY John Wiley and Sons 1984 DIGITAL SIGNAL PROCESSING Alan V Oppenheim and Ronald W Schafer Englewood Cliffs NJ Prentice Hall Inc 1975 DIGITAL SIGNAL PROCESSING A SYSTEM DESIGN APPROACH David J DeFatta Joseph G Lucas and William S Hodgkiss New York NY John Wiley and Sons 1988 FOUNDATIONS OF DIGITAL SIGNAL PROCESSING AND DATA ANALYSIS J A Cadzow New York NY MacMillan Publishing Company 1987 HANDBOOK OF DIGITAL SIGNAL PROCESSING D F Elliott San Diego CA Academic Press Inc 1987 INTRODUCTION TO DIGITAL SIGNAL PROCESSING John G Proakis and Dimitris G Manolakis New York NY Macmillan Publishing Company 1988 MULTIRATE DIGITAL SIGNAL PROCESSING R E Crochiere and L R Rabiner Englewood Cliffs
234. exadecimal digit zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if isxdigit F printf F hexadecimal character n if isxdigit G printf G not a hexadecimal character n prints to standard output F hexadecimal character G not a hexadecimal character ee A 66 DSP56KCC User s Manual MOTOROLA labs labs NAME labs Absolute value of a long integer SYNOPSIS include lt stdlib h gt long int labs long int j DESCRIPTION The labs function returns the absolute value of the long integer j SEE ALSO abs Absolute value of an integer EXAMPLE include lt stdio h gt include lt stdlib h gt void main long int j 19089709l printf labs 190897091 ld n labs j prints to standard output labs 190897091 19089709 AAA A A A A A U EE MOTOROLA DSP56KCC User s Manual A 67 Idexp Idexp NAME Idexp Multiply floating point number by 2 SYNOPSIS include lt math h gt double Idexp double x int exp DESCRIPTION The Idexp function returns x 2 amp f the result exceeds HUGE VAL errno is set to ERANGE and the value HUGE VAL is returned with the
235. exhausted AAA AAA A A A A A U OEA MOTOROLA DSP56KCC User s Manual A 33 fgetpos fgetpos NAME fgetpos Get the value of the file position indicator associated with a stream SYNOPSIS include lt stdio h gt int fgetpos FILE stream fpos_t pos DESCRIPTION The function fgetpos fetches the value of the file position indicator associated with stream and stores it in the object pointed to by pos fgetpos returns zero if it was successful The value of the file position indicator is meaningless except as an argument to the function fsetpos SEE ALSO fopen Open a file on the host s disk and associate it with a stream fseek Used to alter the file position indicator associated with a stream fsetpos Set the value of the file position indicator associated with a stream EXAMPLE include lt stdio h gt void main FILE preexisting fopen already here r fpos_t pos void fgetpos preexisting amp pos void fseek preexisting OL SEEK_END void fsetpos preexisting amp pos will open a hypothetical pre existing file on the disk record the initial position in pos seek to the end of the file and finally restore the initial value of the file position indicator __ ___ ___ _ _ ___ __ gt E gt A M 1 A 34 DSP56KCC User s Manual MOTOROLA fgets fgets NAME fgets Read a string from the specified stream SYNOPSIS include lt stdi
236. f X1 and yO move y r6 n0 restore register nO move y r6 yO restore register YO move y r6 x1 restore register X1 move y r6 ssh epilogue move y r6 r0 tst a rts endsec section mod2 int mactwo int arg1 int arg2 takes two fractional arguments and returns arg1 arg2 r w X X O 5 30 DSP56KCC User s Manual MOTOROLA section mod2 global Fmactwo Fmactwo move r0 y r6 prologue lua r6 r0 move ssh y r6 move x1 y r6 save register X1 move yO y r6 X save register YO move nO y r6 X save register nO move 3 n0 move y r0 n0 x1 the first argument move 4 n0 move y r0 n0 y0 the second argument clr a macr x1 y0 a main program calculates multiplication of x1 and yO move y r6 n0 restore register nO move y r6 yO restore register YO move y r6 x1 restore register X1 move y r6 ssh epilogue move y r6 r0 tst a rts endsec The DSP56KCC control program g56k should be used to assemble the out of line as sembly code The two sections of this code mod1 and mod2 can be put in the same file or in separate files The following command lines and source files provide a test for the case where each program is in a separate file C type main c rn O MOTOROLA DSP56KCC User s Manual 5 31 include lt stdio h gt int mac01 int macO2 int mactwo int int
237. f struct test random check if local cartoon 7 9 printf error memset busted n printf memset OK n prints to standard output memset OK r A A O A 88 DSP56KCC User s Manual MOTOROLA modf modf NAME modf Break a double into it s integral and fractional parts SYNOPSIS include lt math h gt double modf double value double iptr DESCRIPTION The modf function brakes value into its fractional and integral parts The modf function returns the fractional portion of value and stores the integral portion in the double object pointed to by iptr SEE ALSO frexp Break a double into its mantissa and exponent EXAMPLE include lt stdio h gt include lt math h gt void main double result printf fractional f t modf 7 09 amp result printf integral f n result prints to standard output fractional 0 090000 integral 7 000000 AAA A A AA A A UM EA MOTOROLA DSP56KCC User s Manual A 89 perror perror NAME perror Print error message SYNOPSIS include lt stdio h gt void perror const char s DESCRIPTION The perror function prints out the string s followed by and the error message associated with errno SEE ALSO strerror Print out error message associated with errno EXAMPLE include lt stdio h gt include lt math h gt void main double res
238. fabs Absolute value of a double SYNOPSIS include lt math h gt double fabs double x DESCRIPTION The fabs function computes and returns the absolute value of double x When the header file math h is included the default case will be in line see section A 3 Forcing Library Routines Out of line SEE ALSO abs Absolute value of an integer labs Absolute value of a long integer EXAMPLE include lt stdio h gt include lt math h gt void main double pos neg 7 09 pos fabs neg printf absolute value of d d n neg pos prints to standard output absolute value of 7 090000 7 090000 r r O d O A 28 DSP56KCC User s Manual MOTOROLA fclose fclose NAME fclose Close a stream SYNOPSIS include lt stdio h gt int fclose FILE DESCRIPTION The function fclose flushes all output on the specified stream and disassociates the stream from the file on the host The function fclose returns EOF if there are any problems otherwise 0 SEE ALSO fprintf Used to write formatted output to a stream EXAMPLE include lt stdio h gt void main fprintf stdout see me second fprintf stderr see me firstin fclose stdout prints to combined standard error and standard output see me first see me second Note that stdout is by default line buffered while stderr is not T
239. fore count steps stepping stops right away next Similar to step but any function calls appearing within the line of code are exe cuted without stopping Execution stops when control reaches a different line of code at the stack level which was executing when the next command was given This command is abbreviated n An argument is a repeat count as in step next within a function without debugging information acts as does step but any function calls appearing within the code of the function are executed without stop ping finish Continue running until just after the selected stack frame returns or until there is some other reason to stop such as a fatal signal or a breakpoint Print value re turned by the selected stack frame if any Contrast this with the return command see section Returning until This command is used to avoid single stepping through a loop more than once It is like the next command except that when until encounters a jump it automati cally continues execution until the program counter is greater than the address of the jump This means that when you reach the end of a loop after single stepping though it until will cause the program to continue execution until the loop is exited In con trast a next command at the end of a loop will simply step back to the beginning of the loop which would force you to step through the next itera
240. form the actions requested by the DSP The I O code is writ ten as an event driven state machine so that the host side application can perform con currently with the DSP when the DSP is not requesting I O activity In fact the I O driver on the host may be interrupt driven The host side driver consists of the code in dsp etc hostio h and dsp etc hostio c The meat of the package consists of two functions init host io structures and process pending host io and two buffers hio send and hio receive The function init host io structures is called to initialize host side driver data structures before DSP execution is commenced The buffer hio send is used to send messages to the DSP and hio receive is used to receive messages from the DSP The function process pending host io considers the current state of the buffers and its own inter nal state and then performs any required buffer modification or host l O 6 6 3 Communication between the Host and DSP The messages passed between the DSP and the host s I O driver are defined in the file dsp include ioprim h All sequences of communication are initiated by the DSP as a di rect result of a call to a standard I O function Each standard I O call may initiate a series of messages between the DSP and the host with the host eventually returning a message containing the completion status of the original request The file dsp include ioprim h is included by both the host side I O driver and
241. formats and a special section naming format These six separate formats simplify the procedures to combine hand written assembly language and C language statements Use of these formats also makes compiler generated assembly language listings easier to read It is strongly recommended that the programmer avoid using labels with these formats L Local labels Generally the targets of conditional and unconditional jumps Where is a decimal digit LC String Constant labels The data memory location for C string constants such as string constant F lt identifier gt Global C variables global subroutines static C variables and static subroutines A static C variable or subroutine is one which is not visible to any C code outside the file in which it has been declared thus making it possible to reuse variable names across file boundaries Where identifier is the variable or subroutine name F identifier 4 X Variables static to a function ASM APP In line assembly code delimiters Required to allow the programmer to define and use local labels labels beginning with an underscore character _ lt filename_c gt Section names The contents of each assembly language file generated by the compiler are contained in a unique section Where filename is the file name minus any extensions 4 8 Subroutine Call Sequence Each time a C language subroutine is called a strict calling convention is followed The subroutine cal
242. four different states of enablement Enabled The breakpoint will stop the program A breakpoint made with the break command starts out in this state Disabled The breakpoint has no effect on the program Enabled once The breakpoint will stop the program but when it does so it will become disabled A breakpoint made with the toreak command starts out in this state I C H 9 M 1 MOTOROLA DSP56KCC User s Manual E 29 Enabled for deletion The breakpoint will stop the program but immediately af ter it does so it will be deleted permanently You change the state of enablement of a breakpoint with the following commands disable breakpoints bnums disable bnums Disable the specified breakpoints A disabled breakpoint has no effect but is not forgotten All options such as ignore counts conditions and commands are re membered in case the breakpoint is enabled again later enable breakpoints bnums enable bnums Enable the specified breakpoints They become effective once again in stopping the program until you specify otherwise enable breakpoints once bnums enable once bnums Enable the specified breakpoints temporarily Each will be disabled again the next time it stops the program unless you have used one of these commands to spec ify a different state before that time comes enable breakpoints delete bnums enable delete
243. g is normally gdb You can change the prompt string with the set prompt command For instance when debugging GDB with GDB it is useful to change the prompt in one of the GDBs so that you tell which one you are talking to u MOTOROLA DSP56KCC User s Manual E 11 set prompt newprompt Directs GDB to use newprompt as its prompt string henceforth To exit GDB use the quit command abbreviated q Ctrl c will not exit from GDB but rather will terminate the action of any GDB command that is in progress and return to GDB command level lt is safe to type Ctrl c at any time because GDB does not allow it to take effect until a time when it is safe Certain commands to GDB may produce large amounts of information output to the screen To help you read all of it GDB pauses and asks you for input at the end of each page of output Type RET when you want to continue the output Nor mally GDB knows the size of the screen from on the termcap data base together with the value of the TERM environment variable if this is not correct you can override it with the set screensize command set screensize lpp set screensize Ipp cpl Specify a screen height of Ipp lines and optionally a width of cpl characters If you omit cpl the width does not change If you specify a height of zero lines GDB will not pause during output no matter how long the output is
244. g pointed to by s1 The first character of the second string is written over the first strings terminating character The strcat function returns a pointer to 1 SEE ALSO strncat Concatenate n characters from one string to another EXAMPLE include lt stdio h gt include lt string h gt void main char bigstr 80 string 1 char smallstr 20 string 2 printf concatinate s and s n bigstr smallstr void strcat bigstr smallstr puts bigstr prints to standard output concatinate string 1 and string 2 string 1 string 2 AAA AAA A A A A A A A A A A A A OE MOTOROLA DSP56KCC User s Manual A 123 strchr strchr NAME strchr Find first occurrence of a character in a string SYNOPSIS include lt string h gt char strchr const char s int c DESCRIPTION The strchr function locates the first occurrence of c converted to a char in the string pointed to by s The terminating null character is considered part of the string The strchr function returns a pointer to the located character or a null pointer if the character is not found in the string SEE ALSO memchr Find a character in a memory area strcspn Compute the length of the prefix of a string not containing any characters contained in another string strpbrk Find the first occurrence of a character from one string in another string strrchr Find the last occurrence of a character in a string strspn
245. gates the result A classic example of a CSE is the array element assignment from another array array_1 index 1 array_2 index 1 where the expression index 1 is the CSE This optimization is especially effective as CSEs become candidates for register promotion 4 11 3 Constant Propagation Folding Propagation of constants is detected during data flow analysis and is simply the a ee MOTOROLA DSP56KCC User s Manual 4 15 replacement of variable references with constant references when possible For example a 3 block of C code with no references to a func_call a 709 becomes block of C code func_call 3 709 Constant folding is the replacement of run time computations with compile time computations This optimization works well with constant propagation as it exposes many new opportunities for folding The example above would be further transformed to block of C code func_call 712 4 11 4 Dead Code Elimination During data flow analysis the compiler detects when the results of C expressions are never used When this is detected the offending C statements are eliminated from code generation This includes 1 the initialization of variables that are not referenced in the subroutine and 2 the situation where the variables next reference is not an assignment To guarantee code generation a volatile type specifier can be used to declare the left side of the expression main
246. gram asc dsp bin new mcpp and C gt g56k bnew testfile c a JJJFF SOKXOXANmaeoerqqqqoOmommqooStqoH SSS 3 4 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options 0 FILE Select FILE as the output file This applies to all phases of the compiler When the o flag is not in use the following file names are used by the compiler as the default output file names depending upon the compile options as follows E preprocess only stdout S compile only foo asm c no linkage foo cln complete process a cld where stdout is standard output and prints to the console Example 3 6 Only generate a preprocessed file do not invoke the compiler assembler or linker and put the results in file i CoN gt Oak E filee 0 flle Example 3 7 Compile file c and generate the executable output file fft cld If an output name is not given the default file name is a cld C gt g56k file co o fft cld V Verbose mode The compiler control program announces to stderr all commands that it attempts to execute for each phase of the compilation process This com mand is also used by the preprocessor to print the software version information If the E option is selected v will only enable the verbose mode otherwise it will en able the verbose mode and print the version information 3 2 1 Preprocessor Phase Options The options listed below control the C preprocessor which is run on each C source file before actual c
247. gt void main FILE booty fopen professor r char buffer 64 fread buffer 63 sizeof char booty fprintf stdout buffer and will cause the following output to be printed to standard output What s another word for pirate treasure _ __ ______ gt gt _ AAA AAA MOTOROLA DSP56KCC User s Manual A 43 free free NAME free Free storage allocated by calloc malloc and realloc SYNOPSIS include lt stdlib h gt void free void ptr DESCRIPTION The free function causes the space pointed to by ptr to be deallocated Once deallocated it is available to be used again by future dynamic memory allocation requests If ptr is NULL free returns immediately If the space pointed to by ptr has already been deallocated by a previous call to free or realloc the behavior is undefined SEE ALSO alloca Allocate storage in the stack frame calloc Dynamically allocate zero initialized storage malloc Dynamically allocate uninitialized storage realloc Alter size of previously dynamically allocated storage EXAMPLE include lt stdio h gt include lt stdlib h gt void main char alloc if alloc 2 char malloc 709 NULL printf malloc error n exit 1 free 709 words of memory free alloc Ce A 44 DSP56KCC User s Manual MOTOROLA freopen freopen NAME freopen Open a named file on the disk to be ac
248. h function searches an array on nmemb objects the initial element of which is pointed to by base for an element that matches the object pointed to by key The size of each element is specified by size The contents of the array must be in ascending order according to a user supplied comparison function compare The compare function is called with two arguments that must point to the key object and to an array member in that order Also compare must return an integer that is less than equal to or greater than zero for the key object to be respectively considered less than equal to or greater than the array element SEE ALSO qsort Perform quick sort AAA A A AAA A M MOTOROLA DSP56KCC User s Manual A 17 bsearch bsearch EXAMPLE include lt stdio h gt include lt stdlib h gt char stuff 6 bald driving feet flintstone fred on int compare const void key const void aelement return stremp char key char aelement void main char p char key bald p bsearch amp key stuff 6 sizeof char compare if p printf YES fred flintstone drives on bald feet n else printf NO sam the butcher brings alice the meat n prints to standard output YES fred flintstone drives on bald feet eS A A AAA A 18 DSP56KCC User s Manual MOTOROLA calloc calloc NAME calloc Dynamically allocate zero initialized storage for objects SYNOPS
249. he assembler will EES MOTOROLA DSP56KCC User s Manual C 5 asm56000 asm56000 show the beginning of each pass and when files are opened and closed The information is sent to the standard error output stream eeaeee e O C 6 DSP56KCC User s Manual MOTOROLA cldinfo cldinfo NAME cldinfo Memory size information from Motorola DSP COFF object file SYNOPSIS cldinfo file DESCRIPTION cldinfo is a utility that reads an absolute or relocatable Common Object File Format COFF file and produces a formatted display of the program memory size data memory size and the programs starting address file is an operating system compatible file name Only a single file name may be supplied and it must be explicit there is no default extension for the input file A _ EEK lt A A A M oO MOTOROLA DSP56KCC User s Manual C 7 cldlod cldlod NAME cldlod Motorola COFF to LOD Format converter SYNOPSIS cldlod cldfile gt lodfile DESCRIPTION cldlod is a utility that converts a binary COFF object file into an ascii LOD file cldfile is an operating system compatible file name which contains COFF information Only a single file name may be supplied and it must be explic it there is no default extension for the input file lodfile is an LOD file C 8 DSP56KCC User s Manual MOTOROLA cofdmp cofdmp NAME cofdmp Motorola DSP COFF File Dump Utility SYNOPSIS cofdmp cfhlorstv d file files DESCRIPTION
250. he call to fclose causes the pending output on stdout to be flushed eee l O MOTOROLA DSP56KCC User s Manual A 29 feof feof NAME feof Test the end of file indicator of a specified stream SYNOPSIS include lt stdio h gt int feof FILE DESCRIPTION The function feof function tests the end of file indicator associated with the specified stream It returns non zero if and only if the end of file indicator is set SEE ALSO fopen Used to associate a stream with a file on the host s disk fseek Used to alter the file position indicator associated with a stream fprintf Used to write formatted output to a stream EXAMPLE include lt stdio h gt void main FILE somefile fopen somefile rb void fseek somefile OL SEEK_END void fgetc somefile fprintf stdout are we at the file s end s n feof somefile yes no prints to standard output are we at the file s end yes e ae O A 30 DSP56KCC User s Manual MOTOROLA terror terror NAME ferror Test the error indicator of a stream SYNOPSIS include lt stdio h gt int ferror FILE DESCRIPTION The function ferror function tests the error indicator associated with the specified stream It returns non zero if and only if the error indicator is set ferror should be used following one or more stream I O function calls AAA A A AAA A A Mo MOTOROLA DSP56KCC User s Manual A 3
251. he object file describes the data type of each variable or function and the correspondence between source line numbers and addresses in the executable code To request debugging information specify the g option when you run the compiler The Unix C compiler is unable to handle the g and O options together This means that you cannot ask for optimization if you ask for debugger information The GNU C compiler supports g with or without O making it possible to debug opti mized code We recommend that you always use g whenever you compile a program You may think the program is correct but there s no sense in pushing your luck GDB no longer supports the debugging information produced by giving the GNU C com piler the gg option so do not use this option r H M MOTOROLA DSP56KCC User s Manual E 17 r MU E 18 DSP56KCC User s Manual MOTOROLA D 4 Running Your Program Under GDB To start your program under GDB use the run command The program must already have been specified using the exec file command or with an argument to GDB see sec tion Files what run does is create an inferior process load the program into it and set it in motion The execution of a program is affected by certain information it receives f
252. he output file V Output preprocessor version information The primary purpose of this command is a 3 16 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options to display the software version This information is needed when calling the Motoro la DSP helpline for assistance see Appendix D Additional Support for the hel pline phone number Although information pertaining to the internal flags and switch settings is included in this information it is not intended for use by the pro grammer and may be misleading This command is also used by the command pro gram to initiate the verbose mode of operation Example 3 19 The v option is selected using the control program g56k The version numbers for g56k mcpp and g56 cc1 are printed This information is showing the commands that the control program invokes along with the selected options In this case it is showing the default options plus the v option However the user should not invoke these programs independently but should always use the control program to invoke them CLAS Cis foo c EX g56k v 0046 g56k version Motorola Version g1 11 GNU 1 37 1 c dsp bin mcpp v undef D__Y_ MEMORY trigraphs D__STRICT_ANSI_ D DSP56K D__OPTIMIZE foo c cca00527 cpp GNU CPP version 1 37 1 c dsp bin g56 cc1 cca00527 cpp ansi fstrength reduce quiet dumpbase foo c O version o cca00527 asm GNU C version 1 37 1 Motorola DSP56000 1 Motorola Version
253. he proper techniques for manipulating the assembler s run time and load time counters while programming in the C language Currently the Motorola DSP assemblers allow the programmer to specify both a run time location and a load time location for any object however there is no corresponding concept within C The generic pragma facility is used to add this capability rather than extending the C language Users now have complete freedom in specifying both the run time and load time counters for any static or global object These directives may be used with either code or data This flexibility is achieved by allowing the user to modify any of eight counter strings maintained by the compiler two for each memory space x y and p When an object is or defined the current values of those counter strings are bound to that object Syntax for the pragma directive is pragma counter string argument C function or data storage definition pragma counter string L ess SSS MOTOROLA DSP56KCC User s Manual 5 21 where 1 the two pragma statements must encase the entire definition 2 counter string in the first Zpragma specifies which phase run or load time and memory space is to be affected It can be x run y run l run p run x load y load l load or p load The memory model used in the C compiler should match the memory model specified by counter string Note that the p run and p load counter strings will always have an effect
254. he same as the function printf except that an existing va_list is used in place of a series of arguments The macro va_start must have been invoked on the argument arg before the call to vprintf is made vprintf returns the number of characters printed On error vprintf returns a negative value SEE ALSO printf Write formatted output to standard output EXAMPLE include lt stdio h gt int printf const char format va_list ap int result va_start ap format result vprintf format ap va_end ap return result is essentially the library function printf r 04 A 156 DSP56KCC User s Manual MOTOROLA vsprintt vsprintf NAME vsprintf Write formatted output to a string using a va list SYNOPSIS include lt stdio h gt int vsprintf char s const char format va_list arg DESCRIPTION The function vsprintf is exactly the same as the function printf except that an existing va_list is used in place of a series of arguments The macro va_start must have been invoked on the argument arg before the call to vsprintf is made vsprintf returns the number of characters printed On error vsprintf returns a negative value SEE ALSO sprintf Write formatted output to a string EXAMPLE include lt stdio h gt int sprintf char s const char format va_list ap int result va_start ap format result v
255. ial audio model to Effect1 status MODEL 1 break case B set the special audio model to Effect2 status MODEL 2 break case C set the special audio model to Effect3 status MODEL 3 break case D set the special audio model to Effect4 status MODEL 4 break case E set the special audio model to Effect5 status MODEL 5 break case F loop 0 break eM UM E MOTOROLA DSP56KCC User s Manual F 21 default putc BEEP break set_lpf x Displays a menu of low pass filter specs cutoff and order and prompts the user for a selection of a new filter The pointer LPCOEFS is updated to point to the new filter coefficients void set lpf extern void cur pos extern void putstr extern int coef ptr extern int coef 3 coef 4 coef 5 coef 6 coef 7 extern int coef 8 coef band extern int status char filter int loop 1 while loop show menu lpf menu 7 2 cur pos 20 30 putstr Current LPF putstr lpf menu status FILTER filter prompt Select Low Pass Filter gt gt gt switch filter case A a test filter status FILTER 1 coef ptr _coef 3 break Case B 10 Hz Notch Filter status FILTER 2 coef ptr _coef 4 break case C 200 Hz Notch Filter status FILTER 3 coef ptr coef 5 break case D 707 Hz Notch Filter sta
256. ified stream until the input character is not a member of the set of characters comprising the directive Finally directives can be conversion specifications these directives begin with the character They describe how fscanf should parse input and how fscanf should synthesize a value to be stored in memory Conversion specifications are processed as follows First the stream is read until all white space characters have been exhausted unless or n is part of the conversion specification Second a value is derived from the input stream according to the conversion specifier A conversion specifier may be one of the following d match a signed decimal integer i match a signed integer whose base is determined in the same manner as a C integer constant to match an octal integer u match an unsigned decimal integer X match a signed hexadecimal integer X is also valid te Pg match a floating point number E F and G are also valid S match a sequence of non white space characters essentially scan a token string T match a non empty sequence of characters from a set of expected characters which are bounded by a following T MOTOROLA DSP56KCC User s Manual A 47 fscanf fscanf c match a sequence of characters as specified by the field width As a default scan only one character n don t ma
257. ign philosophy is to support concurrent access to these memory spaces to accelerate DSP operations The C programming lan guage does not support separate memory spaces but instead treats memory as a single _ _ _ ____ __ __ _ z z gt _____ _ _ _______ MOTOROLA DSP56KCC User s Manual 6 3 memory space As a result there is a difference between hardware memory organization and C memory utilization DSP56KCC provides three different memory models to minimize these differences They are the x memory model y memory model and memory model Selection of the appro priate memory model is made using the m option of the control program g56k see Sec tion 3 2 2 The memory configuration for each memory model is discussed later in this section The crto file can be modified to configure memory for any hardware design There are four data segments in the C programming environment These are the program segment global static data segment stack data segment and heap data segment The program segment is located in program memory The three data segments can be located in x memory y memory or memory space which is a concatenation of x and y memory depending on the memory model used TOP OF MEMORY X Y L ___break Heap Heap Heap Stack Pointer Stack t f __y_size Stack Stack DSIZE Global Static Global Static Global Static X MEMORY MODEL Y MEMORY MODEL L MEMO
258. ill cause GDB to stop it QRQRQ q q A AAA A A MOTOROLA DSP56KCC User s Manual E 33 When this happens you have three ways to proceed 1 Remove or disable the breakpoints then continue 2 Suspend GDB and copy the file containing the program to a new name Resume GDB and use the exec file command to specify that GDB should run the program under that name Then start the program again 3 Re link the program so that the text segment is non sharable using the linker op tion N The operating system limitation may not apply to non sharable executa bles 3 11 Continuing After your program stops most likely you will want it to run some more if the bug you are looking for has not happened yet cont Continue running the program at the place where it stopped If the program stopped at a breakpoint the place to continue running is the address of the breakpoint You might expect that continuing would just stop at the same breakpoint immediately In fact cont takes special care to prevent that from happening You do not need to delete the breakpoint to proceed through it after stopping at it You can however specify an ignore count for the breakpoint that the program stopped at by means of an argument to the cont command See section Conditions If the program stopped because of a signal other than SIGINT or SIGTRAP continuing will cause the program to see that signal You may not want this
259. inder gt 10 string i A remainder 10 hex digit A F else string i 0 remainder 0 9 x radix discard lowest digit if radix HEX string i add hex symbol else if neg string it or negative sign string i NUL terminate string with a NUL and back up to last character sl string reverse the string s2 string i leaving NUL at end while s1 lt s2 temp sl sltt s2 s2 temp return string pe eO O F 34 DSP56KCC User s Manual MOTOROLA io_ctype c bal The following function are modified versions of the functions from the ctype h file used by the G56K compiler isupper c char c return 0x40 lt int c amp amp Ox5b gt int c islower c char c 1 return 0x60 lt int c amp amp Ox7b gt int c isdigit c char c return 0x2f lt int c amp amp Ox3a gt int c iscntrl c char c return 0 Oxffffe0 int c Ox7f int c isgraph c char c return 0x20 lt int c amp amp Ox7f gt int c isprint c char c return Ox1f lt int c amp amp Ox7f gt int c isalpha c char c return isupper int c islower int c isalnum c char c return isalpha int c isdigit int c ispunct c
260. ing a va list vsprintf Write formatted output to a string using a va list wcstombs Convert wchar t array to multibyte string wctomb Convert wchar t character to multibyte character pe ae O A 6 DSP56KCC User s Manual MOTOROLA abort abort NAME abort Force abnormal program termination SYNOPSIS include lt stdlib h gt void abort void DESCRIPTION The abort function causes the program to terminate abnormally unless the signal SIGABRT is being caught and the signal handler does not return The unsuccessful termination value 1 is returned to the host environment gdb56 run56 The abort function will not return to its caller SEE ALSO exit Terminate a program normally signal Set up a signal handler EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf make abort call An abort printf this line not reached prints to standard output make abort call r A A A A A A A A OS MOTOROLA DSP56KCC User s Manual A 7 abs abs NAME abs Absolute value of integer SYNOPSIS include lt stdlib h gt int abs int j DESCRIPTION The abs function returns the absolute value of j When the header file stdlib h is included the default case will be in line see section A 3 Forcing Library Routines Out of line SEE ALSO fabs Absolute value of a double labs Absolute value of a long EXAMPLE inclu
261. ing h gt char strstr const char s1 const char s2 DESCRIPTION The strstr function locates the first occurrence of the string pointed to by s2 excluding the termination character in the string pointed to by s1 If the string s2 is found a pointer to it is returned If the string s2 is not found a null pointer is returned If s2 has a length of zero a pointer to 1 is returned EXAMPLE include lt stdio h gt include lt string h gt void main char string abcdef random characters ghijkl char fndstr 2 random char found if found strstr string fndstr NULL puts found else puts can t find the string prints to standard output random characters ghijkl i A 138 DSP56KCC User s Manual MOTOROLA strtod strtod NAME strtod String to double SYNOPSIS include lt stdlib h gt double strtod const char nptr char endptr DESCRIPTION The strtod function converts and returns the string pointed to by nptr to floating point number First strtod decomposes nptr into three sections 1 an initial possibly empty sequence of white space characters 2 a subject in the form of a floating point constant and 3 a final string of one or more unrecognized characters including the terminating null character of the input string If the first unrecognized character is not NULL a pointer to that character is stored into the object that endptr points to If the s
262. ings 3 29 Option Link serre aire Narn qTERSI d da 3 30 SU SIPING i hinana Grd Sehen need 3 31 ILIBRARY ciar add 3 31 T MAPPILE 24d 3 31 Option Preprocessor A od 3 6 DMACRO 3 7 DMACRO DEFN 3 8 TE 3 8 la o ea al 3 11 sHEIEE in 3 13 SIDIF s of ve PERI EE need 3 10 A a es 3 14 SMM utes tiun io de 3 14 gini reg c PN NEN 3 15 pro Gad Da opus 3 16 pedantic 3 16 UMACRO 4 2222 cun dilata 3 18 2 PM MET SUM 3 16 Wcomment 3 18 WtrigraphS 4 eec opi LES 3 19 out of line calling C routines 5 35 P P option A sm Eus ded 3 3 3 16 D lOHd 12s scene ai ek ae 5 22 PTUN rt A a 5 22 pedantic option 3 3 3 16 3 24 o A nf hak sds a toate ape A 90 POINTES cion 4 8 DOW arta rado Magen A 91 pragma pp D Irt 5 21 A eer de A 92 MOTOROLA G56KCC User s Manual Program Memory Configuration 4 10 o A adis ind Dia d jr A 98 DUIS sa speed ade A 99 Q Q option orto od eat tee ne 3 3 3 25 e hae ae eee A 100 R AA bam Show ome aes 3 3 3 31 POISE xe x rere eter eoe E 6 1 A 102 RANG cca oath A wee ea EE A 103 reallo6 5 5 dc nia de ears aces 6 8 A 104 Reserved exponents 4 6 A Er P 1 3 run56S M encore Rh 2 5 4 16 C 19 S A a etra a 3 3 3 25 setjmp 3 26 6 1 6 11 A 106 A 107 A 108 4t tik ridad A 110 SHOM A pedo ER ARI IRA UE 4 2 4 8 SIGER Ra tia n aut 6 11 SIGUEN sir es he
263. inning ftell stream char send void fread amp send sizeof char 1 stream putchar send fseek stream beginning SEEK SET void fread amp send sizeof char 1 stream putchar send will read and print the first character in the file file abc twice ftell is used to reset the file position indicator to the beginning of the file A O O AH gt MOTOROLA DSP56KCC User s Manual A 51 fwrite fwrite NAME fwrite Write data directly to a stream SYNOPSIS include lt stdio h gt size_t fwrite const void ptr size_t size size t nmemb FILE stream DESCRIPTION The function fwrite writes raw data to the specified stream The data is drawn from memory starting with the location pointed to by ptr The quantity of data is size nmemb fwrite returns the number of elements successfully written EXAMPLE include lt stdio h gt main char message hand me down pumas fwrite message sizeof char strlen message stdout will write the message hand me down pumas onto standard output pe eO O A 52 DSP56KCC User s Manual MOTOROLA getc getc NAME getc Read a character from the specified stream SYNOPSIS include lt stdout h gt int fgetc FILE stream DESCRIPTION getc is equivalent to fgetc except that getc may be implemented as a macro If such is the case the arg
264. io effects digital system A control 0x0000 0 wait states operation on port A init_port_C set up SCI and SSI init_port_B general purpose I O on port B init project set up for special audio effects List F 6 The list of main program F 14 DSP56KCC User s Manual MOTOROLA invoke main menu setscreen SPACE menu exit program putstr CRLF putstr EXITING PROGRAM putstr CRLF init_port_B il Initialize port B as a general purpose I O void init_port_B t extern void putstr ports B control 0 all general purpose I 0 putstr Port B initialized for general purpose I O putstr CRLF init_port_C x Initialize port C for SCI operation to communicate with E RS 232C port of Wyse terminal NOTE a 40MHz clock speed is assumed void init port C t extern void putstr void init sci void init ssi ports C control 0x0000 all pins set as general purpose I 0 init sci init ssi ports C control 0x01C3 configure RXD TXD pins for SCI function and SRD STD amp SCK pins for SSI function putstr SCI initialized for RS 232 communication with terminal putstr CRLF init_sci Initialize port C for SCI operation to communicate with RS 232C port of Wyse terminal NOTE a 40MHz clock speed is assumed void init sci t extern void putst
265. ion EXAMPLE include lt stdio h gt include lt stdlib h gt void main printf ceil 7 09 f n ceil 7 09 prints to standard output ceil 7 09 8 000000 AA AAA A A A AA A Ml MOTOROLA DSP56KCC User s Manual A 21 clearerr clearerr NAME clearerr Clear any error indicators associated with a specified stream SYNOPSIS include lt stdio h gt void clearerr FILE stream DESCRIPTION The clearerr function clears the end of file and error indicators for the specified stream EXAMPLE include lt stdio h gt void main FILE stream tmpfile initially empty clearerr stream printf end of file indicator is d n feof stream prints to standard output end of file indicator is O e eO O A 22 DSP56KCC User s Manual MOTOROLA COS COS NAME cos Cosine SYNOPSIS include lt math h gt double cos double x DESCRIPTION The cos function computes and returns the cosine of x measured in radians SEE ALSO acos Arc cosine of an angle EXAMPLE include lt stdio h gt include lt math h gt void main printf cos 45 0 f n cos 45 0 prints to standard output cos 45 0 0 525322 AAA A A AA A A Mo MOTOROLA DSP56KCC User s Manual A 23 cosh cosh NAME cosh Hyperbolic cosine SYNOPSIS include lt math h gt double cosh double x DESCRIPTION The cosh function computes and returns the hype
266. ion is given in which case the file will have a cld extension If the B option is IEEE MOTOROLA DSP56KCC User s Manual C 3 asm56000 asm56000 not given then the assembler will not generate an object file The B option should be specified only once D lt symbol gt lt string gt This is equivalent to a source statement of the form DEFINE lt symbol gt lt string gt string must be enclosed in quotes if it contains any embedded blanks Note that if quotes are used they must be passed to the assembler intact e g some host command interpreters will strip quotes from around argu ments The D lt symbol gt lt string gt sequence may be repeated as often as desired F lt argfil gt This option indicates that an external file should be read for further com mand arguments It is useful in host environments where the command line length is restricted argfil must be present on the command line but can be any legal operating system file name including an optional pathname The file may contain any legal command line options including the F op tion itself The arguments need be separated only by white space spaces tabs or newlines A semicolon on a line following white space causes the rest of the line in the file to be treated as a comment G Send source file line number information to the object file This option is valid only in conjunction with B command line option The generated line number information can b
267. ion 6 When precision is 0 and the flag is not specified no decimal point character will be printed A decimal digit will always follow at least one digit The exponent always contains at least two digits g G The double argument is printed in the f e or E form The f form is used unless the exponent to be printed is less than 4 or greater than the precision If precision is zero the printed value consists of no characters this is independent of padding specified by field width Trailing zeros are removed from the fractional portion of the result a decimal point character is printed only if it is followed by a digit c The int argument is printed as an unsigned character a A 94 DSP56KCC User s Manual MOTOROLA printf printf S The argument is a pointer to a character string char Characters from the string are printed up to but not including a terminating null character or until precision characters have been printed If precision is not explicitly specified or is greater than the length of the string the string will be printed until the null character is encountered p The argument is a pointer to the void data type void The value of the of the pointer is printed out as a hexadecimal digit n The argument is a pointer to an integer int which is the number of characters printed so far by the current call to printf 96 Print the percent character 9e Note that the complete specifier is 9696 On
268. ion with an argument name then this argument will be displayed whenever the program stops inside that function but not when it stops elsewhere since this argu ment doesn t exist elsewhere display exp Add the expression exp to the list of expressions to display each time the program stops See section Expressions display fmt exp For fmt specifying only a display format and not a size or count add the expres sion exp to the auto display list but arranges to display it each time in the specified format fmt display fmt addr For fmt i or s or including a unit size or a number of units add the expression addr as a memory address to be examined each time the program stops Examin ing means in effect doing x fmt addr See section Memory undisplay dnums delete display dnums Remove item numbers dnums from the list of expressions to display disable display dnums Disable the display of item numbers dnums A disabled display item is not printed automatically but is not forgotten It may be re enabled later enable display dnums Enable display of item numbers dnums It becomes effective once again in auto display of its expression until you specify otherwise display Display the current values of the expressions on the list just as is done when the program stops info display Print the list of expressions previously set up to display automatically each one with its item number but without
269. ire word of memory each One way to better utilize data memory with a run time cost is to combine the ANSI data type wchar_t and the special ANSI multibyte and wide character library routines pe eO O A 160 DSP56KCC User s Manual MOTOROLA wctomb wctomb EXAMPLE include lt stdio h gt include lt stdlib h gt char mbarray 8 void main wchar t wide Labc char ptr array int convert convert wctomb array wide printf packed char looks like n printf 0 6xinin wide printf d extracted chars looks like n convert while ptr 0 printf 0 6x ptr printf n j prints to standard output packed char looks like 616263 3 extracted chars looks like 000061 000062 000063 u E MOTOROLA DSP56KCC User s Manual A 161 wctomb wctomb pe eO O A 162 DSP56KCC User s Manual MOTOROLA Appendix B DSP56000 DSP56001 Instruction Set and Assembler Directive Summary B 1 Overview This appendix is intended to assist the C programmer in understanding the C compiler s output For a more in depth discussion of assembler and assembly language issues see the DSP56000 DSP56001 Digital Signal Processor User s Manual or the DSP56000 DSP56001 Assembler User s Manual B 2 Instruction Set Instructions can be grouped by function into six types Arithmetic instructions Logical instructions Bit manipulation instructions Loop
270. is code doesn t have to be implemented in an interrupt driven manner periodic polling could be used as well The critical issues are that the communication must be reliable and that the system must not deadlock the latter is easy to ensure given the simple nature of the communication protocol SON en 6 14 DSP56KCC User s Manual MOTOROLA Example 6 7 Sample Host Side Glue Code void interrupt driven io int i get the size of the message from the DSP int size peek IN PORT make sure that hio receive is large enough CHECK BUFFER SIZE amp hio receive size read the message via hardware into the buffer for i 0 i lt size i hio_receive buffer i peek IN_PORT mark the buffer as valid perform any requested I O hio_receive valid_p TRUE process pending host io if the driver wants to send to the DSP then do so now if hio send valid p for i 0 i lt hio_send length i poke OUT PORT hio send buffer i hio send valid p FALSE re register this handler for future DSP message interrupts signal SIG IN PORT interrupt driven io IL _ _ z A MOTOROLA DSP56KCC User s Manual 6 15 AA OO O 6 16 DSP56KCC User s Manual MOTOROLA Appendix A Programming Support A 1 Standard ANSI Header Files Each function provided in the ANSI C library lib56c xyl clb is de
271. ist if C library calls are used This vari able can be utilized as a debugging aid in order to check which error code is re turned from the C function calls 2 Heap stack checking window variable _ _stack_safety is a global variable declared in the crtO file that is used by the heap allocation routines malloc calloc and realloc to avoid heap stack growth collisions If the distance between the bottom of the heap and the top of the stack is less than the value contained in _ stack safety then the heap allocation routine will return an error code indicating that no more memory is available The value may be set as required by the application since the window _ stack safety is declared as a global variable 3 Memory limit variable _ mem limit is a global variable declared in the crtO file and used by the library routine brk to disallow any meaningless memory re quests This variable should have the same value as _ break upon entry into main For information on how to use the function brk refer to Appendix B in this manual 4 Dynamic time variable _ time is a global variable declared in the crtO file and used as a volatile timer counter by the simulator This variable is updated by the DSP56000 simulator run56 every clock cycle Examining this variable allows the SEES 6 8 DSP56KCC User s Manual MOTOROLA programmer to determine program execution time This variable is only used by the simulator and can be omitted when
272. it as the default initialization file at start up whereas gdb56 uses gdbinit56 ee eO A A A A E 2 DSP56KCC User s Manual MOTOROLA GDB Manual The GNU Source Level Debugger Third Edition GDB version 3 4 October 1989 Richard M Stallman Copyright O 1988 1989 Free Software Foundation Inc Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying provided also that the section entitled GNU General Public License is included exactly as in the original and provided that the entire result ing derived work is distributed under the terms of a permission notice identical to this one Permission is granted to copy and distribute translations of this manual into another lan guage under the above conditions for modified versions except that the section entitled GNU General Public License may be included in a translation approved by the author instead of in the original English Summary of GDB The purpose of a debugger such as GDB is to allow you to execute another program while examining what is going on inside it We call the other program your program or the program being debugged GDB can do four kinds of things plus other things in support of these 1 Start the program specifying anythi
273. ite space spaces tabs or new lines A semicolon on a line following white space causes the rest of the line to be treated as a comment l List library contents This option lists the module name as contained in the library header the module size minus library overhead and the date and time the file was stored into the library The listing output is routed to stan dard output so that it may be redirected to a file if desired r This option replaces the named modules in the given library The modules must already be present in the library file u This option updates the specified modules if they exist in the library other wise it adds them to the end of the library file V This option displays the librarian version number and copyright notice X Extract named modules from the library The resulting files are given the name of the modules as stored in the library module header All files are cre ated in the current working directory EET TT Ss SL ees MOTOROLA DSP56KCC User s Manual C 11 dsplnk dsplnk NAME dsplnk Motorola DSP COFF Linker SYNOPSIS dspink B lt lodfil gt F lt argfil gt I L lt library gt M lt mapfil gt N O lt mem gt lt ctr gt lt map gt lt origin gt P lt lpath gt R lt ctlfil gt Z U lt symbol gt V X opt lt opt gt Z files DESCRIPTION dspink is a program that processes relocatable link file
274. ithout updating the memory location corresponding to the variable be tween operations This enhances the performance of the compiled code but makes ac cessing variables in memory risky In order to guarantee that the correct value of a variable is returned when it is referenced a mechanism called operand expansion string OES is provided The OES allows a variable to be securely accessed even though its current location is unknown The operand expansion string is a substring of the instruction template and be gins with the character This string is usually two or three characters long and pro vides the compiler with special information about an operand and how its reference should be printed An OES must reference only one C variable or expression which in turn must be listed in either one or both operand lists see Section 5 2 2 The OES is parsed by the compiler and gives sufficient information to allow the variable to be correct ly referenced by the assembly language instruction in the instruction template Most ex amples in Section 5 2 4 include an OES _ _ ________ _ ___ gt gt gt gt AA lt gt AAA MOTOROLA DSP56KCC User s Manual 5 3 The OES syntax is modifier operand_id_number where 1 modifier is a single optional character which specifies a particular class of oper and The available modifiers are j e R K g i f p and q j an offset
275. k Commands Break conditions can be specified when a breakpoint is set by using if in the arguments to the break command See section Set Breaks They can also be changed at any time with the condition command condition bnum expression Specify expression as the break condition for breakpoint number bnum From now on this breakpoint will stop the program only if the value of expression is true nonzero in C expression is not evaluated at the time the condition command is given See section Expressions condition bnum Remove the condition from breakpoint number bnum It becomes an ordinary un conditional breakpoint A special case of a breakpoint condition is to stop only when the breakpoint has been reached a certain number of times This is so useful that there is a special way to do it using the ignore count of the breakpoint Every breakpoint has an ig nore count which is an integer Most of the time the ignore count is zero and therefore has no effect But if the program reaches a breakpoint whose ignore count is positive then instead of stopping it just decrements the ignore count by one and continues As a result if the ignore count value is n the breakpoint will not stop the next n times it is reached ignore bnum count Set the ignore count of breakpoint number bnum to count The next count times the breakpoint is reached it will not stop To make the breakpoint stop the next time it is re
276. l sig err and sig ign respectively 1 SIG DFL notes that the interrupt happened by incrementing sig drop count and then returns 2 SIG ERR calls abort and never returns 3 SIG IGN returns without any effect i e ignore The mechanisms used to implement the C signal interface may be altered to fit a particular hardware application Any series of alterations applied to the signal file must leave an im plementation conforming to the ANSI standard X3 159 for C Alteration of the signal file is done at one s own risk and is not generally advised Again the contents of the signal file must remain consistent with the include file signal h 65 SetjmpFile The functions setjmp and longjmp are implemented in the setjmp file The setjmp function stores the current process status i e the current execution context in a buffer that is passed The longjmp function is used to restore the process status to the execu tion context which was saved by setjmp I R A I1 1 1 A MOTOROLA DSP56KCC User s Manual 6 11 Saving the current execution context is done by saving the stack pointer the return pro gram counter value the frame pointer and all of the callee save registers into the buffer The buffer that is passed to setjmp should have enough space for the saving process The structure jmp_buf defined in setimp h allocates the buffer space needed for the op eration
277. l like the GDB up command M d Go down the number of frames indicated by the numeric argument like the GDB down command In any source file the Emacs command C x SPC gdb break tells GDB to set a break point on the source line point is on The source files displayed in Emacs are in ordinary Emacs buffers which are visiting the source files in the usual way You can edit the files with these buffers if you wish but keep in mind that GDB communicates with Emacs in terms of line numbers If you add or de lete lines from the text the line numbers that GDB knows will cease to correspond prop erly to the code r C B 9 E 72 DSP56KCC User s Manual MOTOROLA Appendix E Additional Support User support from the conception of a design through completion is available from Motor ola and third party companies as shown in the following list Motorola Third Party Design Data Sheets Data Acquisition Packages Application Notes Filter Design Packages Application Bulletins Operating System Software Software Examples Simulator Prototyping Assembler Logic Analyzer with Linker DSP56000 DSP56001 ROM Packages C Compiler Data Acquisition Cards Simulator DSP Development System Application Development Cards System ADS Operating System Software In Circuit Emulator Debug Software Cable for ADS Design Application Development Data Acquisition Packages Verification Sy
278. l 35 cur pos 25 v col while c getc NO_ECHO ENTER look for an ENTER to quit loop if c ESCAPE c getc NO ECHO switch c case UP for CNTL K or up arrow case ARROW UP if v 15 vtt cur pos 25 v col Screen attr REVERSE increase bar height putstr cur pos 25 v col 1 place cursor at top of bar status VOLUME v update status _GAIN VOL v lt lt 20 update global volume value scaled for fractional format break case DOWN for CNTL J or down arrow case ARROW_DOWN if v gt 0 cur pos 25 v col lower bar screen_attr NORMAL putstr YE MOTOROLA DSP56KCC User s Manual F 23 v decrease volume cur pos 25 v col 1 place cursor at top of bar status VOLUME v update status _GAIN VOL v lt lt 20 update global volume value scaled for fractional format break default putc BEEP beep for invalid entry break screen_attr NORMAL mute sel Toggle between muted and un muted mode If not currently muted MUTE sets the global flag muted stores the current volume in a local static variable mute vol and sets the global volume value to 0 If currently muted MUTE restores the global volume value to the value in mute vol and clears the muted flag void mute t static int mute vol extern int GAIN extern int sta
279. label F_ _crt0_end This label is used by gdb56 and run56 to detect program termination Note Labels which begin with a double underline e g _ _crt0_end in this manual have a space between the double underlines to visually separate them Do not separate the leading double underlines with a space when coding them e code crt0 endas crtO end Example 6 1 DSP56000 DSP56001 Operation Mode Change Mode 2 has a reset vector of 000 which must contain a jmp to the C program bootstrap code Adding the following code segment to the erto file will change the bootstrap mode to Mode2 section mode2 reset org p e000 jmp F__start jump to the C start up program endsec Example 6 2 Hardware was designed to have a 256 byte ROM monitor located in the program memory space starting at 0000 and ending at FF Program RAM starts at location p 100 The following changes to the crto file will change the beginning location of the C bootstrap code to the first available RAM location p 100 The DS statement allocates program space starting at p 0000 and lets the ROM be located at address p 0000 The org statement places the C bootstrap code at memory location p 100 Change this portion of the crto file org p F__ start to org p 0000 ds 100 org p 100 F start 6 3 2 Memory Configuration and Management The DSP56000 family supports three memory spaces program memory p memory x and y data memories The DSP56000 family des
280. lag char s int len int type flag EES F 26 DSP56KCC User s Manual MOTOROLA char c int count count 0 while c getc NO_ECHO ENTER if isgraph c type_flag DIGIT amp amp isdigit c if c BACKSPACE c DEL c CANCEL if count 0 handle backspace if str not empty putc BACKSPACE echo delete character putc SPACE putc BACKSPACE s count else putc BEEP ignore nonprinting chars or non digits for numbers else add character to string putc c and echo character st C count if count len bail out if string is full break end while s NUL end string with null MOTOROLA DSP56KCC User s Manual F 27 io_scrn c This file contains the low level functions required for the communication between the SCI port and the screen manipulation The screen manipulations includes cursor positioning screen line and field clearning E E E E include globals h see page F 11 setscreen Set the entire screen to the specified character using the escape sequence ESC character void setscreen c void putc putc ESCAPE putc putc c clrfield Clear a field of characters of length size to blanks void clrfield size int size int i void putc for i 0 i lt size i putc SPACE
281. lared in this manner In the example below this is done with the assembler directive dc Also ANSI C requires that all global variables be initial ized to zero if they are not explicitly initialized M A e 5 32 DSP56KCC User s Manual MOTOROLA Example 5 32 Global Label in Assembly Language This example shows assembly code that defines a global integer named FGinteger which is normally accessed as Ginteger in the C environment and FGinteger in the assembly programming environment FGinteger dc 0 global FGinteger MOTOROLA DSP56KCC User s Manual 5 33 Example 5 33 Global Variable Declaration This is the C code equivalent to Example 5 32 which defines the global integer Ginteger extern int Ginteger Example 5 34 Changing a Global Label This example shows C code that generates a global integer Ginteger which is accessed as Ginteger in both the C environment and the assembly programming environment extern int Ginteger asm Ginteger Which will appear in assembly language code as Ginteger dc 0 global Ginteger 5 4 3 Using Run time Stack for Local Data The run time stack may be used when the programmer requires a temporary data space for automatic style variables i e local variables in subroutines Using the run time stack requires additional steps in the prologue and epilogue sections lt is the subrou tine s responsibility to automatically all
282. last breakpoint set It is possible for breakpoint commands to start the program up again Simply use the cont command or step or any other command to resume execution However any re maining breakpoint commands are ignored When the program stops again GDB will act according to the cause of that stop If the first command specified is silent the usual message about stopping at a break point is not printed This may be desirable for breakpoints that are to print a specific mes sage and then continue If the remaining commands too print nothing you will see no sign that the breakpoint was reached at all silent is not really a command it is meaning ful only at the beginning of the commands for a breakpoint The commands echo and output that allow you to print precisely controlled output are often useful in silent breakpoints See section Output For example here is how you could use breakpoint commands to print the value of x at entry to foo whenever it is positive break foo if x gt 0 commands silent El E 32 DSP56KCC User s Manual MOTOROLA echo x is 040 output x echo n cont end One application for breakpoint commands is to correct one bug so you can test another Put a breakpoint just after the erroneous line of code give it a condition to detect the case in which something erroneous has been done and give it commands to assign cor rect values to any variables that need them En
283. le a cld and the result is to print hello world on the computer screen Example Program include lt stdio h gt main printf hello world n Commands to Compile and Execute the Example Program C gt g56k hello c C gt run56 a cld Result Printed on the Computer Screen hello world Example 2 1 Test Program AAA A AAA A A A AAA A l E MOTOROLA DSP56KCC User s Manual 2 5 pe 9 2 6 DSP56KCC User s Manual MOTOROLA Chapter 3 Control Program Options 3 1 Overview Program g56k is the control program for Motorola s optimizing C compiler for the DSP56000 DSP56001 family of digital signal processors The program g56k automates control of the four C compiler phases preprocessing compiling assembling and link ing The program g56k utilizes a command syntax similar to those adopted by UNIX utili ties The g56k syntax is g56k options files where 1 options is one or more of the options found in this chapter One difference between g56k and UNIX style utilities is that the combination of multiple single character options is not allowed For example O g instructs the compiler to generate an optimized executable with source level debug information whereas Og which is acceptable to UNIX style compilers is not acceptable to g56k 2 file is the file s to be processed Program g56k accepts input filen
284. le object modules compatible with linker program when in relocatable mode Production of absolute files compatible with simulator program when in absolute mode I O d 1 D 2 DSP56KCC User s Manual MOTOROLA Supports full instruction set memory spaces and parallel data transfer fields of the DSP56000 DSP56001 Modular programming features local labels sections and external definition ref erence directives Nested macro processing capability with support for macro libraries Complex expression evaluation including boolean operators Built in functions for data conversion string comparison and common transcen dental math functions Directives to define circular and bit reversed buffers Extensive error checking and reporting Simulator Features Simulation of all DSP56000 family DSPs e Simulation of multiple DSP56000 family DSPs Linkable object code modules Nondisplay simulator library Display simulator library C language source code for Screen management functions Terminal I O functions Simulation examples Single stepping through object programs Conditional or unconditional breakpoints Program patching using a single line assembler disassembler Instruction clock cycle and histogram counters Session and or command logging for later reference ASCII input output files for peripherals Help line di
285. les STG_1G STG 2G and STG 3G can be accessed through the C array _GAIN In assembly language the variables VOLUME STG_1G STG_2G and STG_3G can be used directly while GAIN O GAIN 1 GAIN 2 and _GAIN 3 are used to set up the same data in the C program the function init_project on page F 16 The special effects system contains a user friendly menu see page F 17 which can be used to program the parameter setups A dumb terminal e g a WYSE 60 sends and receives characters through an RS 232 port interfaced to the SCI of DSP56000 family processor The C programs io sci c io scrn c io host c io atoi c and io ctype c on page F 25 through page F 35 are the low level drivers to interface the standard l O functions to the SCI A makefile is provided on page F 4 to show a common tool which can be utilized for a complex computer software development project The make utility is available both in UNIX and IBM PC environments and it can be very helpful to organize programs Through this tool any modified files are recompiled or reassembled automatically with specific options Notice that the program g56k is used for compilation assembly and linking of the source or link files The option ffixed r7 on page F 4 is intended to facilitate the use of the fast interrupt facility of the DSP56000 family processors This register r7 is used for servicing fast interrupts SCI interrupts in this example The program vectors asm on page F 41
286. lies a cer tain size and representation in memory and set intOx83040 4 would store the value 4 into that memory location 3 30 Continuing at a Different Address Ordinarily when you continue the program you do so at the place where it stopped with the cont command You can instead continue at an address of your own choosing with the following commands jump linenum Resume execution at line number linenum Execution may stop immediately if there is a breakpoint there The jump command does not change the current stack frame or the stack point er or the contents of any memory location or any register other than the program counter If line linenum is in a different function from the one currently executing the results may be bizarre if the two functions expect different patterns of argu ments or of local variables For this reason the jump command requests confir mation if the specified line is not in the function currently executing However even bizarre results are predictable based on careful study of the machine language code of the program jump address Resume execution at the instruction at address address You can get much the same effect as the jump command by storing a new value into the register pc The difference is that this does not start the program running it only chang es the address where it will run when it is continued For example set pc 0x485 causes the next cont comm
287. ling sequence is broken down into three sub sequences that are strictly defined The three sub sequences are caller callee and return sequence Note This calling convention must be followed when writing in line or out of line assembly language subroutines that call subroutines written in C _ LZ A Ali iQs M A 4 12 DSP56KCC User s Manual MOTOROLA 4 8 1 Caller Sequence The caller portion of the subroutine calling sequence is responsible for 1 pushing arguments onto the activation record in reverse order 2 actual subroutine call jsr 3 stack pointer adjustment Additional caller sequence when the subroutine called will return a structure 4 allocate space in the caller s activation record to store the return structure 5 pass the return value address in accumulator a 4 8 2 Callee Sequence During the initial portion of the subroutine calling sequence the callee is responsible for 1 saving return address ssh and the old frame pointer RO 2 updating frame and stack pointers 3 saving the following registers as required B1 BO X1 X0 Y1 YO R1 R5 and R7 4 8 3 Return Sequence During the final portion of the subroutine calling sequence the callee is responsible for 1 placing the return value in accumulator a 2 testing the return value This optimizes the case where function calls are arguments to conditional operators Additional callee sequence when the subroutine called will return a str
288. lower case O lt mem gt lt ctr gt lt map gt lt origin gt By default the linker generates instructions and data for the load file begin ning at absolute location zero for all DSP memory spaces This option al lows the programmer to redefine the start address for any memory space and associated location counter mem is one of the single character memory space identifiers X Y L and P The letter may be upper or lower case The optional ctr is a letter indi cating the high H or low L location counters If no counter is specified the default counter is used map is also optional and signifies the desired nS eA C 14 DSP56KCC User s Manual MOTOROLA dsplnk dsplnk physical mapping for all relocatable code in the given memory space It may be for internal memory E for external memory or B for bootstrap memory valid only in P program memory space If map is not supplied then no explicit mapping is presumed The origin is a hexadecimal number signifying the new relocation address for the given memory space The O option may be specified as many times as needed on the command line P lt lpath gt When the linker encounters a library specification on the command line the current directory or the directory given in the library specification is first searched for the library file If it is not found and the P option is supplied the linker prefixes the file name and optional pathname provided in the li brary
289. lowercase character to uppercase SYNOPSIS include lt ctype h gt int toupper int c DESCRIPTION The toupper function converts lowercase to uppercase If c is a lowercase letter return the corresponding uppercase letter otherwise return c When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main printf toupper A c n toupper A printf toupper z c n toupper 2 printf toupper c n toupper prints to standard output toupper A A toupper z Z toupper AAA A A A A A M MOTOROLA DSP56KCC User s Manual A 153 ungetc ungetc NAME ungetc Push a character back onto an input stream SYNOPSIS include lt stdio h gt int ungetc int c FILE stream DESCRIPTION The function ungetc converts the argument c to an unsigned char and pushes it back onto the specified input stream Pushed characters will be read back in reverse order by any functions reading from said stream If a call is made to a file positioning function such as fseek all pushed characters will be lost Only one call to ungetc before a read from the stream is allowed EOF cannot be pushed ungetc returns EOF upon failure while the converted value is returned upon success SEE ALSO tmpfile C
290. lp Help for iir1 asm 1786 iirt asm 1 0 Test program for iir1 asm 1157 iir2 asm 1 0 Direct Form Second Order All Pole 801 IIR Filter with Scaling iir2 hlp Help for iir2 asm 2286 iir2t asm 1 0 Test program for iir2 asm 1311 iir3 asm 1 0 Direct Form Arbitrary Order All 776 Pole IIR Filter iir3 hlp Help for iir3 asm 2605 iir3t asm 1 0 Test program for iir3 asm 1309 iir4 asm 1 0 Second Order Direct Canonic IIR Filter 713 Biquad IIR Filter iir4 hlp Help for iir4 asm 2255 iir4t asm 1 0 Test program for iir4 asm 1202 iir5 asm 1 0 Second Order Direct Canonic IIR Filter 842 with Scaling Biquad IIR Filter iirb hlp Help for ir5 asm 2803 iirbt asm 1 0 Test program for iir5 asm 1289 iir6 asm 1 0 Arbitrary Order Direct Canonic IIR 923 Filter iir6 hlp Help for iir6 asm 3020 iir6t asm 1 0 Test program for iir6 asm 1377 iir7 asm 1 0 Cascaded Biquad IIR Filters 900 EES D 8 DSP56KCC User s Manual MOTOROLA Document ID Version Synopsis Size iir7 hlp Help for iir7 asm 3947 lir7t asm 1 0 Test program for iir7 asm 1432 Ims hlp 1 0 LMS Adaptive Filter Algorithm 5818 transiir asm 1 0 Implements the transposed IIR filter 1981 transiir hlp 1 0 Help file for transiir asm 974 Floating Point Routines fpdef hlp 2 0 Storage format and arithmetic 10600 representation definition fpcalls hlp 2 1 Subroutine calling conventions 11876 fplist asm 2 0 Test file that lists all subroutines 1601 fprevs hlp 2 0 Latest revisions of
291. lude lt stdio h gt include lt math h gt void main double point for point 0 8 point lt 1 0 point 0 2 printf f asin point if point gt 0 0 printf n prints to standard output 0 927295 0 643501 0 411516 0 201357 0 000000 0 201357 0 411516 0 643501 0 927295 1 570450 i A 10 DSP56KCC User s Manual MOTOROLA atan atan NAME atan Arc tangent SYNOPSIS include lt math h gt double atan double x DESCRIPTION The atan function computes the principle value of the arc tangent of x in the range 1 2 n 2 where x is in radians SEE ALSO tan Tangent EXAMPLE include lt stdio h gt include lt math h gt void main double point for point 0 8 point lt 1 0 point 0 2 printf f atan point if point gt 0 0 printf n prints to standard output 0 674740 0 540419 0 380506 0 197395 0 000000 0 197395 0 380506 0 540419 0 674740 0 785398 u OE MOTOROLA DSP56KCC User s Manual A 11 atan2 atan2 NAME atan2 Arc tangent of angle defined by point y x SYNOPSIS include lt math h gt double atan2 double y double x DESCRIPTION The atan2 function computes the principle value of the arc tangent of y x using the signs of both arguments to determine the quadrant of the return value If both arguments are zero errno is
292. luded from the file globals h include globals h see page F 11 Global variable declarations definitions of globals structures are B contained in the file globals h struct sci port sci pointer to structure defining the SCI port struct ssi port ssi pointer to structure defining the SSI port struct B C ports ports pointer to structure defining control registers for ports B and C int int priority pointer to interrupt priority register int A control pointer to port A control register char ungetcbuf NUL buffer for ungotten characters int status global array to track special audio effects status 0 INPUTS 1 EFFECTS 0 VOLUME 1 MODEL 1 FILTER 0 MUTE y main routine main extern void setscreen extern void putstr extern int menu void init_port_B void init_port_C void init project int c char tell 20 initialize pointers to on chip peripherals and control registers Sci struct sci port SCI ADDR see global h on page F 11 ssi struct ssi port SSI ADDR see global h on page F 11 ports struct B C ports PORTS ADDR see global h on page F 11 A control int A CONTROL ADDR see global h on page F 11 int priority int INT PRIORITY ADDR see global h on page F 11 initialize I O ports and special aud
293. m Ann 3 24 DSP56KCC User s Manual MOTOROLA Compile Phase Options pile properly with or without this option pedantic does not cause warning messages for use of the alternate keywords whose names begin and end with Direct the compiler to execute in verbose mode Compile to DSP56000 1 assembly code with the original C source lines as com ments but do not assemble The assembly language output is placed into a file suf fixed asm Example 3 25 Generate an optimized assembly language file test asm of the C source program test c CEN dir test c C gt type test include lt stdio h gt main int i 100 printf value d n i C gt g56k S test c C gt ALE test asm test c Example 3 26 Generate an optimized assembly language file test asm C gt g56k O S test c W Inhibit all warning messages W Print extra warning messages for the following events e An automatic variable is used without first being initialized This warning is possible only when the optimizer is invoked during compilation A aaa MOTOROLA DSP56KCC User s Manual 3 25 Compile Phase Options default The optimizer generates the data flow information required for reporting This warning will only occur for variables that are candidates for register promo tion Therefore they do not occur for a variable that is declared volatile whose address is taken or whose size is other than 1 or 2 words integ
294. m should be assembled before use since the option crt takes cln file not asm file Caos dace crtasm foo c Gr V gt g56k c crt asm EES 3 30 DSP56KCC User s Manual MOTOROLA Link Phase Options C gt dir crt cln crt asm foo c Co go echt Cres Clin Losa j string Pass the argument string directly to dspInk the DSP56000 1 linker Example 3 34 Pass a single option to the linker C gt g56k jJ v file c Example 3 35 Pass multiple options to the linker C gt g56k j v i file c ILIBRARY Search the standard list of directories for a library file named libLIBRARY clb The linker automatically expands LIBRARY from the option command into libLl BRARY clb and uses this file as if it had been specified precisely by name Example 3 36 Compile the source code using the special dsp application library Searching the standard list of directories for a library named libdspaps clb C gt g56k O file vc ldspaps r CTLFILE Search the standard list of directories for the memory control file CTLFILE to be passed as an argument to the DSP56000 1 relocatable linker This control file will be used as a table to locate object files sections to be linked For more detailed in formation see the R options and the section on Memory Control File in the Motor ola Linker Librarian Reference Manual Example 3 37 Compile the source code main c and data c with the memory configuration described in the control file map ctl
295. match for regular expression regexp Thus info fun step finds all functions whose names include step info fun step finds those whose names start with step info variables Print the names and data types of all variables that are declared outside of func tions i e except for local variables info variables regexp Print the names and data types of all variables except for local variables whose names contain a match for regular expression regexp info types Print all data types that are defined in the program info types regexp Print all data types that are defined in the program whose names contain a match for regular expression regexp printsyms filename Write a complete dump of the debugger s symbol data into the file filename A _ O n E 60 DSP56KCC User s Manual MOTOROLA D 10 Altering Execution Once you think you have find an error in the program you might want to find out for cer tain whether correcting the apparent error would lead to correct results in the rest of the run You can find the answer by experiment using the GDB features for altering execu tion of the program For example you can store new values into variables or memory locations give the pro gram a signal restart it at a different address or even return prematurely from a function to its caller 3 29 Assignment to Variables To alter the value of a variable evaluate an assignment expression See section Ex
296. mbly mnemonic asm instruction and uses input expression as a read only operand asm asm instruction 0 S input expression Example 5 15 Write Only Operand This in line assembly code uses the pseudo assembly mnemonic asm instruction and uses output expression as a write only operand _ asm asm instruction 960 D output_expression Example 5 16 Read Write Operand An addition is programmed using in line assembly code and the C expression result is used as a read write operand The variable foo is used as a read only operand Notice that operand constraint 0 was used to reference the add instructions second source operand which is also the destination operand see the DSP56000 DSP56001 Users Manual Appendix A for the syntax of the add instruction int foo result __asm add 961 960 D result S foo 0 result Example 5 17 Read Write Operand The same result will be obtained as in Example 5 16 Notice how the operand id is changed according to the placement of the C variables int foo result __asm add 962 960 D result 0 result S foo Example 5 18 Multiple Instruction Single Line An in line assembly program which places a value e g 709 in register a and negates the result is written in one line This one line will generate two lines of assembly code in the C compiler output __asm move 709 A n neg A __
297. me to the end of the source path Several directory names may be given to this command separated by whitespace or directory Reset the source path to just the current working directory of GDB This requires confirmation Since this command deletes directories from the search path it may change the directory in which a previously read source file will be discovered To make this work correctly this command also clears out the tables GDB maintains about the source files it has already found info directories Print the source path show which directories it contains Because the directory command adds to the end of the source path it does not affect any file that GDB has already found If the source path contains directories that you do not want and these directories contain misleading files with names matching your source files the way to correct the situation is as follows 1 Choose the directory you want at the beginning of the source path Use the cd command to make that the current working directory 2 Use directory with no argument to reset the source path to just that directory 3 Use directory with suitable arguments to add any other directories you want in the source path A _ _ _ _ gt A U E 46 DSP56KCC User s Manual MOTOROLA D 8 Examining Data The usual way to examine data in your program is with the print command abbreviated p It evaluates and print
298. missions allow 3 Inside the shell use the command cd to go to the directory where the compiler s dsp directory tree is to reside For this example assume that the compiler is to be installed in usr mydir referred to by compiler s dsp directory tree here 4 Make sure that you have write permission in the directory 5 Enter the command bar xZvf dev r fdO If the floppy drive must be accessed via a different device file than rfdO then use the appropriate device for your system 6 Make sure that every user adds compiler s dsp directory tree gt dsp bin to their path In this example the path usr mydir dsp bin would be added to everyone s path 7 Make sure that every user sets the environment variable DSPLOC to the path leading to the dsp directory tree which is the directory compiler s dsp directory tree gt In this example DSPLOC would be set to usr mydir Note that DSPLOC would not be set to usr mydir dsp eeaeee 2 4 DSP56KCC User s Manual MOTOROLA 2 5 Test Program The following test program is intended to be a very simple check to see if the installation has been completed correctly The program should be put in a file named hello c The control program g56k compiles the program in the file hello c and generates the output file a cld Do not enter the C gt as it is simply a prompt indicating that this line should be entered from the keyboard The command run56 executes the program in the fi
299. most impos sible to write without causing those warnings Wshadow Warn whenever a local variable shadows another local variable Wid clash LEN Warn whenever two distinct identifiers match in the first LEN characters This may help prepare a program that will compile with certain obsolete compilers Wpointer arith Warn about anything that depends on the sizeof a function type or of void GNU C assigns these types a size of 1 for convenience in calculations with void pointers and pointers to functions Wcast qual Warn whenever a pointer is cast so as to remove a type qualifier from the target type For example warn if a const char is cast to an ordinary char Wwrite strings Give string constants the type const char LENGTH so that copying the address of One into a non const char pointer will generate a warning These warnings help at compile time to find code that can try to write into a string constant but only if const in declarations and prototypes have been used carefully 3 2 3 Assemble Phase Options This group of assemble phase options is the sub set of the available assembler options that are compiler oriented see the Motorola DSP56000 Macro Assembler Reference gt gt gt a u 2 MOTOROLA DSP56KCC User s Manual 3 29 Link Phase Options Manual for a complete option list The default option is to add to the standard search list the directory that the C compiler writes its output into and then search that direc
300. move ffffff f0 m foo Assembly Code Generated move ffffff Y 233 Example 5 12 OES modifier p and q This in line assembly code programs the SCI of DSP56001 by setting up the SCI registers located at X FFFO and X FFF2 You may use modifier p for any 16 bit value define SCR OxFFFO define SCCR OxFFF2 define V_SCR 0x2000 define V SCCR 0x013F main asm movep 0 x q1 i V SCR i SCR asm movep 0 x q1 i V SCCR i SCCR j Assembly Code Generated movep gt 002000 x 65520 movep gt 00013f x 65522 ea UMME 5 12 DSP56KCC User s Manual MOTOROLA Example 5 13 Input Expression Output Expression This in line assembly code uses the pseudo assembly mnemonic asm_instruction and refers to two C expressions output expression and input_expression This example illustrates how to interpret the operand constraint see Section 5 2 2 and operand id see Section 5 2 1 and Example 5 3 The example implies that the C expression output_expression is expanded with constraint D and is an output of the assembly code instruction asm_instruction Similarly the C expression input_expression is expanded with constraint S and used as an input to the assembly code instruction asm instruction asm asm instruction 961 960 D output expression S input expression Example 5 14 Read Only Operand This in line assembly code uses the pseudo asse
301. n to w n 1 y0 b11 2 mac x1 y0 a x r0 x0 y r4 y0 get w n back y0 b10 2 mac x0 y0 a x r0 x0 y r4 y0 next iter x0 w n 2 y0 ai2 2 move a y SSI XMT DO output through SSI buffer RESTORE REG rti endsec List F 13 The list of project asm rL UM e MOTOROLA DSP56KCC User s Manual F 37 zrec vars asm Special variables for fast access or ON CHIP peripheral device Internal L Memory Space for context switch section L internal org L 0000 xdef REG FILE REGS TOP xdef SPEFFECT IN SPEFFECT OUT REG FILE ds 8 Storage area for reg s saved in context switch REGS TOP ds 1 last storage location for registers SPEFFECT IN ds 1 storage for input to special effects routine SPEFFECT_OUT ds 1 storage for output from special effects routine endsec i Internal X Memory Space for fast variables i section v_bles org X 0010 global F coef ptr F defeat global F coef 3 F coef 4 F coef 5 global F coef 6 F coef 7 F coef 8 global F coef band xdef COEF PTR DATA SOMEOTHERS COEF PTR F coef ptr dc COEF 3 pointer to filter coefficients F defeat ds 1 Special audio effectson off F coef 3 dc COEF 3 Allow C to access the coefficients F coef 4 dc COEF 4 located in Y memory space because F coef 5 dc COEF 5 C program is compiled in X memory model F coef 6 dc COEF 6 F coef 7 dc COEF 7 F coef 8 dc COEF 8 F coef band dc COEF BAND
302. n is supposed to be an argument to the B option it can be placed immediately after the option let ter without intervening white space asm56000 bmain io If there are other options on the command line besides those that take op tional arguments the other options can be placed between the ambiguous option and the list of source file names asm56000 b main v io Alternatively two successive hyphens may be used to indicate the end of the option list asm56000 b main io In this case the assembler interprets main as a source file name and uses the default naming conventions for the B option A Indicates that the assembler should operate in absolute mode creating a load file cld if the B option is given By default the assembler produces a link file cln which is subsequently processed by the Motorola DSP linker B lt objfil gt This option specifies that an object file is to be created for assembler out put objfil can be any legal operating system file name including an option al pathname A hyphen may also be used as an argument to indicate that the object file should be sent to the standard output If a path is not specified the file will be created in the current directory If no file name is supplied the assembler will use the basename file name with out extension of the first file name encountered in the source input file list The resulting output file will have an extension of cln unless the A opt
303. n the selected frame There are special GDB commands to select whichever frame you are interested in When the program stops GDB automatically selects the currently executing frame and describes it briefly as the frame command does see section Frame Info Info 3 13 Stack Frames The call stack is divided up into contiguous pieces called stack frames or frames for short each frame is the data associated with one call to one function The frame con tains the arguments given to the function the function s local variables and the address at which the function is executing When your program is started the stack has only one frame that of the function main This is called the initial frame or the outermost frame Each time a function is called a new frame is made Each time a function returns the frame for that function invocation is eliminated If a function is recursive there can be many frames for the same function The frame for the function in which execution is actually occurring is called the innermost frame This is the most recently created of all the stack frames that still exist Inside your program stack frames are identified by their addresses A stack frame con __ ____ _ __ _ _ __zQ_ z_ A A Qx_ _ AAA MOTOROLA DSP56KCC User s Manual E 37 sists of many bytes each of which has its own address each kind of computer has a convention for choosing one of those bytes whose address serves as the address of
304. nd free Example 6 3 Fast Stack In this example the stack is required to reside in an 8k SRAM starting at L 4000 The following program reserves the stack space using org and ds statements and sets the initial stack pointer to the SRAM stack area Add this section to the crto file section fast ram org L 4000 ds 2000 endsec Change the following line of C bootstrap code in the erto file move y F y size r6 to move 4000 r6 Example 6 4 Fast Heap The heap is required to reside in an 8k SRAM starting at L 4000 The following program reserves the heap space using org and ds statements and sets the initial heap pointer to the SRAM heap area Add this section to the crto file section fast ram org L 4000 ds 2000 endsec Change the following line of C bootstrap code in the crto file H C CCC CK CcCK C C MVAAILOEGGVCD aa MOTOROLA DSP56KCC User s Manual 6 5 TOP_OF_MEMORY equ ffbe to TOP OF MEMORY equ 5fff Sometimes hardware configurations map more than one memory space into a single physical memory Other implementations partially populate various address spaces leav ing holes Some may have different regions with fast memory and slow memory All of these special cases can usually be handled by modifying the crto file When multiple memory spaces are mapped into a single physical memory the memory must be partitioned among the memo
305. nd the current directory if appropriate are searched Using both nostdinc and I options all directories from the search path except those specified can be eliminated _ __ __________ gt _ gt gt gt gt E __ __ _____ 1 MOTOROLA DSP56KCC User s Manual 3 15 Preprocessor Phase Options Example 3 18 A test program test c is used to test a new version of the function printf which is declared in a new header file inc stdio h The directive include lt stdio h gt causes the program to use stdio h however it would normally find it in the standard search directory usr local dsp include Using the nostdinc option prevents the standard search directory from being searched and allows the l option to point to the correct directory C gt dir inc test c C gt dir inc stdio h C gt type test c include lt stdio h gt main printf Hello there n C gt type inc stdio h void printf char C gt g56k nostdinc I inc E test c 1 test c 1 Aincistdio h 1 void printf char 1 test c 2 main printf Hello there n pedantic The pedantic option is used by both the preprocessor and the compiler see pe dantic in the Compile Phase Options section for an explanation of this option P Only run the source file through the C preprocessor This option sends the output to a file with a i suffix This output file does not include line information in t
306. ng that might affect its behavior 2 Make the program stop on specified conditions 3 Examine what has happened when the program has stopped so that you can see bugs happen 4 Change things in the program so you can correct the effects of one bug and go on to learn about another without having to re compile first GDB can be used to debug programs written in C and C Pascal support is being im plemented and Fortran support will be added when a GNU Fortran compiler is written Aaaa MOTOROLA DSP56KCC User s Manual E 3 GNU GENERAL PUBLIC LICENSE Version 1 February 1989 Copyright 1989 Free Software Foundation Inc 675 Mass Ave Cambridge MA 02139 USA Everyone is permitted to copy and distribute verbatim copies of this license document but changing it is not allowed Preamble The license agreements of most software companies try to keep users at the mercy of those companies By contrast our General Public License is intended to guarantee your freedom to share and change free software to make sure the software is free for all its users The General Public License applies to the Free Software Foundation s software and to any other program whose authors commit to using it You can use it for your pro grams too When we speak of free software we are referring to freedom not price Specifically the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software
307. ng the Program or any work based on the Pro gram you indicate your acceptance of this license to do so and all its terms and conditions 7 Each time you redistribute the Program or any work based on the Program the recipient automatically receives a license from the original licensor to copy distrib ute or modify the Program subject to these terms and conditions You may not im pose any further restrictions on the recipients exercise of the rights granted herein EE E 6 DSP56KCC User s Manual MOTOROLA The Free Software Foundation may publish revised and or new versions of the General Public License from time to time Such new versions will be similar in spir it to the present version but may differ in detail to address new problems or con cerns 8 Each version is given a distinguishing version number If the Program specifies a version number of the license which applies to it and any later version you have the option of following the terms and conditions either of that version or of any lat er version published by the Free Software Foundation If the Program does not specify a version number of the license you may choose any version ever pub lished by the Free Software Foundation 9 If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different write to the author to ask for permission For software which is copyrighted by the Free Software Foundation write
308. nge to this file requires detailed knowledge of the DSP56000 family interrupt mechanism in addition to the signal and raise functions This file is closely tied to the signal h file OEE MOTOROLA DSP56KCC User s Manual 6 1 The setjmp file contains code which implements the functions setjmp and longjmp This file will probably never need to be modified unless the signal file is changed however if either the setjmp file or setimp h are modified the code in both files must be made con sistent The source code for setimp and longjmp is provided with DSP56KCC to allow modification should the signal mechanism need to be changed The operation of setjmp and longjmp is described in Section 6 5 and detailed imple mentation information can be obtained from the files provided with DSP56KCC 6 3 crt0 File The following subsections describe the various functions of the crto file 6 3 1 Bootstrapping the C program The processor enters a C program through the C bootstrap code in the crto file The C bootstrap code in crtO provides the C environment required to execute a C program This environment includes a global data area static data area stack area heap area function calling mechanism etc This environment must be established before C programs will ex ecute correctly The following steps are normally taken to initialize the processor to execute C code 1 Jump from the chip reset vector to the C
309. nker refers to the file mem ctl as a control file for special linking instructions the linker generates a map file called project map linker output is placed in the file project cld E Qubdb dE Hb HEHE HE tE Hb db db JE HE Mb db Wb DE DE Pb Ub Mb D Db Pb Mb Pb db db Db Pb Mb Wb db DE DE DE Y Utilities c g56k SM g56k D g56k CVT cldlod Options COPTS c ffixed r7 fvolatile mx memory AOPTS c LOPTS crt crt0 cln j Mproject map o main cld r mem ctl Link files CLNS main cln menu cln io sci cln io scrn cln io ctype cln io host cln io atoi cln project cln vars cln vectors cln convert cln file to lod file project lod crt0 cln main cld CVT main cld gt project lod List F 1 Makefile nan F 4 DSP56KCC User s Manual MOTOROLA Link all cln files together main cld CLNS crt0 cln mem ctl LD LOPTS CLNS Compile and or assemble individual files project cln project asm save_restore mac ASM AOPTS project asm main cln main c CC COPTS main c menu cln menu c CC COPTS menu c io_sci cln io_sci c CC COPTS io sci c io_scrn cln io_scrn c CC COPTS io_scrn c io_ctype cln io_ctype c CC COPTS io_ctype c io_host cln io_host c CC COPTS io_host c io_atoi cln io_atoi c CC COPTS io_atoi c vars cln vars asm CC AOPTS vars asm vectors cln vectors asm CC A
310. no fixed types You can assign a convenience variable any type of value even if it already has a value of a different type The convenience variable as an expression has whatever type its current value has info convenience Print a list of convenience variables used so far and their values Abbreviated i con One of the ways to use a convenience variable is as a counter to be incremented or a pointer to be advanced For example set i 0 print bar i gt contents fepeat that command by typing RET Some convenience variables are created automatically by GDB and given values likely to be useful The variable is automatically set by the x command to the last address exam ined see section Memory Other commands which provide a default address for x to examine also set to that address these commands include info line and info breakpoint The variable _ is automatically set by the x command to the value found in the last address examined EE E 56 DSP56KCC User s Manual MOTOROLA 3 28 Registers Machine register contents can be referred to in expressions as variables with names starting with The names of registers are different for each machine use info registers to see the names used on your machine The names pc and sp are used on all ma chines for the program counter register and the stack pointer Often fp is used for a reg ister that contains a point
311. nop HOST_CMD7_INT nop nop HOST CMD8 INT nop nop HOST CMD9 INT nop nop HOST CMDA INT nop nop HOST CMDB INT nop nop HOST CMDC INT nop nop ILL INST INT nop nop endsec e F 42 DSP56KCC User s Manual MOTOROLA save_restore mac SAVE_REG RESTORE_REG A Function SAVE REG Save A B X Y R N and Status registers s RESTORE REG Restore A B X Y R N and Status registers E Data Format X Ms ee ee a utu eeERCCEELTEI REG FILE gt RO R1 R2 R3 decem R4 R5 i je R6 SR NO N4 a X1 xo Xt vo Al ao REGS_TOP gt B1 BO ee RS SAVE REG MACRO move r0 x REG FILE move lt REG_FILE r0 move rl y r0 move r2 x r0 move 13 y r0 move r4 x r0 move r5 y r0 move r6 x r0 move sr y r0 move n0 x r0 move n4 y r0 move x 1 r0 move y 1 r0 move al0 1 r0 move b10 1 r0 ENDM RESTORE REG MACRO move lt REGS_TOP r0 move 1 r0 b10 move 1 r0 al0 move 1 r0 y move 1 r0 x move y r0 n4 move x r0 n0 move y r0 sr move x r0 r6 move y r0 r5 move x r0 r4 move y r0 r3 move x r0 r2 move y r0 rl move x lt REG_FILE r0 ENDM List F 16 The list of save restore mac a MOTOROLA DSP56KCC User s Manual F 43 pe
312. ns gt 1 second column if it exists col 40 row 6 for i col len i lt options i row cur pos row col putc char A i putstr putstr menu i 1 cur_pos row 40 else cur pos row col putc char A options display exit option putstr putstr EXIT show status Displays the current setting next to the corresponding main menu option void show status ee MOTOROLA DSP56KCC User s Manual F 19 extern void cur pos extern void putstr extern void putint extern int status int row col row 6 col 40 Screen attr REVERSE display settings in inverse mode cur pos row col show inputs setting if status INPUTS putstr ON else putstr OFF cur pos row col show effects setting if status EFFECTS putstr ON else putstr OFF cur pos row col display volume putint status VOLUME DEC cur pos row col display model name from list putstr model menu status MODEL in model menu cur pos row col display filter type from list putstr 1pf_menu status FILTER in lpf menu cur_pos row col display mute setting if status MUTE putstr ON else putstr OFF Screen attr NORMAL back to normal text inputs on off Toggle interrupts on and off by setting the interrupt pri
313. nts A breakpoint makes your program stop whenever a certain point in the program is q _ Q _ ___ ee E 26 DSP56KCC User s Manual MOTOROLA reached You set breakpoints explicitly with GDB commands specifying the place where the program should stop by line number function name or exact address in the program You can add various other conditions to control whether the program will stop Each breakpoint is assigned a number when it is created these numbers are successive integers starting with 1 In many of the commands for controlling various features of breakpoints you use the breakpoint number to say which breakpoint you want to change Each breakpoint may be enabled or disabled if disabled it has no effect on the program until you enable it again The command info break prints a list of all breakpoints set and not deleted showing their numbers where in the program they are and any special features in use for them Disabled breakpoints are included in the list but marked as disabled info break with a breakpoint number as argument lists only that breakpoint The convenience variable _ and the default examining address for the x command are set to the address of the last breakpoint listed see section Memory 3 10 1 Setting Breakpoints Breakpoints are set with the break command abbreviated b You have several ways to say where the breakpoint should go break function Set a breakpoint at entry to
314. nts to standard output 2 chars packed wide 000000 3 chars packed wide 616263 2 chars packed wide 006162 aeaeo A 80 DSP56KCC User s Manual MOTOROLA memchr memchr NAME memchr Find a character in a memory area SYNOPSIS include lt string h gt int memchr const void s int c size t n DESCRIPTION The memchr function finds the first occurrence of c converted to an unsigned char in the memory area pointed to by s The terminating null character is considered to be part of the string The memchr function returns a pointer to the located char or a NULL pointer if the character is not found SEE ALSO strchr Find the first occurrence of a character in a string strcspn Compute the length of the prefix of a string not containing any characters contained in another string strpbrk Find the first occurrence of a character from one string in another string strrchr Find the last occurrence of a character in a string strspn Compute the length of the prefix of a string contained in another string SPECIAL NOTE Due to the word orientation of the DSP56000 DSP56001 there is no way to accurately implement an ANSI version of memchr for the memory model r O MOTOROLA DSP56KCC User s Manual A 81 memchr memchr EXAMPLE include lt stdio h gt include lt string h gt void main char string fred flintstone driving on bald feet cha
315. nual MOTOROLA Table of Contents Continued Paragraph Page Number Title Number Dr BuB Electronic Bulletin BOatd os qt A a D 5 A Ie o C E opo ECCO OO PERIERE D 6 Codec Routines ie nra Isi stessa cere afm aa D 6 DIME RO INES Mijn rrr e Se psu pua E de Ie tac seen detis D 6 Fast Fourier Transforms I soe Seco cd Coo twn Pes MESS T PON D 7 Filters a au Coreen ea Alt OU Datei Ln ter i Sd car a uda D 8 Floating Point HOS eri a uhr or sustento trud daos rare Ord ecd D 9 EDI A tede d ROS RR S Ie X rae USE eR qc No ones bdo Mee da D 10 Lattice Filters 24 252 ut ee thet eee asar RE EN D 10 Matrix Operatoria des o A rapa reos o E reae Flap ee D 11 Reed Solomon Encoder s voee miu e ODE A D 11 Sorting Routines zu 26 50 62 erg is gae det dy thud ed acheter ae D 11 A KC PMID D 12 Standard TO EgHal855 adir racc O Reuse E eee uie o M a te dde D 12 Tools and WU pL EE D 12 The following is a list of current DSP56200 related software D 13 Motorola DSP NewS gt cas Deer coro ae ei tee le oe oido ene D 13 Motorola Field Application Engineers llle D 13 Design Hotline 1 800 521 6274 0 0 cee D 13 DSP Applications Helpline 512 891 3230 0 0002 eee D 13 DSP Marketing Information 512 891 2030 Llllslsslllssss D 13 DSP Third Party Support Information 512 891 3098 D 14 DSP University Support 512 891 3098 0 0 cc ee D 14 DSP Tr
316. nversion specifying portions of format are sent directly to the standard output If the number of arguments passed is less than specified by the format string printf will write non deterministic garbage to the standard output If too many arguments are provided to printf the extras will be evaluated but otherwise ignored A conversion specification is introduced by the character and has the following form 9e flags field width precision size conversion character where flags field width precision h L are optional Flags are for justification of output and printing of signs blanks decimal points octal and hexadecimal prefixes Multiple flags may be utilized at once The ANSI flags are Left justify the result within the field The default is right justified The result of a signed conversion will always have a sign or The default case provides only for space If the first character of a signed conversion is not a sign or if a signed conversion results in no characters a space character will be prefixed to the result If the space and the flags both appear the space flag is ignored The default mode is no space The result is converted to an alternate form specified by the conversion character For o conversion it forces the first digit of the result to be a zero For x or X conversion the non zero result will have Ox 0X prefixed to it For e E f g and G conversions the result will always con
317. o defer delay restoring the stack pointer upon the return of a function call The purpose of deferring restoration of the stack pointer is to reduce code size and decrease execution time however the stack penetration may increase see the DSP56000 Family Manual for information on stack overflow Examples of function calls that will not incur deferred pops whether or not the fno defer pop option is specified are calls as function arguments _ _ _____ a A MOTOROLA DSP56KCC User s Manual 3 19 Compile Phase Options calls in conditional expressions calls inside a statement expression fforce addr Force memory address constants to be copied into registers before doing arithmetic on them The code generated with this option may be better or it may be worse de pending on the source code This option forces memory addresses into registers which in turn may be handled as common sub expressions finline functions Attempt to insert all simple functions in line into their callers The compiler heuristi cally decides which functions are simple enough to merit this form of integration If all calls to a given function are inserted and the function is declared static then the function is no longer needed as a separate function and normally is not output as a separate function in assembly code fcaller saves Enable values to be allocated in registers that will be overwritten by function calls by emitting extra instr
318. o h gt include lt string h gt void main char s is your name michael diamond printf strlen s d n s strlen s prints to standard output strlen is your name michael diamond 29 ee ae M MOTOROLA DSP56KCC User s Manual A 131 strncat strncat NAME strncat Concatenate a portion of one string to another SYNOPSIS include lt string h gt char strncat char s1 const char s2 size_tn DESCRIPTION The strncat function appends at most n characters from the string pointed by s2 to the end of the string pointed to by s1 The first character of the second string is written over the first strings terminating character and a new terminating character is appended The strncat function returns a pointer to s1 If s1 does not have n words allocated past the terminating character the behavior is undefined SEE ALSO strcat Concatenate one string to another EXAMPLE include lt stdio h gt include lt string h gt void main char bstr 80 string 1 char sstr 20 string 2 printf paste 5 chars of s on to s n sstr bstr void strncat bstr sstr 5 puts bigstr prints to standard output paste 5 chars of string 2 on to string 1 string 1 stri eS A A AAA A 132 DSP56KCC User s Manual MOTOROLA strncmp strncmp NAME strncmp Compare a portions of two strings SYNOPSIS include lt string h gt int strncmp const char s1 cons
319. o h gt char fgets char s int n FILE stream DESCRIPTION The function fgets will read at most n 1 characters from the specified stream fgets will not read past a newline character The characters are stored in memory starting at the location pointed to by s fgets returns s if it was successful NULL otherwise fgets will update the file position indicator for any characters read SEE ALSO fputs Write a string to a stream rewind Reset the file position indicator associated with a stream to the beginning of the file EXAMPLE include lt stdio h gt void main FILE disk_file fopen newfile a char one_line 64 fputs read this line n but not this line n disk_file rewind disk_file fgets one line 64 disk file fputs one line stdout will open a new file on the disk named newfile Two lines will be written to the new file and the first line will be read back using fgets The retrieved line is then printed to standard output as follows read this line ______ _ _________ A 1 MOTOROLA DSP56KCC User s Manual A 35 floor floor NAME floor Floor function SYNOPSIS include lt math h gt double floor double x DESCRIPTION The floor function returns the largest integer not greater than x When the header file math h is included the default case will be in line see section A 3 Forcing
320. o ooooooo 6 12 6 6 2 The Host Side I O Driver ooooooooooooornroonon 6 13 6 6 3 Communication between the Host and DSP 6 13 ____ __ __ gt _ ______ ________ __ 22 MOTOROLA DSP56KCC User s Manual iil Table of Contents Continued Paragraph Page Number Title Number Appendix A Programming Support A 1 Standard ANSI Header FileS 20 000 eee ees A 1 A 2 ANSI C Library Sub roUtiNeS oooooccoocccccr ee A 1 A 2 1 Hosted vs Non Hosted Library Routines A 2 A 3 Forcing Library Routines Out of line o ooooooocooooooooo A 2 A 4 Funcion DescripllODS sisas bed bees P a A 3 Appendix B DSP56000 DSP56001 Instruction Set and Assembler Directive Summary B 1 OVErVIEW are eaei e A RS Ad we Yeo oe ates B 1 B 2 ASTUCIA ot da REO B 1 B 2 1 Arithmetic Instructions ute Ai B 1 B 2 2 Logical ASTUCIA ia B 2 B 2 3 Bit Manipulation Instructions s sue is es B 2 B 2 4 koop INSHUCHONS 33 3 6 ee d ex ture ta Tee Eti B 3 B 2 5 Move INSTRUCTIONS qo poss aa era ado la ee Le eis eruta E B 3 B 2 6 Program Control Instructions cirio qc e re A eta eee B 3 B 3 Directive Summary 20 ccc desde qx EE EPOR RENE B 4 B 3 1 Assembly Control 224325 25r RESRDSREERRD ESSO SERIE ead B 4 B 3 2 Symbol Definition ms uso oorr seals coreg eae ios te OE memes B 4 B 3 3 Data Definition Storage Allocati0N oooooooooooooo B 5 B 3 4 Listing Control and Options
321. ocate and deallocate the stack at run time In the prologue an extra step is required to save the run time stack space Keeping in mind that the stack pointer must always point to the next available stack location the stack space is allocated by advancing the stack pointer by the amount of space required One way to allocate this space is shown in the Example 5 35 Example 5 35 Run time stack allocation This code segment can be inserted in the general template prologue for out of line assembly code Notice that size in the move statement below should be replaced with the appropriate constant move size n6 the stack size needed nop wait until n6 is available to operate on r6 move r6 n6 allocate the run time stack for locals Referencing the data space can then be accomplished using negative offsets from the stack pointer or via initialized address registers There are many alternatives to these methods but they are all similar In the epilogue an extra step is required to restore the stack pointer i e deallocate the run time local stack This is simply the reverse of the allocation process in the pro logue Example 5 36 Run time stack deallocation This code segment can be inserted in the general template epilogue for out of line assembly EEE 5 34 DSP56KCC User s Manual MOTOROLA code Notice that size in the move statement below should be replaced with the appropriate constant move size n6 the stack
322. ogram you run under GDB does input and output to the same terminal that GDB uses You can redirect the program s input and or output using sh style redirection commands in the run command For example run gt outfile starts the program diverting its output to the file outfile Another way to specify where the program should do input and output is with the tty command This command accepts a file name as argument and causes this file to be the default for future run commands It also resets the controlling terminal for the child pro EES MOTOROLA DSP56KCC User s Manual E 21 cess for future run commands For example tty dev ttyb directs that processes started with subsequent run commands default to do input and output on the terminal dev ttyb and have that as their controlling terminal An explicit redirection in run overrides the tty command s effect on input output redirec tion but not its effect on the controlling terminal When you use the tty command or redirect input in the run command only the input for your program is affected The input for GDB still comes from your terminal 3 7 Debugging an Already Running Process Some operating systems allow GDB to debug an already running process that was start ed outside of GDB To do this you use the attach command instead of the run com mand The attach command requires one argument which
323. ompilation Some options described only make sense when used in com bination with the E option preprocess only as the requested preprocessor output may be unsuitable for actual compilation The default option is to use ANSI C syntax For ex ample if the IDIR option is not specified then ANSI specifies that the current working di rectory will be searched first for user defined include files AAA AAA A A A AAA A l O MOTOROLA DSP56KCC User s Manual 3 5 Preprocessor Phase Options C Tell the preprocessor not to discard comments This option is only valid when used in conjunction with the E option Example 3 8 This example preprocesses a simple program foo c without discarding comments C gt type foo E This COMMENT won t be deleted main printf Hello DSP56000 n C gt g56k E C foo c it 1 foo c This COMMENT won t be deleted main printf Hello DSP56000 n pe eO O 3 6 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options DMACRO Define the preprocessor macro MACRO with a constant value of 1 This is equiva lent to making MACRO a constant set to one Example 3 9 Compile and run a simple program dsp c and enable or disable a printed message depending on the macro definition given at the command line C gt type dsp c include lt stdio h gt main ifdef DSP56000 printf message DSP56000 n else printf message DSP56001 An endif
324. on These things can be done with output formats The simplest use of output formats is to say how to print a value already computed This is done by starting the arguments of the print command with a slash and a format letter The format letters supported are Regard the bits of the value as an integer and print the integer in hexadecimal d Print as integer in signed decimal u Print as integer in unsigned decimal o Print as integer in octal a Print as an address both absolute in hex and then relative to a symbol defined as an address below it E 50 DSP56KCC User s Manual MOTOROLA c Regard as an integer and print it as a character constant P Regard the bits of the value as a floating point number and print using typical floating point syntax For example to print the program counter in hex see section Registers type p x pc Note that no space is required before the slash this is because command names in GDB cannot contain a slash To reprint the last value in the value history with a different format you can use the print command with just a format and no expression For example p x reprints the last value in hex 3 24 1 Examining Memory The command x for examine can be used to examine memory without reference to the program s data types The format in which you wish to examine memory is instead explicitly specified The allowable formats are a superset of the
325. on letters may be entered in either upper or low er case If no option is given the librarian operates as if the U option were specified b Use byte addressing when transferring load addresses to S record address es This means that load file DATA record start addresses are multiplied by the number of bytes per target DSP word and subsequent S1 S3 record ad dresses are computed based on the data byte count The b and w options are mutually exclusive l Use double word addressing when transferring load addresses from L space to S record addresses This means that load file DATA records for L space data are moved unchanged and subsequent S1 S3 record addresses are computed based on the data word count divided by 2 This option should always be used when the source load file contains DATA records in L mem ory space m Split each DSP word into bytes and store the bytes in parallel S records The m and s options are mutually exclusive r Write bytes high to low rather than low to high This option has no effect when used with the m option Aaaa C 20 DSP56KCC User s Manual MOTOROLA Ssrec Srec S Write data to a single file putting memory space information into the ad dress field of the SO header record The m and s options are mutually ex clusive W Use word addressing when transferring load addresses to S record ad dresses This means that load file DATA record start addresses are moved unchanged and subsequent S1
326. on of the user s single character response char prompt prompt_str char prompt_str t extern char getc extern void cur pos extern void putstr extern void clrend char c ee F 18 DSP56KCC User s Manual MOTOROLA cur_pos 24 1 position cursor at bottom of screen clrend clear the line to the end putstr prompt str display the prompt message c getc ECHO get the user s input return toupper c convert to upper case and return show menu Displays the options of the menu pointed to by the string pointer menu id the options parameter tells the function how many options are defined for the menu and the columns parameter indicates the number of columns into which the options are to be formatted void show_menu menu options columns char menu int options int columns extern void setscreen extern void putstr extern void putc extern void cur pos int i row col int col len setscreen SPACE clear the screen cur pos 1 5 putstr menu 0 display the menu title if options gt 12 force multiple columns for more than 12 options columns 2 col_len options columns options columns gt 0 1 0 col 5 row 6 for i 0 i lt col len i row first column cur_pos row col putc char A i putstr putstr menu i 1 if colum
327. on returns a nonzero value for any punctuation character zero is returned in the false case A punctuation character is one that is printable not a digit not a letter and not a space or t This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if ispunct printf space print character n if ispunct V printf tab not print character n prints to standard output space print character tab not print character AA _______ lt A M ES MOTOROLA DSP56KCC User s Manual A 63 isspace isspace NAME isspace Test for white space character SYNOPSIS include lt ctype h gt int isspace int c DESCRIPTION The isspace function returns a nonzero value for any standard white space character zero is returned in the false case The standard white space characters are space form feed P new line n carriage return r horizontal tab t and vertical tab v This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt includ
328. ond Edition Rafael C Gonzales and Paul Wintz Reading MA Addison Wesley Publishing Company Inc 1977 DIGITAL IMAGE PROCESSING TECHNIQUES M P Ekstrom New York NY Academic Press Inc 1984 DIGITAL PICTURE PROCESSING Azriel Rosenfeld and Avinash C Kak New York NY Academic Press Inc 1982 SCIENCE OF FRACTAL IMAGES THE M F Barnsley R L Devaney B B Mandelbrot H O Peitgen D Saupe and R F Voss New York NY Springer Verlag Motorola DSP Manuals MOTOROLA DSP56000 LINKER LIBRARIAN REFERENCE MANUAL Motorola Inc 1991 MOTOROLA DSP56000 MACRO ASSEMBLER REFERENCE MANUAL Motorola Inc 1991 MOTOROLA DSP56000 SIMULATOR REFERENCE MANUAL Motorola Inc 1991 MOTOROLA DSP56000 DSP56001 USER S MANUAL Motorola Inc 1990 Numerical Methods ALGORITHMS THE CONSTRUCTION PROOF AND ANALYSIS OF PROGRAMS P Berliout and P Bizard New York NY John Wiley and Sons 1986 MATRIX COMPUTATIONS G H Golub and C F Van Loan John Hopkins Press 1983 q __ _____________ A AAA MOTOROLA DSP56KCC User s Manual D 19 NUMERICAL RECIPES IN C THE ART OF SCIENTIFIC PROGRAMMING William H Press Brian P Flannery Saul A Teukolsky and William T Vetterling Cambridge University Press 1988 NUMBER THEORY IN SCIENCE AND COMMUNICATION Manfred R Schroeder New York NY Springer Verlag 1986 Pattern Recognition PATTERN CLASSIFICATION AND SCENE ANALYSIS R O Duda and P E Hart New York NY John
329. ons p 40 p 1000 p 1400 and p 1A00 respectively Notice that the corresponding data are located at the memory locations 10 3000 3300 and 3a00 The C compiler option j M project map creates the Memory Map File project map which describes the memory map for both data and program segments of the program Only the front portion of the Memory Map File is shown on page F 6 and the data sections v bles main c crtO menu c io scrn c and io vars and program sections vectors project main c crt0 menu C io sci c io scrn c io host c io atoi c and io ctype c are located according to the Memory Control File described in the DSP56001 CLAS package see the diagram on page F 6 ee ae M MOTOROLA DSP56KCC User s Manual F 3 F 3 List of Program Makefile This file is used by the MAKE command to create the file project lod which may be downloaded to a target board via a command converter and the ADS56001 software Compiler options all memory locations referenced by pointers are assumed to be volatile register R7 is fixed so that generated code will never refer to it R7 is used for servicing fast interrupts X memory is used for data rather than Y memory so that on chip peripherals may be accessed by the C code Assembler Options the linker is suppressed a cln file is output Link Options the linker is instructed to use the crt0 file ert0 cln rather than the standard library version the li
330. ontrol string to printer STITLE Initialize program sub title TITLE Initialize program title B 3 5 Object File Control The directives used to control the object file are COBJ Comment object code IDENT Object code identification record SYMOBJ Write symbol information to object file B 3 6 Macros and Conditional Assembly The directives used for macros and conditional assembly are DUP Duplicate a sequence of source lines DUPA Duplicate sequence with arguments DUPC Duplicate sequence with characters ENDIF End of conditional assembly ENDM End of macro definition EXITM Exit macro IF Conditional assembly directive MACLIB Macro library MACRO Macro definition PMACRO Purge a macro definition SSS MOTOROLA DSP56KCC User s Manual B 5 B 3 7 Structured Programming The directives used for structured programming are BREAK Exit from structured loop construct CONTINUE Continue next iteration of structured loop ELSE Perform following statements when IF false ENDF End of FOR loop ENDI End of IF condition ENDL End of hardware loop ENDW End of WHILE loop FOR Begin FOR loop AF Begin IF condition LOOP Begin hardware loop REPEAT Begin REPEAT loop UNTIL End of REPEAT loop WHILE Begin WHILE loop pe eO O B 6 DSP56KCC User s Manual MOTOROLA Appendix C Utilities There are nine utility programs availa
331. or durbin1 asm 3616 adpcm asm 1 0 32 kbits s CCITT ADPCM Speech Coder 120512 adpcm hlp 1 0 Help file for adpcm asm 14817 adpcmns asm 1 0 Nonstandard ADPCM source code 54733 adpcmns hlp 1 0 Help file for adpcmns asm 9952 Standard I O Equates ioequ asm 1 1 Motorola Standard I O Equate File 8774 ioequic asm 1 1 Lower Case Version of ioequ asm 8788 intequ asm 1 0 Standard Interrupt Equate File 1082 intequic asm 1 0 Lower Case Version of intequ asm 1082 Tools and Utilities srec c 4 10 Utility to convert DSP56000 OMF format 38975 to SREC srec doc 4 10 Manual page for srec c 7951 srec h 4 10 Include file for srec c 3472 srec exe 4 10 Srec executable for IBM PC 22065 sloader asm 1 1 Serial loader from the SCI port for the 3986 DSP56001 sloader hlp 1 1 Help for sloader asm 2598 sloader p 1 1 Serial loader s record file for download 736 to EPROM parity asm 1 0 Parity calculation of a 24 bit number in 1641 accumulator A parity hlp 1 0 Help for parity asm 936 parityt asm 1 0 Test program for parity asm 685 parityt hlp 1 0 Help for parityt asm 259 EEE Eee D 12 DSP56KCC User s Manual MOTOROLA Document ID Version Synopsis Size dspbug Ordering information for free debug 882 monitor for DSP56000 DSP56001 The following is a list of current DSP56200 related software p1 1 0 Information on 56200 Filter Software 6343 p2 1 0 Interrupt Driven Adaptive Filter Flowchart 10916 p3 1 0 C code implementation of p2 25795 p4 1 0
332. ority register of the DSP56001 The global variable interrupts on keeps track of the x status of the interrupts Interrupts are initially off void inputs on off if status INPUTS int_priority INT_DISABLE status INPUTS 0 else int_priority INT_ENABLE status INPUTS 1 effects_on_off Toggle the global flag _defeat to indicate whether special audio effects should be used or whether outputs should be the direct feed of the input void effects on off 1 extern int _defeat if _defeat 222 z _ _____ __________ _________22 2 2 F 20 DSP56KCC User s Manual MOTOROLA _defeat 0 status EFFECTS 1 turn effects on else defeat 1 status EFFECTS 0 turn effects off set_model Display a menu of special audio effects to the user and prompt for a selection Update model pointers and parameters used by the x Special Audio Effects interrupt subroutine to reflect the new model selection void set_model t extern void putc extern void putstr extern void cur pos extern void set delays void show menu char prompt char model int loop 1 show menu model menu 5 2 while loop cur pos 20 30 putstr Current model putstr model_menu status MODEL model prompt Select Model gt gt gt switch model case A set the spec
333. ork which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License The Program below refers to any such program or work and a work based on the Program means either the Program or any work containing the Program or a portion of it either verbatim or with modifications Each licensee is addressed as you 2 You may copy and distribute verbatim copies of the Program s source code as you receive it in any medium provided that you conspicuously and appropriately pub lish on each copy an appropriate copyright notice and disclaimer of warranty keep intact all the notices that refer to this General Public License and to the absence of any warranty and give any other recipients of the Program a copy of this General Public License along with the Program You may charge a fee for the physical act of transferring a copy 3 You may modify your copy or copies of the Program or any portion of it and copy and distribute such modifications under the terms of Paragraph 1 above provided that you also do the following e cause the modified files to carry prominent notices stating that you changed the files and the date of any change and e cause the whole of any work that you distribute or publish that in whole or in part contains the Program or any part thereof either with or without modifica tions to be licensed at no charge to all third parties under the terms of
334. ormation 512 891 3098 Information concerning third party manufacturers using and supporting Motorola DSP products is available by calling this number Third party support includes Filter design software Logic analyzer support Boards for VME IBM PC XT AT MACII SPARC HP300 Development systems Data conversion cards Operating system software Debug software Additional information is available on Dr BuB and in DSP News DSP University Support 512 891 3098 Information concerning university support programs and university discounts for all Motorola DSP products is available by calling this number DSP Training Courses 602 994 6900 There are two courses available for the DSP56000 Family 1 Introduction to the DSP56000 DSP56001 MTTA5 which is a 4 5 hour audio tape course on the DSP56000 DSP56001 architecture and programming 2 Introduction to the DSP56000 DSP56001 MTT31 which is a four day instructor led course and laboratory covering the details of the DSP56000 DSP56001 architecture and programming Additional information is available by writing Motorola SPS Training and Technical Operations Mail Drop HW68 P O Box 21007 Phoenix Arizona 85036 or by calling the number above A technical training catalog is available which describes these courses and gives the current training schedule and prices Reference Books and Manuals A list of DSP related books is included here as an aid for the engineer who is n
335. out fputc int n stdout Will cause the following output to be printed to standard output Shadrack eeaeee U OES MOTOROLA DSP56KCC User s Manual A 41 fputs fputs NAME fputs Write a string to a stream SYNOPSIS include lt stdio h gt int fputs const char s FILE stream DESCRIPTION The function fputc writes the string s to the specified stream The trailing O in s is not written to the stream EXAMPLE include lt stdio h gt void main fputs hand me down pumas n stdout Will cause the following output to be printed to standard output hand me down pumas pe eee O A 42 DSP56KCC User s Manual MOTOROLA fread fread NAME fread Read data directly from a stream SYNOPSIS include lt stdio h gt size_t fread void ptr size_t size size_t nmemb FILE stream DESCRIPTION The function fread reads raw data from the specified stream The data is stored in memory starting with the location pointed to by ptr The quantity of data is size nmemb fread returns the number of elements successfully read SEE ALSO printf Used to write formatted output to a standard output fopen Open a file and associate it with a stream EXAMPLE Assume that the disk file professor has as its contents the following string including the trailing O What s another word for pirate treasure The following C program uses fread include lt stdio h
336. pe sequences that you can use in the string are the simple ones that consist of backslash followed by a letter r A A MM MOTOROLA DSP56KCC User s Manual E 67 A _ EEE A mm A A A A A A A H E 68 DSP56KCC User s Manual MOTOROLA D 12 Options and Arguments for GDB When you invoke GDB you can specify arguments telling it what files to operate on and what other things to do 3 36 Mode Options NX Do not execute commands from the init files gdbinit Normally the com mands in these files are executed after all the command options and argu ments have been processed See section Command Files gq Quiet Do not print the usual introductory messages batch Run in batch mode Exit with code 0 after processing all the command files specified with x and gdbinit if not inhibited Exit with nonzero status if an error occurs in executing the GDB commands in the command files fullname This option is used when Emacs runs GDB as a subprocess It tells GDB to output the full file name and line number in a standard recognizable fash ion each time a stack frame is displayed which includes each time the pro gram stops This recognizable format looks like two 032 characters followed by the file name line number and character position separated by colons and a newline The Emacs to GDB interface program uses the two 032 characters as a signal to display
337. point constant description zero is returned If base is between 2 and 36 the expected form of the long integer subject is a sequence of letters and digits with the radix specified by base The letters a or A through z or Z are ascribed values 10 to 35 only letters whose value is less than base are valid If base is 16 Ox or OX may optionally proceed the long integer subject If base is zero the long integer subject determines its own base Leading Ox or OX base 16 Leading 0 base 8 otherwise base 10 If the value of the return value is too large to be expressed by a long int errno is set to ERANGE and LONG MAX is returned SEE ALSO atof String to double atoi String to integer atol String to long integer strtod String to double strtoul String to unsigned long integer GE MOTOROLA DSP56KCC User s Manual A 143 strtol strtol EXAMPLE include lt stdio h gt include lt string h gt void main char hexstr Oxabcdef709hexstr stopped char decstr 709709709decstr stopped char octstr 012341234octstr stopped char stopped long result printf result t tstop string Wn result strtol hexstr amp stopped 16 printf lx t t s result stopped result strtol decstr amp stopped 10 printf Y ld t t s result stopped result strtol octstr amp stopped 8 printf lo t t s result stopped prints to standard output result stop
338. pproximation exp2 hlp Help for exp2 asm 759 exp2t asm 1 0 Test program for exp2 asm 1019 sqrt1 asm 1 0 Square Root by polynomial 991 approximation 7 bit accuracy sqrt1 hlp Help for sqrt1 asm 779 sqrtit asm 1 0 Test program for sqrt1 asm 1065 sqrt2 asm 1 0 Square Root by polynomial 899 approximation 10 bit accuracy sqrt2 hlp Help for sqrt2 asm 776 sqrt2t asm 1 0 Test program for sqrt2 asm 1031 sqrt3 asm 1 0 Full precision Square Root Macro 1388 sqrt3 hlp Help for sqrt3 asm 794 sqrt3t asm 1 0 Test program for sqrt3 asm 1053 tli asm 1 1 Linear table lookup interpolation 3253 routine for function generation tli hlp 1 1 Help for tli asm 1510 bingray asm 1 0 Binary to Gray code conversion macro 601 bingrayt asm 1 0 Test program for bingray asm 991 rand1 asm 1 1 Pseudo Random Sequence Generator 2446 rand1 hlp Help for rand1 asm 704 Lattice Filters latfir1 asm 1 0 Lattice FIR Filter Macro 1156 latfir1 hlp Help for latfir1 asm 6327 latfir1t asm 1 0 Test program for latfirt asm 1424 latfir2 asm 1 0 Lattice FIR Filter Macro 1174 modified modulo count latfir2 hlp Help for latfir2 asm 1295 latfir2t asm 1 0 Test program for latfir2 asm 1423 TF A D 10 MOTOROLA Document ID Version Synopsis Size latiir asm 1 0 Lattice IIR Filter Macro 1257 latiir hlp Help for latiir asm 6402 latiirt asm 1 0 Test program for latiir asm 1407 latgen asm 1 0 Generalized Lattice FIR IIR 1334 Filter Macro latgen hlp Help for latgen asm 5485
339. pres sions For example print x 4 would store the value 4 into the variable x and then print the value of the assignment ex pression which is 4 All the assignment operators of C are supported including the incrementation operators and and combining assignments such as and lt lt If you are not interested in seeing the value of the assignment use the set command in stead of the print command set is really the same as print except that the expression s value is not printed and is not put in the value history see section Value History The ex pression is evaluated only for side effects Note that if the beginning of the argument string of the set command appears identical to a set sub command it may be necessary to use the set variable command This command is identical to set except for its lack of sub commands GDB allows more implicit conversions in assignments than C does you can freely store an integer value into a pointer variable or vice versa and any structure can be converted to any other structure that is the same length or shorter To store values into arbitrary places in memory use the construct to generate a val a ee MOTOROLA DSP56KCC User s Manual E 61 ue of specified type at a specified address see section Expressions For example int Ox83040 would refer to memory location 0x83040 as an integer which imp
340. printf big d n greater 10 20 C gt type greater h define greater x y x y x y C gt g56k M big c big o big c dsp include stdio h dsp include ioprim h dsp in clude stdarg h greater h MM Like M but the output mentions only the header files described in the include FILE directive System header files included with include lt FILE gt are omitted MM implies E with makefile rules eee 3 14 DSP56KCC User s Manual MOTOROLA Preprocessor Phase Options Example 3 17 The program big c which prints the larger of two integers uses the macro greater x y defined in the file greater h The MM option is used to generate a makefile rule Notice that the rule that generates an output file appended by o can be modified to generate cld which is required for the Motorola Cross C Compiler C gt dir big c greater h C gt type big c include lt stdio h gt include greater h main printf big d n greater 10 20 C gt type greater h define greater x y x y x y C gt g56k MM big c big o big c greater h ap th a big c greater h makefile text C gt type makefile a cld big o g56k big o big o big c greater h g56k c o big o big c C gt make g56k c o big o big c g56k big o CNS Euubo us cia big 20 nostdinc Do not search the standard system directories for file inclusions Only the directo ries specified with I options a
341. ptr a X1 X0 yO r1 r4 5 2 4 In line Assembly Code Examples The examples in this section illustrate the practical application of the _ asm extension The main purpose of this section is to show how to write in line assembly code Since these examples are intended to illustrate the information presented earlier in this chapter references to the appropriate subjects have been included Example 5 2 illustrates the use of the in line assembly code instruction_template Since this in line assembly code directly clears register A the programmer should check to be sure that the contents of A are not needed e 5 8 DSP56KCC User s Manual MOTOROLA Example 5 2 Instruction template The following are a few examples of how to utilize the instruction template in in line assembly code This feature allows the generation of any valid assembly instruction and it is probably the most frequently used feature in in line assembly coding asm clr a clears the register A __asm move 10 a2 load the register A2 with the hex value 10 __asm HCR EQU FFE8 equate the Host Control Register to FFE8 A pseudo operand will be used to illustrate use of the OES operand id number The pseu do operand functions as an input or output operand Example 5 3 uses five pseudo oper ands V W X Y and Z each of which is referenced by operand ids 0 1 2 3 and 4 respectiv
342. py str short string printf sin string allocate space for 40 character string if str char realloc str 40 sizeof char NULL perror realloc test exit 9 strcat str becomes a long string printf sin str prints to standard output short string short string becomes a long string AAA AAA AA A A A A U E MOTOROLA DSP56KCC User s Manual A 105 remove remove NAME remove Remove a file from the disk SYNOPSIS include lt stdio h gt int remove char filename DESCRIPTION The function remove will eliminate the file associated with the specified filename The effect of this call on open files may vary from host to host and is considered undefined EXAMPLE include lt stdio h gt void main remove foo exe will remove the file foo exe on the disk if such a file exists pe eO O A 106 DSP56KCC User s Manual MOTOROLA rename rename NAME rename Rename a file on the disk SYNOPSIS include lt stdio h gt int rename const char old const char new DESCRIPTION The function rename disassociates the a disk file from the name old and associates it with the name new The behavior of this call is undefined if there already exists a file associated with the name new rename returns zero if it is successful If it fails the file remains associated with the old name and is not altered in any way EXAMPLE include lt
343. quires using the C subroutine calling convention see Section 4 8 and Section 5 4 4 and matching the C function labels The in line assembly directive __asm can be used as shown in Example 5 25 to change the C program la bels Example 5 25 Calling C from assembly This C subroutine called C_print c uses the standard C library routine printf to print the input argument as a string C gt type c_print c include lt stdio h gt int C print X asm print C printf char msg i printf s n msg Example 5 26 Calling C from assembly This assembly program called greeting asm prints the message greeting hello there on the screen It uses the C subroutine printf to print this message Notice that the assembly program name is Fmain because the control program g56k uses the default start up file crt056y cln and crt056y cln uses Fmain to start up the main program see MOTOROLA DSP56KCC User s Manual 5 17 Chapter 6 in this manual C gt type greeting asm section greeting org y LCO dc greeting hello there 00 org p global Fmain Fmain move _ ssh y r6 move r1 y r6 move LCO r1 move r1 y r6 jsr print move r6 move y r6 r1 move y r6 ssh rts endsec The following two command lines are used to test two programs c_print c and greeting asm C gt g56k greeting asm c_print c C run56 a cld 5 2 5 3 Referencing Assembly Global Variables from C
344. r sci gt clock 0x0040 divide clock by 64 to generate 9600 baud sci gt control 0x0302 asynchronous no parity one stop bit putstr SCI initialized for RS 232 communication with terminal putstr CRLF init_ssi initialize controller s SSI port to process CD data I O q _ _ _ ________ _ M MOTOROLA DSP56KCC User s Manual F 15 void init ssi t extern void putstr Ssi control A 0x4300 16 bit word length 4 words per frame don t care about internal clock ssi gt control_B OxBBO00 rcv interrupts enabled rcv amp xmit enabled network mode continuous clock synch rcv amp xmit 1 bit frame synch s MSB first external clock source putstr SSI initialized to receive and transmit CD data putstr CRLF init_project Initialize special audio effects i e no special audio effects zero volume x audio effect model to Effect2 and low pass filter 4KHz void init_project extern int _GAIN _defeat extern int _coef ptr _coef 4 initialization routine for the special audio effects project status EFFECTS 0 special effects off defeat 1 status VOLUME 0 set the volume zero GAIN VOL 0 status MODEL 5 set the audio effect to Effect2 _GAIN STAGE_1G 0x100000 required gains just example for the audio ffect Effect2 _GAIN STAGE_2G 0x2
345. r result locate the occurance of b result memchr string b strlen string printf s n result prints to standard output bald feet ee ae O A 82 DSP56KCC User s Manual MOTOROLA memcmp memcmp NAME memcmp Compare portion of two memory areas SYNOPSIS include lt string h gt int memcmp const void s1 const void s2 size t n DESCRIPTION The memcmp function compares the first n words of the object pointed to by s1 with the first n words of the object pointed to by s2 comparison is lexicographical The memcmp function returns zero if the two areas compared are equal a value greater than zero if s1 is greater or a value less than zero if s1 is smaller SEE ALSO strncmp Compare portion of two strings SPECIAL NOTE Due to the word orientation of the DSP56000 DSP56001 there is no way to accurately implement an ANSI version of memcmp for the memory model rn O MOTOROLA DSP56KCC User s Manual A 83 memcmp memcmp EXAMPLE include lt stdio h gt include lt string h gt struct test char cartoon 20 int value gi flintstones 709 g2 flintstones 709 93 jetsons 709 void main if memcmp amp g1 amp g2 sizeof struct test 0 printf error flintstones differ n else printf flintstones are flintstones n if m
346. r is the target execution device Several aspects of the default run time environment must be altered in order to adapt the compiler to work with a custom hardware configuration The files which are alterable are discussed and classified according to effect Aspects of the run time environment such as bootstrapping interrupts and memory management are addressed individually 6 2 Run Time Environment Specification Files The run time environment is specified by three assembly language files crt056 x y asm signal56 x y I asm and setjmp56 x y I asm where x y or denote the memory model see chapters 2 and 4 These files may need to be modified if the run time environment is to be customized The crto file contains parameters which specify the C bootstrap code memory configura tion memory management interrupt vectors and other miscellaneous code This file must be modified to match the software and hardware configuration because the memory con figuration and interrupt vectors are determined by the hardware The information in this manual on the crtO file applies to DSP56KCC Version g1 11 The crtO file may be different for other versions of this compiler The signal file which is equivalent to a hardware interrupt is implemented in the C environment The signal file contains the code and data structures used to implement the signal and raise library functions Changing this file is not recommended unless necessary since any cha
347. r program This information is found by GDB in the symbol table loaded by the symbol file com mandi it is inherent in the text of your program and does not change as the program exe cutes whatis exp Print the data type of expression exp exp is not actually evaluated and any side effecting operations such as assignments or function calls inside it do not take place See section Expressions whatis Print the data type of the last value in the value history info address symbol Describe where the data for symbol is stored For a register variable this says which register it is kept in For a non register local variable this prints the stack frame offset at which the variable is always stored Note the contrast with print amp symbol which does not work at all for a register variables and for a stack local variable prints the exact address of the current in stantiation of the variable ptype typename Print a description of data type typename typename may be the name of a type or for C code it may have the form struct struct tag union union tag or enum enum tag info sources Print the names of all source files in the program for which there is debugging in formation ss __ A MOTOROLA DSP56KCC User s Manual E 59 info functions Print the names and data types of all defined functions info functions regexp Print the names and data types of all defined functions whose names contain a
348. ral and float data types Warnings will not occur for structures unions or arrays even when they are in registers There may be no warning about a variable that is used only to compute a value that is never used because such computations may be deleted by data flow analy sis before the warnings are printed Spurious warnings may be avoided by declaring functions that do not return as volatile A nonvolatile automatic variable may be changed by a call to longjmp This warning also requires that the optimizer be invoked The compiler sees only the calls to setjmp It cannot know where longjmp will be called in fact a signal handler could call it at any point in the code As a result a warning may be issued even when there is no problem because longjmp cannot be called at the place which would cause a problem A function can return either with or without a value Falling off the end of the func tion body is considered returning without a value For example this function would evoke such a warning foo a if a gt 0 return a Spurious warnings can occur because GNU CC does not realize that certain func tions including abort and longjmp will never return An expression statement contains no side effects Example 3 27 Extra warning messages are wanted to help find potential problems in a test function foo which is programmed to return a value only if a 0 exc que foo c Caro type foo int
349. ration using the DSP56000 DSP56000 Family Differences Specific Requirements 1 Since the DSP56000 has three memory spaces it will sometimes be necessary to use one of the prefixes p x or y in front of an address in order to examine or modify the specific memory space The debugger symbol information already has the proper memory space designator accompanying each symbol address so symbolic names do not require a memory space prefix however addresses entered as numeric constants require the prefix for x or y memory P memory is the default 2 The gdb56 debugger operates with COFF format cld files generated by the DSP56000 COFF Assembler and Linker programs The gdb56 subdirectory m56kinc contains header files which define the COFF structures used by gdb56 as well as other device specific header files 3 The gdb56 evaluator and display routines have been enhanced to handle the 48 bit long values and special format floating point values used by the DSP56000 Pe ee MOTOROLA DSP56KCC User s Manual E 1 4 The simulation is able to halt at breakpoints without actually breaking the pipeline activity of the device and without actually inserting breakpoint code into the device memory As a result the simulator can maintain an accurate record of the device execution time regardless of the number of inserted breakpoints The cycle count is maintained in the variable cyc 5 The normal gdb program uses gdbin
350. rbolic cosine of x If the value of x is too large a range error occurs setting errno to ERANGE and causes cosh to return HUGE_VAL SEE ALSO sinh Hyperbolic sin tanh Hyperbolic tangent EXAMPLE include lt stdio h gt include lt math h gt void main printf cosh 3 1415 f n cosh 3 1415 prints to standard output cosh 3 1415 11 590883 pe aee O A 24 DSP56KCC User s Manual MOTOROLA div div NAME div integer division with remainder SYNOPSIS include lt stdlib h gt div_t div int numer int denom DESCRIPTION The div function computes the quotient and remainder of the division of the numerator numer by the denominator denom and returns them in a structure of type div_t If the result can not be represented the behavior is undefined SEE ALSO Idiv Long integer division with remainder EXAMPLE include lt stdio h gt include lt stdlib h gt void main div_t result int numer 709 denom 56 result div numer denom printf quotient d t result quot printf remainder d n result rem prints to standard output quotient 12remainder 37 AAA A A A A A U OEA MOTOROLA DSP56KCC User s Manual A 25 exit exit NAME exit Terminate program normally SYNOPSIS include lt stdlib h gt void exit int status DESCRIPTION The exit function causes normal program termination to occur Any functions registered with
351. reate a temporary file EXAMPLE include lt stdio h gt void main char peek getchar putchar peek ungetc peek stdin putchar getchar will print the first character from standard input twice on standard output A AAA AAA AAA A O A 154 DSP56KCC User s Manual MOTOROLA v printf v printf NAME vfprintf Write formatted output to a stream using a va_list SYNOPSIS include lt stdio h gt int vfprintf FILE stream const char format va_list arg DESCRIPTION The function vfprintf is exactly the same as the function fprintf except that an existing va_list is used in place of a series of arguments The macro va_start must have been invoked on the argument arg before the call to vfprintf is made vfprintf returns the number of characters printed On error vfprintf returns a negative value SEE ALSO fprintf Write formatted output to a stream EXAMPLE include lt stdio h gt int printf const char format va_list ap int result va_start ap format result vfprintf stdout format ap va_end ap return result is essentially the library function printf AAA AAA A A A A A U EA MOTOROLA DSP56KCC User s Manual A 155 vprintf vprintf NAME vprintf Write formatted output to standard output using a va_list SYNOPSIS include lt stdio h gt int vprintf const char format va_list arg DESCRIPTION The function vprintf is exactly t
352. rface of the two possible target DSP s is assumed PBO PB7 lt gt H0 H7 PB8 PB10 lt gt HAO HA2 PB11 lt gt HR W PB12 lt gt RESET of both target DSP s PB13 lt gt HEN of target DSP 1 PB14 lt gt HEN of target DSP 0 Bit patterns and masks used to set control and address lines for the Host Interface registers are defined in the file globals h Note Each routine is responsible for configuring port B the way it needs it no assumptions are made about the configuration at the beginning of the routine 3b OR HHH include globals h see page F 11 B config in void B config in 1 ports gt B_direction OxFF00 low bits are input high bits are output B config out Configure the low 8 bits of the B port for outputs NOTE This could be implemented as a MACRO to reduce overhead void B config out configure port B to write to target s host port t ports B direction OxFFFF all bits are output read hreg Return the value of the host port register specified by reg_addr on the DSP processor specified by target int read_hreg target reg_addr int target int reg_addr void B config in int status B config in configure port B for inputs ports B data READ BYTE amp target reg addr status ports B data amp OxOOFF ports B data LATCH DATA List F 10 The list of the
353. ri ena ind eere d E aaa A 66 OPIO lia 3 3 3 31 ali AAA ates oot de 3 3 3 31 Mel A Tcr 5 22 MERCI re rated um Satie eed 5 22 labe eL eu Dania Td A 67 IGGXD 2a e A ees A 68 O E0250 Lysis to Bde ate A 69 Es MERCEDE 4 15 MODA sidis etree setae ey 4 15 WIMPY DAs pos ene eh Gta S 4 15 NOG ie crt A ET A 70 o E A 71 OO DD 4 2 4 8 longimp 3 26 6 2 6 11 A 72 M M option pool EFE 3 3 3 14 MOGO ore nE ES se ke bie 3 23 Mallo qt tada 6 8 A 74 Mantissa s dato dd 4 6 map files coy lia e a 3 31 MAXMEM Susto e Sethe 2 3 MB CURMMAX ERE S A 160 MBIEN acosa EA A 75 MDSIOWES Cos ca adas at A 77 Ed G56KCC User s Manual mbtowC o A 79 memchr Nos opio eos at e ba A 81 Ine mie mpi orde o A 83 Hel tie Dy stescieckatide d E EO OR eda A 85 memmowve s e m eds A 86 A dd ct d cria a A 87 MINMEM oscars S EOD 2 3 ml memory option 3 3 3 23 3 24 MM option tenons 3 3 3 14 mno biv plus linv promotion option 3 3 3 23 mno do loop generation option 3 3 3 23 mno dsp optimization option 3 3 3 23 mod_ba Sessoms aati ue e esed 4 15 A meas O A 89 Modifier Registers 4 8 mp mem switchtable 3 23 mstack_check option 3 3 3 23 4 16 mx memory option 3 3 3 23 3 24 my memory option 3 3 3 23 3 24 N NaNS aia EROR EN Eh ed 4 7 nostdinc option s 3 2 520 ws 3 3 3 15 O option eren date RR Bad cod 3 3 3 23 0 OptION
354. rint ten more lines If the last lines printed were printed with a list command this prints ten lines following the last lines printed however if the last line printed was a solitary line printed as part of displaying a stack frame see section Stack this prints ten lines centered around that line list Print ten lines just before the lines last printed Repeating a list command with RET discards the argument so it is equivalent to typing just list This is more useful than listing the same lines again An exception is made for an argument of that argument is preserved in repetition so that each repetition moves up in the file In general the list command expects you to supply zero one or two linespecs EEE Se MOTOROLA DSP56KCC User s Manual E 43 Linespecs specify source lines there are several ways of writing them but the ef fect is always to specify some source line Here is a complete description of the possible arguments for list list linespec Print ten lines centered around the line specified by linespec list first last Print lines from first to last Both arguments are linespecs list last Print ten lines ending with last list first Print ten lines starting with first list Print ten lines just after the lines last printed list Print ten lines just before the lines last printed list As described in the preceding table Here are the ways of specifying
355. rol Register SSR ds 1 SCI Interface Status Register SCCR ds 1 SCI Control Register STXA ds 1 SCI Transmit Data Address Register SRX LO STX LO ds 1 SCI Low Rec Xmit Data Register SRX MID STX MID ds 1 SCI Mid Rec Xmit Data Register SRX HI STX HI ds 1 SCI Hi Rec Xmit Data Register ds 1 ds 1 ds 1 ds 1 ds 1 ds 1 ds 1 BCR ds 1 Port A Bus Control Register IPR ds 1 Interrupt Priority Register endsec e F 40 DSP56KCC User s Manual MOTOROLA vectors asm function Define all interrupt vectors and fast interrupts memory P 00 3F comments replaces reset section of crt0 asm file section vectors org x xref RX TX org P 0000 xref F _start PROJECT RESET jmp F start STACK ERROR nop nop TRACE nop nop SWI INT nop nop IRQA move lt SSI_RCV_DO r7 jsr lt PROJECT IRQB nop nop SSI_RCV_INT movep x lt lt RX y r7 movep sy r7 x lt lt TX SSI RCV INT E movep x RX x r7 movep y r7 t x TX SSI XMT INT nop nop SSI XMT INT E nop nop SCI RCV INT nop nop SCI RCV INT E nop nop SCI XMT INT nop nop SCI IDLE INT nop nop SCI TIMER INT nop nop NMI INT nop nop HOST RCV INT nop nop HOST XMT INT nop nop HOST CMDO INT nop nop HOST CMD1 INT nop nop HOST CMD2 INT nop nop HOST CMD3 INT nop nop HOST CMDA4A INT nop nop HOST CMD5 INT nop List F 15 The list of vectors asm MOTOROLA DSP56KCC User s Manual F 41 nop HOST_CMD6_INT nop
356. rom its superior GDB provides ways to specify this information which you must do before starting the program You can change it after starting the program but such changes do not affect the program unless you start it over again This information may be divided into three categories The arguments You specify the arguments to give the program as the arguments of the run com mand The environment The program normally inherits its environment from GDB but you can use the GDB commands set environment and unset environment to change parts of the environment that will be given to the program The working directory The program inherits its working directory from GDB You can set GDB s working directory with the cd command in GDB After the run command the debugger does nothing but wait for your program to stop See section Stopping A AA A AAA A A A A A A A MM MOTOROLA DSP56KCC User s Manual E 19 Note that once your program has been started by the run command you may evaluate expressions that involve calls to functions in the inferior See section Ex pressions If you wish to evaluate a function simply for its side affects you may use the set command See section Assignment 3 3 Your Program s Arguments The arguments to your program are specified by the arguments of the run command They are passed to a shell which expands wildcard characters and performs redirection of I O
357. rrently implemented 6 4 4 Signal The signal function is passed two arguments 1 A signal number On the DSP56000 family processor the signal number corre sponds directly to the interrupt vector address Notice that the signal number is not an integer sequence but is an even number 2 A function pointer The function pointer passed is assumed to belong to a C function either generated by this compiler or by assembly code Signal performs the following three steps when binding the specified signal number and function 1 The instruction jsr F c sig goto_dispatch lt signal numbers is placed into the interrupt table location specified by the signal number _ ______ gt gt gt oH MOTOROLA DSP56KCC User s Manual 6 9 2 The function pointer passed is entered into the table c sig handlers which is used to store pointers to C signal handlers indexed by the signal number 3 The old signal handler address is returned Once the signal number and specified function are bound the instruction jsr F c sig goto dispatch signal numbers is executed upon receiving the interrupt where the F c sig goto dispatch variable is the starting address of a table of jsr F c sig dispatch instructions and each jsr instruction points to an interrupt service routine The pseudo function _ c sig dispatch is used to calculate the actual C interrupt routine
358. rrupt08 jsr interrupt3e endsec Example 6 6 Interrupt Service Routine This service routine updates the global variable F__ time at each SCI timer interrupt The SCI timer period can be set by programming the SCCR see Section 11 2 2 3 of the DSP56000 DSP56001 User s Manual This program is based on the y memory model and the SCI interface control registers X FFFO and X FFF2 should be initialized for proper SCI timer operation see Section 11 2 in the DSP56000 DSP56001 User s Manual for detailed information on the SCI operation section interrupt org p global interruptic YS MOTOROLA DSP56KCC User s Manual 6 7 interruptic move r6 secure the stack pointer refer to section 5 4 1 4 move r2 y r6 save the r2 register move y F__time r2 retrieve the variable time move r2 increment the variable move r2 y F__ time save the result move y r6 r2 restore the r2 register rti return from interrupt service endsec Notice that fast interrupts can also be programmed by modifying the erto file in the same way as for the long interrupts see Chapter 8 of the DSP56000 DSP56001 User s Manual for more information on fast and long interrupts 6 3 4 Miscellaneous Code There are other data structures and code related to the run time environment in the crtO file They are 1 Error code variable errno is a global integer used to record failure codes in C li brary calls This error code variable will ex
359. rted inside a C statement in a C source file Since assembly code is generated from this C statement directly the C state ment looks like assembly code in the C source and is referred to as in line assembly code All of the assembly code to be generated is visible at the C source level and it is of ten convenient to intermix assembly code with a C source program in this fashion Typically in line assembly code is used when D MOTOROLA DSP56KCC User s Manual 5 1 1 inserting a small amount of assembly code directly into the compiler output i e in ner loop kernels 2 writing fast assembly language routines to be called by C subroutines This elimi nates the need to manage data referencing register saving and allocation and function call return overhead The key word _ asm is introduced as an extension to the ANSI C language standard and this key word is used like a function call to specify the in line assembly code genera tion rule discussed below The in line assembly statement syntax is asm instruction template output operands input _operands reg save where 1 instruction template is a string used to describe a sequence of assembly code instructions that are to be inserted into the compiler output stream It may specify arguments which are listed in output operands and input operands It does this via a substring called an operand expansion string OES An OES starts with a OES and instruction template int
360. ry spaces A way to restrict the linker from overlap ping these memory spaces is needed For example suppose that both the Y and P spaces are mapped into the same 64k physical RAM and need to be partitioned with the low 48k for program memory and the high 16k for data memory The linker can be restricted from allocating across holes in physical memory by using the org and ds directives to confiscate those addresses Note that the linker may not auto matically take advantage of memory which is present between holes It may be required to manually place assembly language data structures to utilize this memory 6 3 3 Interrupt Vectors The interrupt vector locations for the DSP56000 family a k a interrupt source in Section 8 of the DSP56000 DSP56001 User s Manual contain one or two instructions each to be executed when the interrupt assigned to that location occurs There are 32 interrupt vec tors available all of which should be initialized with some value to avoid undefined behav ior resulting from an unexpected interrupt The crto file contains code to initialize these interrupt vectors By default all vectors are initialized with the instruction jsr Fabort The first element of the vector table which is the hardware RESET interrupt is initialized with the instruction jmp F start The purpose of the C function abort which is labeled as Fabort in the assembly environment is to stop program execution and leave the chip in the STOP mo
361. s AAA _ A E 5 b b I l gt Q Pr Q gt AA MOTOROLA DSP56KCC User s Manual 4 9 Higher Memory register spill temp area local data return address ssh 1 word Stack Pointer R6 Frame Pointer RO old frame pointer 1 word Lower Memory Figure 4 3 Activation Record Note The Stack Pointer r6 points to the next available data memory location Each subroutine called puts a new copy of the subroutine activation record in the run time stack and returning from the subroutine removes the activation record The run time stack is described in Figure 4 4 Default Data Memory Configuration The variables shown in the bottom of the X or Y memory option selected memory are controlled by the crtO file For example the F fp shift variable is typically 23 words but can be changed by the user or may vary with later releases of this compiler When the L memory option is selected the heap run time stack global static data and data that is more than 24 bits in length will occupy one word in L memory i e 48 bit memory 16 bit and 24 bit data memory will occupy only one word in Y memory DSIZE is set by the linker and points to the top address of the global and static data DSIZE is used by the crtO file as the default initial stack pointer The dynamic run time stack growth is illustrated in Figure 4 5 In this example there is one activation record as execution of the sample C code begins This activation
362. s a1 a0 24 bits Accumulator Registers b2 8 bits b1 bO 24 bits Input Register x x1 x0 48 bits Input Register y y1 yO 48 bits Input Register a10 a1 a0 48 bits Input Register b10 b1 b0 48 bits Accumulator a a2 a1 a0 56 bits Accumulator b b2 b1 b0 56 bits Address ALU f Address Registers RO R7 16 bits nu Address Offset Registers NO N7 16 bits m Address Modifier Registers MO M7 16 bits Caution The m address modifier registers are not used directly by DSP56KCC Some of these registers are implied whenever any address registers rO r7 are referenced either in C library or in C While assembly code can access and use these registers the programmer must restore them to their previous state FFFF before returning control to DSP56KCC Failing to do so will cause unpredictable errors when DSP56KCC accesses these EEE MOTOROLA DSP56KCC User s Manual 4 7 registers The programmer is required to preserve any registers that are directly used in in line and in out of line assembly language code see Chapter 5 Mixing C and Assembly Language Table 4 9 outlines the compiler s usage of each register Table 4 9 DSP56KCC registers and Usage Register Usage Frame Pointer Stack Pointer Register promotion by the optimizer Code generator temporary Used by compiler keep this as F FFF 48 bit function return value float double or long 24 bit and 16 bit return value Integer or poin
363. s play of strings set prettyprint on Cause GDB to print structures in an indented format with one member per line like this 1 next 0x0 flags sweet 1 sour 1 h meat 0x54 Pork set prettyprint off Cause GDB to print structures in a compact format like this 1 next 0x0 flags sweet 1 sour 1 meat 0x54 Pork This is the default format set unionprint on Tell GDB to print unions which are contained in structures This is the default set ting MOTOROLA DSP56KCC User s Manual E 49 set unionprint off Tell GDB not to print unions which are contained in structures For example given the declarations typedef enum Tree Bug Species typedef enum Big_tree Acorn Seedling Tree_forms typedef enum Caterpiller Cocoon Butterfly Bug_forms struct thing Species it union Tree_forms tree Bug_forms bug form i struct thing foo Tree Acorn with set unionprint on in effect p foo would print 1 it Tree form tree Acorn bug Cocoon and with set unionprint off in effect it would print 1 it Tree form 3 24 Output formats GDB normally prints all values according to their data types Sometimes this is not what you want For example you might want to print a number in hex or a pointer in decimal Or you might want to view data in memory at a certain address as a character string or an instructi
364. s and contents saved are from the last memory unit printed this is not the same as the last address printed if several units were printed on the last line of output The specialized command disassemble is also provided to dump a range of memory as machine instructions The default memory range is the function surrounding the program counter of the selected frame A single argument to this command is a program counter value the function surrounding this value will be dumped Two arguments specify a range of address first inclusive second exclusive to be dumped 3 25 Automatic Display If you find that you want to print the value of an expression frequently to see how it changes you might want to add it to the automatic display list so that GDB will print its value each time the program stops Each expression added to the list is given a number to identify it to remove an expression from the list you specify that number The auto matic display looks like this 2 foo 38 3 bar 5 struct hack 0x3804 showing item numbers expressions and their current values gt _ _ _____ a 2222 zz AAA MOTOROLA DSP56KCC User s Manual E 53 If the expression refers to local variables then it does not make sense outside the lexical context for which it was set up Such an expression is printed only when execution is in side that lexical context For example if you give the command display name while in side a funct
365. s for alternate accessing of serial or host DMA ports ADM can be used in stand alone configuration No external power supply needed when connected to a host platform DSP56000ADSx Application Development System Software Features Single multiple stepping through DSP56000 DSP56001 object programs Up to 99 conditional or unconditional breakpoints Program patching using a single line assembler disassembler Session and or command logging for later reference Loading and saving files to from ADM memory Macro command definition and execution Display enable disable of registers and memory EES D 4 DSP56KCC User s Manual MOTOROLA Debug commands supporting multiple ADMs Hexadecimal decimal binary calculator Host operating system commands from within ADS user interface program e Multiple OS I O file access from DSP56000 DSP56001 object programs Fully compatible with the DSP56000CLASx design in software package On line help screens for each command and DSP56000 DSP56001 register Support Integrated Circuits 8Kx24 Static RAM e DSP56ADC16 16 bit 100 kHz analog to digital converter e DSP56401 AES EBU processor e DSP56200 FIR filter Dr BuB Electronic Bulletin Board Dr BuB is an electronic bulletin board providing free source code for a large variety of topics that can be used to develop applications with Motorola DSP products The software library includes files including FFTs FIR filters IIR filters l
366. s may be a macro getchar Read a character from the stream stdin this may be a macro gets Read a string from the stream stdin isalnum Test for alphanumeric character isalpha Test for alphabetic character iscntrl Test for control character isdigit Test for numeric character isgraph Test for printing character excluding space and tab islower Test for lower case alphabetic characters isprint Test for printing character excluding t ispunct Test for punctuation character isspace Test for white space character isupper Test for upper case alphabetic character isxdigit Test for hexadecimal numeric character labs Absolute value of a long integer Idexp Multiply floating point number by a power of two q U E A 4 DSP56KCC User s Manual MOTOROLA Idiv Long integer division with remainder log Natural logarithm base e log10 Base ten logarithm longjmp Execute a non local jump malloc Dynamically allocate uninitialized storage mblen Length of a multibyte character mbstowcs Convert multibyte string to wide character string mbtowc Convert a multibyte character to a wide character memchr Find a character in a memory area memcmp Compare portion of two memory areas memcpy Copy from one area to another memmove Copy from one area to another source and destination may overlap memset
367. s produced by the DSP assemblers generating an absolute load file which can be 1 loaded directly into the Motorola DSP simulator or 2 converted to Motorola S record format for PROM burning files is a list of operating system compatible file names including optional pathnames If no extension is supplied for a given file the linker will first at tempt to open the file using the file name as supplied If that is not success ful the linker appends cln to the file name and tries to open the file again If no pathname is supplied for a given file the linker will look for that file in the current directory The list of files will be processed sequentially in the order given and all files will be used to generate the load file and map listing Note that some options B and M allow a hyphen as an optional argu ment which indicates that the corresponding output should be sent to the standard output stream Unpredictable results may occur if for example the object file is explicitly routed to standard output while the listing file is al lowed to default to the same output stream OPTIONS Any of the following command line options may be specified These can be in any order but must precede the list of link file names except for the L option Option letters may be specified in either upper or lower case Option arguments may immediately follow the option letter or may be sepa rated from the option letter by blanks or tabs However an am
368. s the value of any valid expression of the language the program is written in for now C You type print exp where exp is any valid expression and the value of exp is printed in a format appropriate to its data type A more low level way of examining data is with the x command It examines data in memory at a specified address and prints it in a specified format 3 20 Expressions Many different GDB commands accept an expression and compute its value Any kind of constant variable or operator defined by the programming language you are using is le gal in an expression in GDB This includes conditional expressions function calls casts and string constants It unfortunately does not include symbols defined by preprocessor define commands Casts are supported in all languages not just in C because it is so useful to cast a num ber into a pointer so as to examine a structure at that address in memory GDB supports three kinds of operator in addition to those of programming languages is a binary operator for treating parts of memory as arrays See section Ar rays for more information allows you to specify a variable in terms of the file or function it is defined in See section Variables type addr Refers to an object of type type stored at address addr in memory addr may be any expression whose value is an integer or pointer but parentheses are re quired around non unary operators just as in a cast
369. same sign as x SEE ALSO exp Raising e to a power pow Raising a floating point number to a power EXAMPLE include lt stdio h gt include lt math h gt void main printf Idexp 7 09 4 f n Idexp 7 09 4 prints to standard output Idexp 7 09 4 113 440000 e AAA A A O A 68 DSP56KCC User s Manual MOTOROLA Idiv Idiv NAME Idiv Long integer division with remainder SYNOPSIS include lt stdlib h gt Idiv t Idiv long int numer long int denom DESCRIPTION The Idiv function computes the quotient and remainder of numer denom and returns the result in a structure of type Idiv t If the result cannot be represented the result is undefined SEE ALSO div Integer division with remainder EXAMPLE include lt stdio h gt include lt stdlib h gt void main Idiv_t result long numer 709 denom 56 result Idiv numer denom printf quotient ld t result quot printf remainder ld n result rem prints to standard output quotient 12remainder 37 AAA AAA A A A A A U OES MOTOROLA DSP56KCC User s Manual A 69 log log NAME log Natural logarithm base e SYNOPSIS include lt math h gt double log double x DESCRIPTION The log function computes the natural logarithm of x If the value of x is less than zero errno is set to EDOM and the value HUGE_VAL is returned If x is equal to zero errno is set to ERANGE and the value
370. ser s Manual D 17 ISSUES IN THE IMPLEMENTATION OF DIGITAL FEEDBACK COMPENSATORS P Moroney Cambridge MA The MIT Press 1983 Graphics CGM AND CGI D B Arnold and P R Bono New York NY Springer Verlag 1988 COMPUTER GRAPHICS Second Edition D Hearn and M Pauline Baker Englewood Cliffs NJ Prentice Hall Inc 1986 FUNDAMENTALS OF INTERACTIVE COMPUTER GRAPHICS J D Foley and A Van Dam Reading MA Addison Wesley Publishing Company Inc 1984 GEOMETRIC MODELING Michael E Morteson New York NY John Wiley and Sons Inc GKS THEORY AND PRACTICE P R Bono and Herman Eds New York NY Springer Verlag 1987 ILLUMINATION AND COLOR IN COMPUTER GENERATED IMAGERY Roy Hall New York NY Springer Verlag POSTSCRIPT LANGUAGE PROGRAM DESIGN Glenn C Reid Adobe Systems Inc Reading MA Addison Wesley Publishing Company Inc 1988 MICROCOMPUTER DISPLAYS GRAPHICS AND ANIMATION Bruce A Artwick Englewood Cliffs NJ Prentice Hall Inc 1985 PRINCIPLES OF INTERACTIVE COMPUTER GRAPHICS William M Newman and Roger F Sproull New York NY McGraw Hill Company Inc 1979 PROCEDURAL ELEMENTS FOR COMPUTER GRAPHICS David F Rogers New York NY McGraw Hill Company Inc 1985 RENDERMAN INTERFACE THE Pixar San Rafael CA 94901 oa E D 18 DSP56KCC User s Manual MOTOROLA Image Processing DIGITAL IMAGE PROCESSING William K Pratt New York NY John Wiley and Sons 1978 DIGITAL IMAGE PROCESSING Sec
371. set to EDOM and 0 0 is returned argument range output range y gt 0 0 x gt 0 0 0 0 7 2 y gt 0 0 x lt 0 0 1 2 n y lt 0 0 x lt 0 0 7 7 2 y lt 0 0 x2 0 0 1 2 0 0 SEE ALSO atan Arc tangent tan Tangent EXAMPLE include lt stdio h gt include lt math h gt void main printf atan2 7 09 7 09 f n atan2 7 09 7 09 printf atan2 7 09 7 09 f n atan2 7 09 7 09 printf atan2 7 09 7 09 f n atan2 7 09 7 09 printf atan2 7 09 7 09 f n atan2 7 09 7 09 prints to standard output atan2 7 09 7 09 785398 atan2 7 09 7 09 785398 atan2 7 09 7 09 2 356194 atan2 7 09 7 09 2 356194 A 12 DSP56KCC User s Manual MOTOROLA atexit atexit NAME atexit Register a function for execution at normal program termination SYNOPSIS include lt stdlib h gt int atexit void func void DESCRIPTION The atexit registers a function func that will be called at normal program execution The registered function is called without arguments and returns nothing A total of 32 functions may be registered and will be called in the order in which they were registered The atexit function returns zero if registration succeeds and a non zero value for failure SEE ALSO exit Terminate a program normally EXAMPLE include lt stdio h gt include lt stdlib h gt void main atexit func_1 atexit func_2
372. showing the values This includes disabled ex pressions which are marked as such It also includes expressions which would not be displayed right now because they refer to automatic variables not currently available A a A A AA AA A E 54 DSP56KCC User s Manual MOTOROLA 3 26 Value History Every value printed by the print command is saved for the entire session in GDB s value history so that you can refer to it in other expressions The values printed are given history numbers for you to refer to them by These are suc cessive integers starting with 1 print shows you the history number assigned to a value by printing num before the value here num is the history number To refer to any previous value use followed by the value s history number The output printed by print is designed to remind you of this Just refers to the most recent value in the history and refers to the value before that For example suppose you have just printed a pointer to a structure and want to see the contents of the structure It suffices to type p If you have a chain of structures where the component next points to the next one you can print the contents of the next one with this p next It might be useful to repeat this command many times by typing RET Note that the history records values not expressions If the value of x is 4 and you type this command print x set x 5 then the value recorde
373. splay and expanded on line help for simulator commands Loading and saving of files to from simulator memory Macro command definition and execution Display enable disable of registers and memory Hexadecimal decimal binary calculator _ _ M H M E MOTOROLA DSP56KCC User s Manual D 3 DSP320to56001 Translator DSP320to56001 Translator Features Translates any TMS32010 linked object code to DSP56001 source assembler code Two modes of operation Translates to DSP56001 source assembler code for optimization and assembly using DSP56000CLASx Translates and runs as is directly and immediately on the DSP56000ADSx e C language DSP320t056001 source code is provided in addition to IBM PC XT AT object code to allow User modification for TMS32020 or TMS320C25 translation User compilation to accommodate different host platforms DSP56000ADSx Application Development System DSP56000ADS Application Development System Hardware Features Full speed 27 MHz operation Multiple application development module ADM support with programmable ADM addresses 8Kx24 expandable to 32Kx24 user configurable RAM for DSP56000 DSP56001 code development e 1Kx24 monitor ROM expandable to 4Kx24 96 pin Euro card connector making all DSP56001 pins accessible In circuit emulation capabilities when used with the DSP56KEMULTRCABL cable Separate berg pin connector
374. sprintf s format ap va_end ap return result is essentially the library function sprintf AAA A A A A A UO H MOTOROLA DSP56KCC User s Manual A 157 wcstombs wcstombs NAME wcstombs Convert wchar_t array to multibyte string SYNOPSIS include lt stdlib h gt size t wcstombs char s const wchar_t pwcs size tn DESCRIPTION The wcstombs function converts a wide character string pointed to by pwcs into the character string pointed to by s Each character of the wide character string is converted into the corresponding multibyte character as if by the wctomb function Conversion will stop when n total characters have been converted or a null character is encountered If s and pwcs overlap the behavior is undefined If an invalid character is encountered wcstombs returns size t 1 Otherwise wcstombs returns the number of characters converted not including the terminating NULL character if any SEE ALSO mbtowcs Convert a multibyte string to a wchar t array SPECIAL NOTE The DSP56000 DSP56001 does not provide byte addressing thus characters always require an entire word of memory each One way to better utilize data memory with a run time cost is to combine the ANSI data type wchar t and the special ANSI multibyte and wide character library routines eee EEO O A 158 DSP56KCC User s Manual MOTOROLA wcstombs wcstombs EXAMPLE include lt stdio h gt include lt stdlib h gt char array 16
375. stdio h gt void main rename old exe new exe will rename the file old exe to new exe provided that old exe actually exists on the disk Note that old exe will cease to exist AAA A A A A A Moo MOTOROLA DSP56KCC User s Manual A 107 rewind rewind NAME rewind Reset the file position indicator to the beginning of the file SYNOPSIS include lt stdio h gt void rewind FILE stream DESCRIPTION The function rewind will reset the file position indicator associated with the specified stream Any pending error is also cleared SEE ALSO fgetpos Obtain the file position indicator value associated with a stream fsetpos Set the file position indicator value associated with a stream EXAMPLES include lt stdio h gt void main FILE preexisting fopen already here r putchar fgetc preexisting rewind preexisting putchar fgetc preexisting will print the first character in the file already here onto standard output twice pe aee O A 108 DSP56KCC User s Manual MOTOROLA scanf scanf NAME scanf Read formatted input from standard input SYNOPSIS Hinclude stdio h int scanf char format DESCRIPTION The function scanf is equivalent to the fscanf function except that input is always read from standard input Please use the description of argument values in the description of the fscanf fun
376. stem ADS Logic Analyzer with In Circuit Emulator DSP56000 DSP56001 ROM Packages Simulator Data Acquisition Cards DSP Development System Cards Application Specific Development Tools Debug Software AAA O O III MOTOROLA DSP56KCC User s Manual D 1 The following is a partial list of the support available for the DSP56000 DSP56001 Additional information can be obtained through Dr BuB or the appropriate support telephone service Motorola DSP Product Support e DSP56000CLASx Design In Software Package which includes Relocatable Macro Assembler Linker Simulator simulates single or multiple DSP56000 DSP56001s Librarian e 56KCCx Full ANSI Compliant C Compiler e DSP320to56001 Translator Software e DSP56000 DSP56001 Applications Development System ADS Support Integrated Circuits DSP Bulletin Board Dr BuB Motorola DSP Newsletter Motorola Technical Service Engineers TSEs See your local telephone directory for the Motorola Semiconductor Sector sales office telephone number Design Hotline Applications Assistance Marketing Information e Third Party Support Information University Support Information DSP56000CLASx Assembler Simulator The macro cross assembler and simulator run on 1 IBM PCs and clones using an 80386 or upward compatible processor 2 Macintosh computers with a NU BUS expansion port 3 SUN computer 4 NeXT computer Macro Cross Assembler Features Production of relocatab
377. store it in the ungetc buffer NOTE This could be implemented as a MACRO to reduce overhead void List F 8 The list of I O function io sci c EEE MOTOROLA DSP56KCC User s Manual F 25 ungetc c char c m putc x Output a character to the terminal through the SCI port void putc c send a character out the SCI port char c ungetcbuf c t int d for d 0 d 1000 d while sci gt status TX EMPTY wait for buffer to empty sci lo data c for d 0 d 1000 d putstr Output a string of characters to the screen though the SCI port void putstr str char str t void putc while str while character is not NULL print it out putc str putint Output the characters representing an integer x to the x screen through the SCI port The number is represented void putint x radix int x int radix void putc void putstr char itoa int i int remainder char string 25 allocate a buffer for the number if x 0 if zero output 0 and return putc 0 else putstr itoa x radix string else convert to string and print return getstr Get a string of characters from the keyboard through the x SCI port The string is ended by a carriage return or x when the number of characters specified by len is reached void getstr s len type f
378. successful completion printf returns the an integer equal to the number of characters printed On failure printf returns an integer less than O SEE ALSO scanf Read values from standard input sscanf Read values from a string sprintf Multiplying a number by a power of 2 AAA A A A A A M MOTOROLA DSP56KCC User s Manual A 95 printf printf EXAMPLE include lt stdio h gt char lib_name printf void main int i 709 double d 7 09 printf Show several s examples n lib name printf tintegers n printf t toctal o n i printf t toctal 90 i printf force leading O and zero pad n printf t tdecimal d n i printf t tdecimal 96 d force leading blank i printf t thex x n i printf t thex X force leading OX W i printf tfloating point n printf t tdouble f n d printf t tdouble e n d prints to standard output Show several printf examples integers octal 1305 octal 000001305 force leading 0 and zero pad decimal 709 decimal 709 force leading blank hex 2c5 hex 0X2C5 force leading OX floating point double 7 090000 double 7 090000e 00 ee UMM E A 96 DSP56KCC User s Manual MOTOROLA putc putc NAME putc Write a single character to a stream SYNOPSIS include lt stdio h gt int putc int c FILE stream DESCRIPTION The function pute writes
379. t and 2 macO2 arg which takes a fractional argument and returns 0 02 times the argument IL 5 28 DSP56KCC User s Manual MOTOROLA The second section implements mactwo arg which takes two fractional arguments and returns arg1 arg2 section mod1 int maco01 int arg takes a fractional argument and returns 0 01 argument int mac02 int arg takes a fractional argument and returns 0 02 argument section mod1 global Fmac01 Fmac01 move r0 y r6 prologue lua r6 r0 move ssh y r6 move x1 y r6 save register X1 move yO y r6 X save register YO move nO y r6 save register nO move 3 n0 move y r0 n0 x1 argument move 0 01 y0 operand 0 01 clr a macr x1 y0 a main program calculates multiplication of X1 and yO move y r6 n0 restore register nO move y r6 yO restore register YO move y r6 x1 restore register X1 move y r6 ssh epilogue move y r6 rO tst a rts rn o MOTOROLA DSP56KCC User s Manual 5 29 global Fmac02 Fmac02 move r0 y r6 prologue lua r6 r0 move ssh y r6 move x1 y r6 save register X1 move yO y r6 X save register YO move n0 y r6 save register nO move 3 n0 move y r0 n0 x1 argument move 140 02 y0 operand 0 02 clr a macr x1 y0 a main program calculates multiplication o
380. t char s2 size tn DESCRIPTION The strncmp function compares n characters of the string pointed to by s2 with the string pointed to by s1 If string s1 is lexicographically greater than equal to or less than 2 an integer respectively greater than equal to or less than zero will be returned This is similar to stremp SEE ALSO strcmp Compare two strings EXAMPLE include lt stdio h gt include lt string h gt void main char bigstr 80 string 1 char smallstr 20 string 2 if strncmp bigstr smallstr 5 0 printf strncmp ok n printf 2 strncmp error n prints to standard output strncmp ok I O MOTOROLA DSP56KCC User s Manual A 133 strncpy strncpy NAME strncpy Copy a portion of one string into another SYNOPSIS include lt string h gt char strncpy char s1 const char s2 size tn DESCRIPTION The strncpy function copies exactly n characters from a string pointed to by s2 into a string pointed to by s1 If strlen s2 is less than n the string 1 is null padded If strlen S2 is greater than or equal to n no null termination character is copied to s1 The s1 pointer is returned Note that the behavior of non null terminated strings is undefined SEE ALSO memcpy Copy one memory area to another strcpy Copy one string to another EXAMPLE include lt stdio h gt include lt string h gt
381. t to the standard output If a pathname is not given the file will be created in the current directory If no file name is supplied or if the B option is not given the linker will use the basename file name without extension of the first file name encoun tered in the link input file list The resulting output file will have an extension of cld The B option should be specified only once F lt argfil gt This option indicates that an external file should be read for further com mand arguments It is useful in host environments where the command line length is restricted argfil must be present on the command line but can be any legal operating system file name including an optional pathname The file may contain any legal command line options including the F option itself The arguments need be separated only by white space spaces tabs or newlines A semicolon on a line following white space causes the rest of the line to be treated as a comment ES MOTOROLA DSP56KCC User s Manual C 13 dsplnk dsplnk l Under normal operation the linker produces an absolute load file as output If the I option appears on the command line the linker combines the input files into a single relocatable link file suitable for a subsequent linker pass No absolute addresses are assigned and no errors are issued for unre solved external references L lt library gt The linker ordinarily processes a list of link files which each contain
382. tain a decimal point character even if no digits follow it Additionally for g and G trailing zeros will not be removed C O A 92 DSP56KCC User s Manual MOTOROLA printf printf 0 For d i o u x X e E f g and G conversions leading zeros following any indication of sign or base are used to pad to the field width no space padding is performed If the 0 and flags both appear the 0 flag will be ignored Each conversion takes place in character fields The minimum size of the field can be specified with the field width If the converted result contains fewer characters than specified by field width the result will be left padded with spaces by default see flags above The field width takes the form of a decimal integer or an asterisk When the field width is an asterisk the value is to be taken from an integer argument that precedes the argument to be converted Precision specifies the minimum number of digits to appear for the d i o u x X conversions the number of digits appear after the decimal point character for e E and f conversions the maximum number of significant digits for the g and G conversions or the maximum number of characters to be written from a string in the s conversion The precision takes the form of a followed by or by an optional decimal integer if only the period is specified the precision is taken to be zero If precision appears with any other conversion character the b
383. tch anything just store the number of characters read from the input stream during this call to fscanf 9o match a 9e character fscanf returns EOF if an input failure is detected before any conversions take place Otherwise it returns the number of assignments made Note that an optional assignment suppression character may follow the initial This character will cause fscanf to discard the converted value without advancing along the list of object pointers SEE ALSO scanf Read formatted input from standard input sscanf Read formatted input from a string EXAMPLES a The following program will assuming that the input pending on standard input is my 98 store the three characters m y 0 will be stored in word and 98 will be stored in number include lt stdio h gt void main char word 8 int number fscanf stdin 96s d word amp number b The following program will assuming that the input pending on standard input is yall come store the following five characters in the array word y a T T 90 include lt stdio h gt void main char word 8 fscanf stdin lay word __ gt _ ________ AA A A s BEEU A 48 DSP56KCC User s Manual MOTOROLA fseek fseek NAME fseek Set the file position indicator associated with a stream SYNOPSIS include lt stdio h gt int fseek FILE stream
384. te create command words to latch data into target latch high LATCH DATA high byte latch middle LATCH DATA middle byte latch low LATCH DATA low byte write the commands to the host port of the target ports B data ports B data B MOTOROLA DSP56KCC User s Manual F 31 high word latch high ports gt B_data ports gt B_data ports gt B_data ports gt B_data middle word latch middle low word latch low e aO 9 F 32 DSP56KCC User s Manual MOTOROLA io_atoi c x Data conversion between custom ASCII to internal integer representation The function atoi converts from ASCII integer data representation to internal integer data representation The function itoa converts from an integer to ASCII include globals h see page F 11 atoi Custom ASCII to integer conversion function Returns the integer represented by the string s The integer can be HEX or BINARY E or OCTAL or DECIMAL as indicated by the radix parameter B The function converts each character in the string until it finds a character that is not a valid digit in the given radix int atoi s radix char s int radix unsigned int num int digit int neg endcondition char c num 0 initialize number to zero neg 0 initialize flags to zero endcondition 0 if s amp amp radix DEC set negative flag neg 1 else if
385. te and returns 7 The host checks the buffer valid flag on hio send sees that it is true and transmits the message to the DSP 8 The library code running on the DSP finishes the fopen call and returns On the host side of the interface the application writer must write the code that exchanges data with the DSP the code that calls process_pending_host_io and the code that checks buffer valid flags On the DSP side of the interface the application writer must write the routines send and receive The communication between the DSP and the host is always initiated by the DSP and always follows a predetermined pattern depend ing on the initial message Because this communication is so simple the code that calls process pending host io can also be quite simple Example 6 7 is a hypothetical non reentrant interrupt handler written in C It uses two functions peek and poke to access some sort of hardware communication device connected to the DSP The functions peek and poke aren t provided they re simply an abstraction for host side hardware access This code assumes that the DSP sends the size of a message directly before sending a message CHECK BUFFER SIZE is a mac ro defined in dsp etc hostio h It should always be used to ensure that the buffer hio receive is large enough to handle the incoming message Finally this example as sumes that the function signal is available to register interrupt handlers Th
386. tensive error handling required by affine arithmetic denormalized numbers signaling Not a Numbers NaNs and quiet NaNs It postpones the introduction of computational errors by using internal signaling and user traps to process each exception condition Computational errors will be introduced by the application program if the calculation is completed instead of aborting the program The DSP56KCC format introduces computation errors when an exception occurs in order to maintain real time execution An error flag L bit in CCR is set to inform the application program that an exception has occurred This bit will remain set until reset by the application program The user can then eliminate the exception by algorithm modifications A _ 2 zz 4 6 DSP56KCC User s Manual MOTOROLA 4 4 3 Pointer Types With DSP56KCC all pointers are 16 bits see Table 4 7 When computing addresses with integer arithmetic only the least significant 16 bits are relevant Table 4 7 Pointer Size and Range Data Type Size words Min value Max value pointers 1 0 OxFFFF 45 Register Usage The DSP56000 family digital signal processor register set is shown in Table 4 8 DSP56KCC uses all of the registers listed in Table 4 8 with the exception of the M address modifier registers Table 4 8 DSP56000 Family Processor Registers Data AL Xn Input Registers x1 x0 24 bits Input Registers y1 yO 24 bits Accumulator Registers a2 8 bit
387. ter b X y 48 bit register promotion by optimizer x1 x0 y1 yO 24 bit register promotion by optimizer 4 6 Memory Usage Memory can be partitioned in several ways to provide high speed operation and additional off chip memory expansion Program and data memory are separate and the data memory is divided into two separate 24 bit wide memory spaces X and Y which can be combined to form a third 48 bit wide memory space L DSP56KCC generates code that can utilize X or Y or L data memory By default the Y memory model is selected Each separate memory model is supported by separate run time libraries that have been written and compiled assembled to handle each memory space See Chapter 3 Control Program Options for examples of the mx memory my memory and ml memory command line options for changing target memory spaces By default the compiler expects that each memory space is fully populated and several global C variables are defined see Chapter 6 Software Hardware Integration for information about customizing the memory configuration Figure 4 2 and Figure 4 4 illustrate the default program and data memory configuration The L memory model is recommended for best performance when long float or double data types are extensively used 4 6 1 Activation Record An activation record is the run time representation of a C subroutine A typical Enns 4 8 DSP56KCC User s Manual MOTOROLA Top Of Memory Program Area FFFF Max
388. that you receive source code or can get it if you want it that you can change the software or use pieces of it in new free programs and that you know you can do these things To protect your rights we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain respon sibilities for you if you distribute copies of the software or if you modify it For example if you distribute copies of a such a program whether gratis or for a fee you must give the recipients all the rights that you have You must make sure that they too receive or can get the source code And you must tell them their rights We protect your rights with two steps 1 copyright the software and 2 offer you this li cense which gives you legal permission to copy distribute and or modify the software Also for each author s protection and ours we want to make certain that everyone un derstands that there is no warranty for this free software If the software is modified by someone else and passed on we want its recipients to know that what they have is not the original so that any problems introduced by others will not reflect on the original au thors reputations The precise terms and conditions for copying distribution and modification follow EEE E 4 DSP56KCC User s Manual MOTOROLA TERMS AND CONDITIONS 1 This License Agreement applies to any program or other w
389. the frame Usually this address is kept in a register called the frame pointer register while ex ecution is going on in that frame GDB assigns numbers to all existing stack frames starting with zero for the innermost frame one for the frame that called it and so on upward These numbers do not really exist in your program they are to give you a way of talking about stack frames in GDB commands Many GDB commands refer implicitly to one stack frame GDB records a stack frame that is called the selected stack frame you can select any frame using one set of GDB com mands and then other commands will operate on that frame When your program stops GDB automatically selects the innermost frame Some functions can be compiled to run without a frame reserved for them on the stack This is occasionally done with heavily used library functions to save the frame setup time GDB has limited facilities for dealing with these function invocations if the innermost function invocation has no stack frame GDB will give it a virtual stack frame of 0 and cor rectly allow tracing of the function call chain Results are undefined if a function invoca tion besides the innermost one is frameless 3 14 Backtraces A backtrace is a summary of how the program got where it is It shows one line per frame for many frames starting with the currently executing frame frame zero followed by its caller frame one and on up the stack backtrace bt Print
390. the Free Software Foundation gdb56 has something of the flavor of the UNIX source level debugger dbx but has more features and power gdb56 is invoked with the shell command gdb56 Once started it reads commands from the terminal until given the quit command name is the name of the executable program and core if specified is the name of the DSP56000 DSP56001 state file to be examined or have execution re sumed gdb56 has been modified to run with both software and hardware DSP56000 DSP56001 execution devices OPTIONS The following command line options can be used to more precisely specify the files to be debugged All the options and command line arguments giv en are processed in sequential order The order makes a difference when the x command is used s SYMFILE Read symbol table from file SYMFILE e EXECFILE Use EXECFILE as the executable file to execute when appropriate and for examining pure data in conjunction with a core dump se FILE Read symbol table from FILE and use it as the executable file c COREFILE Analyze the core dump COREFILE GE MOTOROLA DSP56KCC User s Manual C 17 gdb56 gdb56 X file Execute GDB commands from file d directory Add directory to the path to search for source files The following additional command line options can be used to affect cer tain aspects of the behavior of gdb56 hx Don t execute commands from the init files gdbinit Normally the com mands in thes
391. the character c to the specified stream It is identical to the function fputc except that putc may be implemented as a macro This means that arguments to putc may be evaluated more than once This is only a problem for function arguments that have side effects when evaluated SEE ALSO fputc Write a single character to a stream EXAMPLE include lt stdio h gt void main putc int S stdout putc int h stdout putc int a stdout putc int d stdout putc int r stdout putc int a stdout putc int c stdout putc int k stdout putc int n stdout Will cause the following output to be printed to standard output Shadrack eau MOTOROLA DSP56KCC User s Manual A 97 putchar putchar NAME putchar Write a character to standard output SYNOPSIS include lt stdio h gt int putchar int c DESCRIPTION The putchar function prints a character to standard output SEE ALSO getchar Get a character from standard input gets Get a line of text from standard input puts Write a string to standard output EXAMPLE Hinclude lt stdio h gt char str bald feet n void main while str 10 putchar str prints to standard output bald feet r rH C O A 98 DSP56KCC User s Manual MOTOROLA puts puts NAME puts
392. the source code for the frame 3 37 File specifying Options All the options and command line arguments given are processed in sequential order The order makes a difference when the x option is used file Read symbol table from file file e file Use file file as the executable file to execute when appropriate and for ex amining pure data in conjunction with a core dump se file Read symbol table from file file and use it as the executable file c file Use file file as a core dump to examine EES MOTOROLA DSP56KCC User s Manual E 69 X file Execute GDB commands from file file d directory Add directory to the path to search for source files 3 38 Other Arguments If there are arguments to GDB that are not options or associated with options the first one specifies the symbol table and executable file name as if it were preceded by se and the second one specifies a core dump file name as if it were preceded by c E 70 DSP56KCC User s Manual MOTOROLA D 13 Using GDB under GNU Emacs A special interface allows you to use GNU Emacs to view and edit the source files for the program you are debugging with GDB To use this interface use the command M x gdb in Emacs Give the executable file you want to debug as an argument This command starts GDB as a subprocess of Emacs with input and output through a newly created Emacs buffer Using GDB under Emacs is just like
393. the standard I O library code it defines the constant definitions used in the aforementioned messages A typical series of events and messages that comprise a standard I O call might look like this 1 The application running on the DSP makes a call to fopen 2 The library code in lib56c xyl clb calls send with a buffer that contains the code DSP OPEN the flags the mode and the string length of the path 3 The host receives the message into the buffer hio receive sets its valid flag and calls process pending host io The state machine inside process pending host io notes that it is now in the middle of an open file request records the values from the first message and then returns At this point code written by the application developer must check the valid flag of the buffer hio send in this case the buffer hio send has not been marked valid 4 The library code in lib56c xyl clb calls send again this time sending the path D RrruEAELAEALAZZMLFLZZLLSS ee MOTOROLA DSP56KCC User s Manual 6 13 5 Again the host receives the message into the buffer hio_receive and calls process_pending_host_io after setting the buffer s valid flag 6 process pending host io uses the information from the two messages to perform the file open It then builds an operation status message places it in the buffer hio send and sets that buffer s valid flag process pending host io resets its internal sta
394. tion _ _ gt z __ z _ _____ ______ _ ___ M 1 MOTOROLA DSP56KCC User s Manual E 35 until always stops the program if it attempts to exit the current stack frame until may produce somewhat counterintuitive results if the order of the source lines does not match the actual order of execution For example in a typical C for loop the third expression in the for statement the loop step expression is ex ecuted after the statements in the body of the loop but is written before them Therefore the until command would appear to step back to the beginning of the loop when it advances to this expression However it has not really done so not in terms of the actual machine code Note that until with no argument works by means of single instruction stepping and hence is slower than until with an argument until location Continue running the program until either the specified location is reached or the current innermost stack frame returns This form of the command uses break points and hence is quicker than until without an argument stepi si Execute one machine instruction then stop and return to the debugger It is often useful to do display i pc when stepping by machine instructions This will cause the next instruction to be executed to be displayed automatically at each stop See section Auto Display An argument is a repeat count as in step nexti
395. tions Perform machine dependent and independent optimizations This is the default mode of the compiler Invoking the compiler with the optimizer may cause compile times to increase and require more system memory Invoking the compiler without the optimizer should be done only when the program mer requires additional flexibility while debugging code An example of such flexibil ity includes the ability to assign new values to declared c variables Additionally non optimized code takes register usage clues from the storage class specifier reg ister something not done with the optimizer invoked Disabling the optimizer is done via f options listed above m56002 Enables the generation of DSP56002 instructions mno dsp optimization Disables all Motorola optimizer enhancements mno do loop generation Disable DO instruction usage by optimizer mno biv plus linv promotion Disable the promotion of address expressions to address registers within loops This optimization transforms array base address plus induction variable expressions into auto increment decrement style memory references mp mem switchtable Forces the compiler to locate all switch tables in P memory mstack check Generate extra run time code to check for run time stack collision with the heap This option causes run time execution times to increase dramatically mx memory Direct the compiler to locate data in the X data memory space Memory modes can not
396. to happen For example if the program stopped due to some sort of memory reference error you might store cor rect values into the erroneous variables and continue hoping to see more execution but the program would probably terminate immediately as a result of the fatal signal once it sees the signal To prevent this you can continue with signal 0 See section Signaling You can also act in advance to prevent the program from seeing certain kinds of signals using the handle command see section Signals 3 12 Stepping Stepping means setting your program in motion for a limited time so that control will re turn automatically to the debugger after one line of code or one machine instruction Breakpoints are active during stepping and the program will stop for them even if it has not gone as far as the stepping command specifies SSE E 34 DSP56KCC User s Manual MOTOROLA step Continue running the program until control reaches a different line then stop it and return control to the debugger This command is abbreviated s This command may be given when control is within a function for which there is no debugging information In that case execution will proceed until control reaches a different function or is about to return from this function An argument repeats this action step count Continue running as in step but do so count times If a breakpoint is reached or a signal not related to stepping occurs be
397. to the Free Software Foundation we sometimes make exceptions for this Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally NO WARRANTY 1 BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE THERE IS NO WARRANTY FOR THE PROGRAM TO THE EXTENT PERMITTED BY APPLI CABLE LAW EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPY RIGHT HOLDERS AND OR OTHER PARTIES PROVIDE THE PROGRAM AS IS WITHOUT WARRANTY OF ANY KIND EITHER EXPRESSED OR IMPLIED INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MER CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU SHOULD THE PROGRAM PROVE DEFECTIVE YOU ASSUME THE COST OF ALL NECESSARY SERVICING REPAIR OR CORRECTION 2 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER OR ANY OTHER PARTY WHO MAY MODIFY AND OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE BE LIABLE TO YOU FOR DAMAGES INCLUDING ANY GENERAL SPECIAL INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM INCLUDING BUT NOT LIM ITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF S
398. tory first asm string Pass the argument string directly to asm56000 the DSP56000 1 assembler Example 3 31 Pass a single option to the assembler C gt g56k asm v file vw Example 3 32 Pass multiple options to the assembler C gt g56k asm v OS CRE file c C Compile and or assemble the source files suppressing the link phase This option generates corresponding output files suffixed cln Affected input files are suffixed with c and asm 3 2 4 Link Phase Options The options listed below control the link phase of the compilation process This group of link phase options is the sub set of the available linker options that are compiler oriented see the Motorola DSP56000 Linker Librarian Reference Manual for a complete option list The crt and I options locate the file provided as an argument by searching a stan dard list of directories see Section 3 1 for this directory list The default option is to add the C compiler output directory into the standard search list and search that directory first crt file Replace the default start up file crt056 cln with file g56k searches the standard list of directories to find the start up file In addition any directory defined using the B option or the G56_EXEC_PREFIX environment variable will be searched For additional information see Chapter 6 Example 3 33 Compile the C program foo c with the crtO file crt asm Notice that the crtO file crt as
399. tream cos Cosine cosh Hyperbolic cosine div integer division with remainder exit Terminate program normally _ _ ___ __ _ _ _ __ _ ____z_ _____ AA MOTOROLA DSP56KCC User s Manual A 3 exp Exponential e fabs Absolute value of a double fclose Close a stream feof Test the end of file indicator of a stream ferror Test the error indicator of a stream fflush Flush all output pending on a stream fgetc Read acharacter from a stream fgetpos Retrieve the current value of the file position indicator of a stream fgets Read a string from a stream floor Floor function fmod Floating point remainder fopen Open anamed file on the disk to be accessed via a stream fprintf Write formatted output to a stream fputc Write a character to a stream fputs Write a string to a stream fread Read unformatted input from a stream free Free storage allocated by calloc malloc and realloc freopen Open a named file on the disk to be accessed via a stream frexp Break a floating point number into mantissa and exponent fscanf Read formatted input from a stream fseek Set a stream s file position indicator fsetpos Set a stream s file position indicator ftell Retrieve the current value of a stream s file position indicator fwrite Write unformatted output to a stream getc Read a character from a stream thi
400. tring is empty or the subject contains no floating point constant description zero is returned SEE ALSO atof String to double atoi String to integer atol String to long integer strtol String to long integer strtoul String to unsigned long integer eeaeee Moo MOTOROLA DSP56KCC User s Manual A 139 strtod strtod EXAMPLE include lt stdio h gt include lt stdlib h gt void main char string 7 09strtod stopped char stopped double result result strtod string amp stopped printf string s n string printf result f n result printf stop string s n stopped prints to standard output string 7 09strtod stopped result 7 089998 stop string strtod stopped r WW O A 140 DSP56KCC User s Manual MOTOROLA strtok strtok NAME strtok Break string into tokens SYNOPSIS include lt stdlib h gt char strtok char s1 const char s2 DESCRIPTION The strtok function breaks the string pointed to by stinto tokens and each token is delimited by characters from the string pointed to by s2 The first call in the sequence has s1 as its first argument and is followed by calls with a null pointer as the first argument The separator string s2 may be different from call to call If a token is not found a null pointer is returned If a token is found a null terminated token is returned eeaeee
401. tus if status MUTE mute vol _GAIN VOL _GAIN VOL 0 status MUTE 0 else _GAIN VOL mute_vol status MUTE 1 pe aee O F 24 DSP56KCC User s Manual MOTOROLA io_sci c This file contains the low level i o functions required for communications between the SCI port and the keyboard Characters are transmitted via this communication as well as strings and numbers include globals h see page F 11 getc Get a character from the keyboard through the SCI port char getc echo flag int echo flag flag indicating if character will be echoed to screen or not void putc char data if ungetcbuf NUL data ungetcbuf ungetcbuf NUL else while sci gt status amp RX_FULL wait for data data sci gt lo_data if echo_flag putc data echo character to screen return data getc_nw Try to get a character from the keyboard through the SCI port or return a NUL if no character is waiting char getc nw t void putc char data if ungetcbuf NUL check character buffer first data ungetcbuf ungetcbuf NUL else if sci status amp RX FULL see if a character is waiting data sci lo data putc data else return NUL if no character is ready data NUL return data ungetc If a character has been read but is not needed now
402. tus FILTER 4 coef ptr coef 6 break case E 1000 Hz Notch Filter status FILTER 5 coef ptr _coef 7 break case F 2000 Hz Notch Filter status FILTER 6 coef ptr _coef 8 break case G 1000 Hz Band Pass Filter status FILTER 7 coef ptr _coef band break case H loop 0 break default putc BEEP break F 22 DSP56KCC User s Manual MOTOROLA set_volume Displays a bar graph which may be adjusted with the arrow keys by the user to set a new volume level void set volume 1 extern void putc extern void putstr extern void setscreen extern void screen attr extern char getc extern void download extern int GAIN int v col char c if status MUTE if mute is on turn it off status MUTE 0 setscreen SPACE display current settings and instructions cur pos 1 27 Screen attr UNDERSCORE putstr ADJUST VOLUME Screen attr NORMAL putstr use arrow keys cur pos 10 5 putstr volume putint status VOLUME DEC cur_pos 14 5 putstr range 0 15 cur_pos 20 60 putstr hit RETURN to cur pos 21 60 putstr return to menu Screen attr REVERSE use reverse spaces to draw the bar for v 1 co1 35 v lt status VOLUME v cur pos 25 v col putstr draw bar for current vol v status VOLUME co
403. type h gt void main if islower a printf a lower case character n if islower F printf F not a lower case character n prints to standard output a lower case character F not a lower case character UM E MOTOROLA DSP56KCC User s Manual A 61 isprint isprint NAME isprint Test for printing character excluding Mt SYNOPSIS include lt ctype h gt int isprint int c DESCRIPTION The isprint function returns a nonzero value for any printable character excluding the tab character X zero is returned in the false case This function is provided both as an in line and out of line function When the header file ctype h is included the default case will be in line see section A 3 Forcing Library Routines Out of line EXAMPLE include lt stdio h gt include lt ctype h gt void main if isprint printf space print character n if isprint t printf tab not print character n prints to standard output space print character tab not print character u Cc M Z 2 2 A0 A 62 DSP56KCC User s Manual MOTOROLA ispunct ispunct NAME ispunct Test for punctuation character SYNOPSIS include lt ctype h gt int ispunct int c DESCRIPTION The ispunct functi
404. uctions to save and restore the registers around such calls Such allocation is done only when it seems to result in better code than would otherwise be produced fkeep inline functions Output a separate run time callable version of the function even if all calls to a given function are integrated and the function is declared static fwritable strings Store string constants in the writable data segment without making them unique This is for compatibility with old programs which assume they can write into string constants Writing into string constants is poor technique constants should be con stant fcond mismatch Allow conditional expressions with mismatched types in the second and third argu ments The value of such an expression is void fvolatile Consider all memory references through pointers to be volatile ffixed REG Treat the register named REG as a fixed register generated code should never re ____ _ gt z_ _ _ _ _ __ _ _ AAA gt gt A AAA 3 20 DSP56KCC User s Manual MOTOROLA Compile Phase Options fer to it except perhaps as a stack or frame pointer Legal values for REG are r1 r2 r3 r4 r5 r7 This flag should be used sparingly as it can have devastating results on the code generated eeaeee M o MOTOROLA DSP56KCC User s Manual 3 21 Compile Phase Options Example 3 22 Reserve r4 for later special purpose C gt g56k O ffixed r4 file c o tile eld Caution C code that utilizes
405. ucture 3 the return value is not passed in accumulator a A copy of the return structure is placed into the space allocated in the caller s activation record and pointed to by accumulator A 4 9 Software Support for Arithmetic Routines The DSP56000 family architecture provides full hardware support for all 24 bit arithmetic operations and partial support for 48 bit integer operations Support for all float double and a portion of the 48 bit long is provided via special software library routines These special library routines do not pass arguments to the routines according to the normal subroutine calling convention instead each routine has its arguments passed in the A and B accumulators and the result returned in the A accumulator limiting the overhead involved in the call return sequence See Table 4 10 and Table 4 11 for a list of the gt _ _n__ I IIM i MOTOROLA DSP56KCC User s Manual 4 13 Table 4 10 Floating point Arithmetic Routine Source Module fadd_ba fadd56 asm fsub_ba fsub56 asm fmpy_ba fmpy56 asm fdiv_ba fdiv56 asm fneg_a fneg56 asm fcmp a fcmp56 asm Table 4 11 48 bit Long Integer Arithmetic Routine Source Module div ba idivb6 asm mod ba imod56 asm udiv_ba uidiv56 asm umod_ba uimod56 asm Impy_ba _mpy56 asm Idiv_ba div56 asm Imod_ba mod56 asm F uldiv ulongdivmod c F ulmod ulongdivmod c routines supported in software All but two of these routines restore all registers us
406. ue may be any string the values of environment variables are just strings and any interpretation is supplied by your program itself The value parameter is optional if it is eliminated the variable is set to a null value This command can be abbreviated as short as set e EE E 20 DSP56KCC User s Manual MOTOROLA For example this command set env USER foo tells the program when subsequently run to assume it is being run on behalf of the user named foo delete environment varname unset environment varname Remove variable varname from the environment to be passed to your program This is different from set env varname because delete environment leaves the variable with no value which is distinguishable from an empty value This com mand can be abbreviated d e 3 5 Your Program s Working Directory Each time you start your program with run it inherits its working directory from the cur rent working directory of GDB GDB s working directory is initially whatever it inherited from its parent process typically the shell but you can specify a new working directory in GDB with the cd command The GDB working directory also serves as a default for the commands that specify files for GDB to operate on See section Files cd directory Set GDB s working directory to directory pwd Print GDB s working directory 3 6 Your Program s Input and Output By default the pr
407. ult result asin 7 09 if result 0 0 amp amp errno EDOM perror asin perror test prints to standard output asin perror test domain error r HO A O A 90 DSP56KCC User s Manual MOTOROLA pow pow NAME pow Raise a double to a power SYNOPSIS include lt math h gt double pow double x double y DESCRIPTION The pow function computes and returns x If x is zero and y is less than zero a domain error occurs setting errno to EDOM and returning 0 0 If xY is greater than HUGE VAL errno is set to ERANGE and HUGE VAL is returned SEE ALSO exp Raising e to a power Idexp Multiplying a number by a power of 2 EXAMPLE include lt stdio h gt include lt math h gt void main printf pow 2 0 2 0 f n pow 2 0 2 0 prints to standard output pow 2 0 2 0 4 000000 AAA AAA A A AA A A U EE MOTOROLA DSP56KCC User s Manual A 91 printf printf NAME printf Print to standard output SYNOPSIS include lt stdio h gt int printf const char format DESCRIPTION The printf function formats and writes a string to the standard output Interpreting the format specifier format left to right The format specifier format consists of ordinary characters escape sequences and conversion specifications The conversion specifications describe how arguments passed to printf are converted for output All non co
408. ument stream may be evaluated more than once This only becomes a problem if evaluation of the argument has side effects SEE ALSO fgetc Read a character from a stream fputc Write a character to a stream EXAMPLE include lt stdio h gt void main char value char getc stdin while EOF value fputc value stdout value char getc stdin will echo all characters from standard input to standard output until the input is exhausted A A A UME MOTOROLA DSP56KCC User s Manual A 53 getchar getchar NAME getchar Read a character from standard input SYNOPSIS include lt stdio h gt int getchar void DESCRIPTION The function getchar reads the next character from standard input If there is no pending input getchar returns EOF otherwise the read character is cast to type int and returned SEE ALSO fputc Write a character to a stream EXAMPLE include lt stdio h gt void main char value char getchar while EOF value fputc value stdout value char getchar will echo all characters from standard input to standard output until the input is exhausted eea A 54 DSP56KCC User s Manual MOTOROLA gets gets NAME gets Read a string from standard input SYNOPSIS include lt stdio h gt char gets char s DESCRIPTION The function fgets will read characters from standard input and place
409. uter s CPU b gdb56 which is a debugging tool for trouble shooting the compiled application c sim56000 which is a complete DSP56000 1 simulator that can be used to execute the compiled application in either COFF format or lod file format and allow examination of registers and memory d ads56000 is the development system hardware that can then be used to load and execute the compiled application in either COFF format or lod file format on the ADS development system and e the target system shown is the user s custom DSP system Note The three execution devices in the shaded boxes are not part of the C compiler software The COFF linker output can be used by these execution devices directly The conversion utility srec see Figure 1 1 can be used to convert the executable file from the COFF Linker to a suitable format for PROM burning These PROMs can then be used on the ADS development system or the user s target system The PROM programmer ADS development system and user s target system are not part of the DSP56KCC compiler IEEE MOTOROLA DSP56KCC User s Manual 1 3 The DSP56000 family represents a departure from more conventional architectures on which other implementations of the C language are based Also the nature of DSP applications dictates that a greater measure of control be provided to the programmer in specifying the constraints of the run time environment For these reasons the components of the development syst
410. utput operands and input operands see Section 5 2 2 The first operand is labeled zero and there can be up to 31 more operands in the list More than one instruction template can be used if more than 32 operands are needed In line assembly code can also be used to insert a label directly into the compiler output A label without any white spaces in the in line assembly code instruction template will guarantee that the same template label will be in the compiler output see Example 5 __ _ gt a __ _ _ _ NM 5 4 DSP56KCC User s Manual MOTOROLA 22 Care should be taken not to use labels that the C compiler generates Using the same labels as the C compiler will cause a duplicate label error see Section 4 7 Compil er Naming Conventions 5 2 2 Output Input Operands The operand list is a concatenation of output and input operands which the OES can access via the operand_id_number see Section 5 2 1 Output or input operands consist of operands separated by a comma Each operand should be associated with a C ex pression and its operand constraint described below A colon is used to separate the assembler instruction template from the first output operand A second colon separates the final output operand from the first input operand A third colon can be used to separate the input operands from the optional field reg_save Two consecutive colons are required when only input operands are needed in
411. ves As an example the sequence of the options IDIRA 1 IDIRB directs C compiler to use both the directories DIRA and DIRB for the file inclusion filename and DIRB only for file inclusion lt filename gt NOTE The l option inhibits the use of the current directory as the first search directory for include filename There is no way to override this ef fect of l However the directory which is current when the compiler is invoked can be searched by using l This is different from the prepro cessor s default search list but it is often satisfactory I does not inhibit the use of the standard system directories for header files Thus I and nostdinc are independent _ _ O O O fE MOTOROLA DSP56KCC User s Manual 3 11 Preprocessor Phase Options Example 3 14 A test program file c is used to test a file operation fopen which is in this example desired to be developed for a DSP56000 1 system The file include lt stdio h gt is used as if it is in the standard include directory The file is desired to be developed or debugged and it is located in the user working directory mysys This example shows how to use IDIR and l combination to test file inclusion filename Notice that the l inc I 1 mysys option specifies the inc directory only for the file inclusion cnt h and mysys directory for the file inclusion lt stdio h gt CENS ALE file c inc mysys C gt dir ine cnt h
412. void main char bigstr 80 string 1 char smallstr 20 spanky 2 void strncpy bigstr smallstr 6 puts bigstr prints to standard output spanky 1 A A A O A 134 DSP56KCC User s Manual MOTOROLA strpbrk strpbrk NAME strpbrk Find the first occurrence of a character from one string in another SYNOPSIS include lt string h gt char strpbrk char s1 const char s2 DESCRIPTION The strpbrk function finds the first occurrence of any character in the string pointed to by s2 in the string pointed to by s1 If a character is found a pointer to the character is returned If a character is not found a null pointer is returned SEE ALSO memchr Find a character in a memory area strchr Find the first occurrence of a character in a string strcspn Compute the length of the prefix of a string not containing any characters contained in another string strrchr Find the last occurrence of a character in a string strspn Compute the length of the prefix of a string contained in another string AAA A A A A A Mo MOTOROLA DSP56KCC User s Manual A 135 strpbrk strpbrk EXAMPLE include lt stdio h gt include lt string h gt void main char string abcde random characters fghijkl char fndstr kImnopqr char found if found strpbrk string fndstr NULL puts found puts can t find a character prints to stand
413. xamining the Slate sd ie E 37 3 13 Stack Frames trata a o ota E 37 3 14 ll A D PEL E 38 3 15 Selecting a Framo 2 cs tess hs rages esce LENS E eas ts E 39 3 16 Information on a FraMe ooocccccoccc ee E 40 D 7 Examining Source Files c obe bs ts ke edel xx E 43 3 17 Printing Source Lines uae etur uo Rs e arr BUE abe se E 43 3 18 searching Source Files comadre iaa hanes E 45 IEEE C _ _ _ _ UUU MOTOROLA DSP56KCC User s Manual V Table of Contents Continued Paragraph Page Number Title Number 3 19 Specifying Source Directories oooooooooooooooo E 45 D 8 Examining Datars a oce due tus Dd ra A O je E 47 3 20 EXPONE E 47 3 21 Program VarnableS cc road de Su sna ie nets a dd er kids E 48 3 22 Artificial Aray Sa oe ext ere bs oe ee a to eee meee CHE p ENS E 48 3 23 Format GDIIOrSs St es tt era na he de dre Le Le le dida od E 49 3 24 OUIDUL TOTIS rada E 50 3 24 1 Examining Memory iu eques ov ed ER uS E ARE REA E 51 3 25 Automatic DISDIay s dut ap peREESRDERLERRRDRR3 ERR E 53 3 26 Value HIStory ob a acp ETC PU eoe de oe Rabe CE ENS eo es E 55 3 27 Convenience Variables ves odas ee extet dane eee es wee E 56 3 28 A Luc E 57 3 28 1 Examples as c rns ea aa Uu aas obere othe ec saa E 58 D 9 Examining the Symbol Table 2 ax a w ues E 59 D 10 Altering Exeoulloflss us eau eames bat e E P rU EERIG E 61 3 29 Assignment to Varlables xi aah red ados E 61 3 30 Continuing at a Different Address
414. xample below the number of loops is a variable and therefore cannot be predetermined that may equal zero for i 0 i lt j i 4 11 10 Jump Optimizations All cases of jumps conditional and unconditional to unconditional jumps are eliminated to create a single jump and target label 4 11 11 Instruction Combination Instruction combination replaces several operators with a single less expensive operator This optimization method is very machine specific Sequences that are commonly combined by the optimizer include 1 integer add multiply becomes a mac instruction 2 integer subtract multiply becomes a mac instruction 3 a memory reference combined with a pointer adjustment becomes an autoincrement or autodectrement addressing mode This is very powerful when combined with register promotion and do loop promotion For example for iz0 i 10 i c array 1 i array 2 i the for loop becomes a do instruction the array references are promoted to address registers and the induction variable is eliminated with array pointer advancement done via the autoincrement addressing mode 4 11 12 Leaf Routine Detection A leaf routine is a subroutine that makes no further subroutine calls When the compiler identifies such routines the prologue and epilogue code are optimized no save and restore of the ssh 2222 _ __ _ _ _z z __ ________ 4 18 DSP56KCC User s Manual MOTOROLA 4 11 13 Function
415. y free except for a nominal charge for the cost of distribution a complete machine readable copy of the corresponding source code to be distributed under the terms of Paragraphs 1 and 2 above or accompany it with the information you received as to where the corresponding source code may be obtained This alternative is allowed only for noncom mercial distribution and only if you received the program in object code or exe cutable form alone Source code for a work means the preferred form of the work for making mod ifications to it For an executable file complete source code means all the source code for all modules it contains but as a special exception it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs or for standard header files or definitions files that accompany that operating system 5 You may not copy modify sublicense distribute or transfer the Program except as expressly provided under this General Public License Any attempt otherwise to copy modify sublicense distribute or transfer the Program is void and will auto matically terminate your rights to use the Program under this License However parties who have received copies or rights to use copies from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance 6 By copying distributing or modifyi
Download Pdf Manuals
Related Search
Related Contents
Brainboxes IS-250 TechNEWS November 2014 - FDRPASVM GAT10-DN RS-485/DeviceNet変換器 取扱説明書 基本編 Submersible Automatic Utility Pump HumidiProbe User's Guide MimioClassroom User Guide 共有在庫市場 一撃市場 市場規約 ANEXO C INSTRUCTIVO RENDICION CUENTA.doc Copyright © All rights reserved.
Failed to retrieve file