id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
801
./cc65/libsrc/geos-common/common/perror.c
/* * perror.c * * Maciej 'YTM/Elysium' Witkowiak, 15.07.2001 */ #include <stdio.h> #include <string.h> #include <errno.h> #include <geos.h> void __fastcall__ perror(const char* msg) { const char *errmsg = strerror(errno); ExitTurbo(); if (msg && *msg) { DlgBoxOk(msg, errmsg); } else { DlgBoxOk("", errmsg); } }
802
./cc65/libsrc/geos-common/common/_afailed.c
/* * _afailed.c * * Maciej 'YTM/Elysium' Witkowiak 28.10.2001 */ #include <stdio.h> #include <stdlib.h> #include <geos.h> void _afailed (char* file, unsigned line) { ExitTurbo(); drawWindow.top = 0; drawWindow.left = 0; drawWindow.bot = 15; drawWindow.right = 150; dispBufferOn = ST_WR_FORE|ST_WR_BACK; SetPattern(0); Rectangle(); FrameRectangle(0xff); PutString(CBOLDON "file: ", 10, 10); PutString(file, 10, r11); PutString(CBOLDON " line: ", 10, r11); PutDecimal(0, line, 10, r11); DlgBoxOk(CBOLDON "ASSERTION FAILED", "PROGRAM TERMINATED" CPLAINTEXT); exit (2); }
803
./cc65/libsrc/geos-common/common/sleep.c
/* * sleep.c * * Maciej 'YTM/Elysium' Witkowiak, 16.08.2003 * */ #include <geos.h> unsigned __fastcall__ sleep (unsigned wait) { char typ; if ( (get_tv()) & TV_NTSC ) { typ = 60; } else { typ = 50; } Sleep(wait*typ); return 0; }
804
./cc65/libsrc/geos-common/common/_poserror.c
/* * _poserror.c * * Maciej 'YTM/Elysium' Witkowiak, 25.04.2003 */ #include <stdio.h> #include <string.h> #include <errno.h> #include <geos.h> void __fastcall__ _poserror (const char* msg) { const char *errmsg = _stroserror(_oserror); ExitTurbo(); if (msg && *msg) { DlgBoxOk(msg, errmsg); } else { DlgBoxOk("", errmsg); } }
805
./cc65/libsrc/geos-common/common/abort.c
/* * abort.c * * Maciej 'YTM/Elysium' Witkowiak 15.7.2001 */ #include <stdlib.h> #include <geos.h> void abort (void) { ExitTurbo(); DlgBoxOk(CBOLDON "ABNORMAL PROGRAM", "TERMINATION." CPLAINTEXT); exit(3); }
806
./cc65/libsrc/geos-common/system/systime.c
/* * systime.c * * Maciej 'YTM/Elysium' Witkowiak, 22.11.2002 */ #include <time.h> #include <geos.h> time_t _systime(void) { struct tm currentTime; currentTime.tm_sec = system_date.s_seconds; currentTime.tm_min = system_date.s_minutes; currentTime.tm_hour = system_date.s_hour; currentTime.tm_mday = system_date.s_day; currentTime.tm_mon = system_date.s_month; currentTime.tm_year = system_date.s_year; if (system_date.s_year < 87) { currentTime.tm_year+=100; } currentTime.tm_isdst = -1; return mktime(&currentTime); } clock_t clock(void) { return _systime(); }
807
./cc65/libsrc/geos-common/dlgbox/messagebox.c
/* * char MessageBox (char mode, const char *format, ...) * * Maciej 'YTM/Elysium' Witkowiak, 17.08.2003 * */ #include <geos.h> #include <stdio.h> void _mbprintout(void); static dlgBoxStr _mbdlg_EMPTY = { DB_DEFPOS(1), DB_OPVEC(&RstrFrmDialogue), DB_USRROUT(&_mbprintout), DB_END, }; static dlgBoxStr _mbdlg_OK = { DB_DEFPOS(1), DB_USRROUT(&_mbprintout), DB_ICON(OK, DBI_X_1, DBI_Y_2), DB_END, }; static dlgBoxStr _mbdlg_OKCANCEL = { DB_DEFPOS(1), DB_USRROUT(&_mbprintout), DB_ICON(OK, DBI_X_0, DBI_Y_2), DB_ICON(CANCEL, DBI_X_2, DBI_Y_2), DB_END, }; static dlgBoxStr _mbdlg_YESNO = { DB_DEFPOS(1), DB_USRROUT(&_mbprintout), DB_ICON(YES, DBI_X_0, DBI_Y_2), DB_ICON(NO, DBI_X_2, DBI_Y_2), DB_END, }; static dlgBoxStr *_mbboxes[] = { &_mbdlg_EMPTY, &_mbdlg_OK, &_mbdlg_OKCANCEL, &_mbdlg_YESNO }; static char _mbbuffer[256]; char MessageBox(char mode, const char *format, ...) { register char *buf; va_list ap; /* first format out things */ va_start(ap, format); vsprintf(_mbbuffer, format, ap); va_end(ap); /* replace LFs by CRs */ buf = &_mbbuffer[0]; while (*buf) { if (*buf==LF) *buf=CR; ++buf; } /* validate mode */ if (mode>=MB_LAST) mode = MB_EMPTY; return DoDlgBox(_mbboxes[mode]); } void _mbprintout(void) { UseSystemFont(); curWindow.top = DEF_DB_TOP; curWindow.left = DEF_DB_LEFT+10; curWindow.right = DEF_DB_RIGHT-10; curWindow.bot = DEF_DB_BOT; PutString(_mbbuffer, DEF_DB_TOP+10+curFontDesc.height, DEF_DB_LEFT+10 ); }
808
./cc65/libsrc/dbg/dbg.c
/* * dbg.c * * Ullrich von Bassewitz, 08.08.1998 * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <ctype.h> #include <6502.h> #include <dbg.h> /*****************************************************************************/ /* Function forwards */ /*****************************************************************************/ /* Forwards for handler functions */ static char AsmHandler (void); static char RegHandler (void); static char StackHandler (void); static char CStackHandler (void); static char DumpHandler (void); static char HelpHandler (void); /* Forwards for other functions */ static void DisplayPrompt (char* s); static void SingleStep (char StepInto); static void RedrawStatic (char Frame); static void Redraw (char Frame); static char GetKeyUpdate (void); /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Color definitions */ #if defined(__PLUS4__) || defined(__C16__) # define COLOR_BORDER (BCOLOR_DARKBLUE | CATTR_LUMA6) # define COLOR_BACKGROUND COLOR_WHITE # define COLOR_TEXTHIGH COLOR_BLACK # define COLOR_TEXTLOW COLOR_GRAY1 # define COLOR_FRAMEHIGH COLOR_BLACK # define COLOR_FRAMELOW COLOR_GRAY2 #else # if defined(COLOR_GRAY3) # define COLOR_BORDER COLOR_BLACK # define COLOR_BACKGROUND COLOR_BLACK # define COLOR_TEXTHIGH COLOR_WHITE # define COLOR_TEXTLOW COLOR_GRAY3 # define COLOR_FRAMEHIGH COLOR_WHITE # define COLOR_FRAMELOW COLOR_GRAY3 # else # if defined(__APPLE2__) # define COLOR_BORDER COLOR_BLACK # define COLOR_BACKGROUND COLOR_BLACK # define COLOR_TEXTHIGH COLOR_BLACK # define COLOR_TEXTLOW COLOR_BLACK # define COLOR_FRAMEHIGH COLOR_BLACK # define COLOR_FRAMELOW COLOR_BLACK # else # define COLOR_BORDER COLOR_BLACK # define COLOR_BACKGROUND COLOR_BLACK # define COLOR_TEXTHIGH COLOR_WHITE # define COLOR_TEXTLOW COLOR_WHITE # define COLOR_FRAMEHIGH COLOR_WHITE # define COLOR_FRAMELOW COLOR_WHITE # endif # endif #endif #ifndef COLOR_BLACK # define COLOR_BLACK 0 #endif #ifndef COLOR_WHITE # define COLOR_WHITE 1 #endif /* Screen definitions */ #if defined(__CBM610__) # define BIGSCREEN # define MAX_X 80 # define MAX_Y 25 # define DUMP_BYTES 16 #elif defined(__APPLE2__) || defined(__ATARI__) # define MAX_X 40 # define MAX_Y 24 # define DUMP_BYTES 8 #else # define MAX_X 40 # define MAX_Y 25 # define DUMP_BYTES 8 #endif /* Replacement key definitions */ #ifndef CH_DEL # define CH_DEL ('H' - 'A' + 1) /* Ctrl+H */ #endif /* Replacement char definitions */ #ifndef CH_ULCORNER # define CH_ULCORNER '+' #endif #ifndef CH_URCORNER # define CH_URCORNER '+' #endif #ifndef CH_LLCORNER # define CH_LLCORNER '+' #endif #ifndef CH_LRCORNER # define CH_LRCORNER '+' #endif #ifndef CH_TTEE # define CH_TTEE '+' #endif #ifndef CH_LTEE # define CH_LTEE '+' #endif #ifndef CH_RTEE # define CH_RTEE '+' #endif #ifndef CH_BTEE # define CH_BTEE '+' #endif #ifndef CH_CROSS # define CH_CROSS '+' #endif /* Defines for opcodes */ #define OPC_BRK 0x00 #define OPC_BPL 0x10 #define OPC_JSR 0x20 #define OPC_BMI 0x30 #define OPC_RTI 0x40 #define OPC_JMP 0x4C #define OPC_BVC 0x50 #define OPC_RTS 0x60 #define OPC_JMPIND 0x6C #define OPC_BVS 0x70 #define OPC_BCC 0x90 #define OPC_BCS 0xB0 #define OPC_BNE 0xD0 #define OPC_BEQ 0xF0 /* Register values that are used also in the assembler stuff */ extern unsigned char DbgSP; /* Stack pointer */ extern unsigned DbgCS; /* C stack pointer */ extern unsigned DbgHI; /* High 16 bit of primary reg */ /* Descriptor for one text line */ typedef struct { unsigned char x; unsigned char y; char* text; } TextDesc; /* Window descriptor */ typedef struct { unsigned char fd_tl; /* Top left char */ unsigned char fd_tr; /* Top right char */ unsigned char fd_bl; /* Bottom left char */ unsigned char fd_br; /* Bottom right char */ unsigned char fd_x1, fd_y1; /* Upper left corner */ unsigned char fd_x2, fd_y2; /* Lower right corner */ unsigned char fd_width, fd_height; /* Redundant but faster */ unsigned char fd_visible; /* Is the window currently visible? */ char (*fd_func) (void); /* Handler function */ unsigned char fd_textcount; /* Number of text lines to print */ TextDesc* fd_text; /* Static text in the window */ } FrameDesc; /* Texts for the windows */ static TextDesc RegText [] = { { 1, 0, "PC" }, { 1, 1, "SR" }, { 1, 2, "A" }, { 1, 3, "X" }, { 1, 4, "Y" }, { 1, 5, "SP" }, { 1, 6, "CS" }, { 1, 7, "HI" } }; static TextDesc HelpText [] = { { 1, 0, "F1, ? Help" }, { 1, 1, "F2, t Toggle breakpoint" }, { 1, 2, "F3, u Run until subroutine returns" }, { 1, 3, "F4, h Run to cursor" }, { 1, 4, "F7, space Step into" }, { 1, 5, "F8, enter Step over" }, { 1, 6, "1-5 Select active window" }, { 1, 7, "+ Page down" }, { 1, 8, "- Page up" }, { 1, 9, "Cursor Move up/down" }, { 1, 10, "a/z Move up/down" }, { 1, 11, "c Continue" }, { 1, 12, "f Follow instruction" }, { 1, 13, "o Goto origin" }, { 1, 14, "p Use as new PC value" }, { 1, 15, "q Quit" }, { 1, 16, "r Redraw screen" }, { 1, 17, "s Skip next instruction" }, }; /* Window data */ static FrameDesc AsmFrame = { CH_ULCORNER, CH_TTEE, CH_LTEE, CH_CROSS, 0, 0, MAX_X - 10, 15, MAX_X - 11, 14, 1, AsmHandler, 0, 0 }; static FrameDesc RegFrame = { CH_TTEE, CH_URCORNER, CH_LTEE, CH_RTEE, MAX_X - 10, 0, MAX_X - 1, 9, 8, 8, 1, RegHandler, sizeof (RegText) / sizeof (RegText [0]), RegText }; static FrameDesc StackFrame = { CH_LTEE, CH_RTEE, CH_CROSS, CH_RTEE, MAX_X - 10, 9, MAX_X - 1, 15, 8, 5, 1, StackHandler, 0, 0 }; static FrameDesc CStackFrame = { CH_CROSS, CH_RTEE, CH_BTEE, CH_LRCORNER, MAX_X - 10, 15, MAX_X - 1, MAX_Y - 1, 8, MAX_Y - 17, 1, CStackHandler, 0, 0 }; static FrameDesc DumpFrame = { CH_LTEE, CH_CROSS, CH_LLCORNER, CH_BTEE, 0, 15, MAX_X - 10, MAX_Y-1, MAX_X - 11, MAX_Y - 17, 1, DumpHandler, 0, 0 }; static FrameDesc HelpFrame = { CH_ULCORNER, CH_URCORNER, CH_LLCORNER, CH_LRCORNER, 0, 0, MAX_X - 1, MAX_Y-1, MAX_X - 2, MAX_Y - 2, 0, HelpHandler, sizeof (HelpText) / sizeof (HelpText [0]), HelpText }; static FrameDesc* Frames [] = { &AsmFrame, &RegFrame, &StackFrame, &CStackFrame, &DumpFrame, &HelpFrame }; /* Number of active frame, -1 = none */ static int ActiveFrame = -1; /* Window names */ #define WIN_ASM 0 #define WIN_REG 1 #define WIN_STACK 2 #define WIN_CSTACK 3 #define WIN_DUMP 4 #define WIN_HELP 5 /* Other window data */ static unsigned AsmAddr; /* Start address of output */ static unsigned DumpAddr; /* Start address of output */ static unsigned CStackAddr; /* Start address of output */ static unsigned char StackAddr; /* Start address of output */ /* Prompt line data */ static char* ActivePrompt = 0; /* Last prompt line displayed */ static char PromptColor; /* Color behind prompt */ static char PromptLength; /* Length of current prompt string */ /* Values for the bk_use field of struct BreakPoint */ #define BRK_EMPTY 0x00 #define BRK_USER 0x01 #define BRK_TMP 0x80 /* Structure describing a breakpoint */ typedef struct { unsigned bk_addr; /* Address, 0 if unused */ unsigned char bk_opc; /* Opcode */ unsigned char bk_use; /* 1 if in use, 0 otherwise */ } BreakPoint; /* Temporary breakpoints - also accessed from the assembler source */ #define MAX_USERBREAKS 10 unsigned char DbgBreakCount = 0; BreakPoint DbgBreaks [MAX_USERBREAKS+2]; /*****************************************************************************/ /* Forwards for functions in the assembler source */ /*****************************************************************************/ BreakPoint* DbgGetBreakSlot (void); /* Search for a free breakpoint slot. Return a pointer to the slot or 0 */ BreakPoint* DbgIsBreak (unsigned Addr); /* Check if there is a user breakpoint at the given address, if so, return * a pointer to the slot, else return 0. */ /*****************************************************************************/ /* Frame/window drawing code */ /*****************************************************************************/ static void DrawFrame (register FrameDesc* F, char Active) /* Draw one window frame */ { TextDesc* T; unsigned char Count; unsigned char tl, tr, bl, br; unsigned char x1, y1, width; unsigned char OldColor; /* Determine the characters for the corners, set frame color */ if (Active) { OldColor = textcolor (COLOR_FRAMEHIGH); tl = CH_ULCORNER; tr = CH_URCORNER; bl = CH_LLCORNER; br = CH_LRCORNER; } else { OldColor = textcolor (COLOR_FRAMELOW); tl = F->fd_tl; tr = F->fd_tr; bl = F->fd_bl; br = F->fd_br; } /* Get the coordinates into locals for faster access */ x1 = F->fd_x1; y1 = F->fd_y1; width = F->fd_width; /* Top line */ cputcxy (x1, y1, tl); chline (width); cputc (tr); /* Left line */ cvlinexy (x1, ++y1, F->fd_height); /* Bottom line */ cputc (bl); chline (width); cputc (br); /* Right line */ cvlinexy (F->fd_x2, y1, F->fd_height); /* If the window has static text associated, print the text */ (void) textcolor (COLOR_TEXTLOW); Count = F->fd_textcount; T = F->fd_text; while (Count--) { cputsxy (x1 + T->x, y1 + T->y, T->text); ++T; } /* Set the old color */ (void) textcolor (OldColor); } static void DrawFrames (void) /* Draw all frames */ { unsigned char I; FrameDesc* F; /* Build the frame layout of the screen */ for (I = 0; I < sizeof (Frames) / sizeof (Frames [0]); ++I) { F = Frames [I]; if (F->fd_visible) { DrawFrame (F, 0); } } } static void ActivateFrame (int Num, unsigned char Clear) /* Activate a new frame, deactivate the old one */ { unsigned char y; register FrameDesc* F; if (ActiveFrame != Num) { /* Deactivate the old one */ if (ActiveFrame >= 0) { DrawFrame (Frames [ActiveFrame], 0); } /* Activate the new one */ if ((ActiveFrame = Num) >= 0) { F = Frames [ActiveFrame]; /* Clear the frame if requested */ if (Clear) { for (y = F->fd_y1+1; y < F->fd_y2; ++y) { cclearxy (F->fd_x1+1, y, F->fd_width); } } DrawFrame (F, 1); } /* Redraw the current prompt line */ DisplayPrompt (ActivePrompt); } } /*****************************************************************************/ /* Prompt line */ /*****************************************************************************/ static void DisplayPrompt (char* s) /* Display a prompt */ { unsigned char OldColor; /* Remember the current color */ OldColor = textcolor (COLOR_TEXTHIGH); /* Clear the old prompt if there is one */ if (ActivePrompt) { (void) textcolor (PromptColor); chlinexy ((MAX_X - PromptLength) / 2, MAX_Y-1, PromptLength); } /* Get the new prompt data */ ActivePrompt = s; PromptColor = OldColor; PromptLength = strlen (ActivePrompt); /* Display the new prompt */ (void) textcolor (COLOR_TEXTHIGH); cputsxy ((MAX_X - PromptLength) / 2, MAX_Y-1, ActivePrompt); /* Restore the old color */ (void) textcolor (PromptColor); } static void HelpPrompt (void) /* Display a prompt line mentioning the help key */ { DisplayPrompt ("Press F1 for help"); } static void AnyKeyPrompt (void) { DisplayPrompt ("Press any key to continue"); } static char IsAbortKey (char C) /* Return true if C is an abort key */ { #if defined(CH_ESC) if (C == CH_ESC) { return 1; } #endif #if defined(CH_STOP) if (C == CH_STOP) { return 1; } #endif #if !defined(CH_ESC) && !defined(CH_STOP) /* Avoid compiler warning about unused parameter */ (void) C; #endif return 0; } static char Input (char* Prompt, char* Buf, unsigned char Count) /* Read input from the user, return 1 on success, 0 if aborted */ { int Frame; unsigned char OldColor; unsigned char OldCursor; unsigned char x1; unsigned char i; unsigned char done; char c; /* Clear the current prompt line */ cclearxy (0, MAX_Y-1, MAX_X); /* Display the new prompt */ OldColor = textcolor (COLOR_TEXTHIGH); cputsxy (0, MAX_Y-1, Prompt); (void) textcolor (COLOR_TEXTLOW); /* Remember where we are, enable the cursor */ x1 = wherex (); OldCursor = cursor (1); /* Get input and handle it */ i = done = 0; do { c = cgetc (); if (isalnum (c) && i < Count) { Buf [i] = c; cputcxy (x1 + i, MAX_Y-1, c); ++i; } else if (i > 0 && c == CH_DEL) { --i; cputcxy (x1 + i, MAX_Y-1, ' '); gotoxy (x1 + i, MAX_Y-1); } else if (c == '\n') { Buf [i] = '\0'; done = 1; } else if (IsAbortKey (c)) { /* Abort */ done = 2; } } while (!done); /* Reset settings, display old prompt line */ cursor (OldCursor); (void) textcolor (OldColor); DrawFrames (); Frame = ActiveFrame; ActiveFrame = -1; ActivateFrame (Frame, 0); return (done == 1); } static char InputHex (char* Prompt, unsigned* Val) /* Prompt for a hexadecimal value. Return 0 on failure. */ { char Buf [5]; char* P; char C; unsigned V; /* Read input from the user (4 digits max), check input */ if (Input (Prompt, Buf, sizeof (Buf)-1) && isxdigit (Buf [0])) { /* Check the characters and convert to hex */ P = Buf; V = 0; while ((C = *P) && isxdigit (C)) { V <<= 4; if (isdigit (C)) { C -= '0'; } else { C = toupper (C) - ('A' - 10); } V += C; ++P; } /* Assign the value */ *Val = V; /* Success */ return 1; } else { /* Failure */ return 0; } } static void ErrorPrompt (char* Msg) /* Display an error message and wait for a key */ { /* Save the current prompt */ char* OldPrompt = ActivePrompt; /* Display the new one */ DisplayPrompt (Msg); /* Wait for a key and discard it */ cgetc (); /* Restore the old prompt */ DisplayPrompt (OldPrompt); } static char InputGoto (unsigned* Addr) /* Prompt "Goto" and read an address. Print an error and return 0 on failure. */ { char Ok; Ok = InputHex ("Goto: ", Addr); if (!Ok) { ErrorPrompt ("Invalid input - press a key"); } return Ok; } static void BreakInRomError (void) /* Print an error message if we cannot set a breakpoint */ { ErrorPrompt ("Cannot set breakpoint - press a key"); } /*****************************************************************************/ /* Breakpoint handling */ /*****************************************************************************/ static void DbgSetTmpBreak (unsigned Addr) /* Set a breakpoint */ { BreakPoint* B = DbgGetBreakSlot (); B->bk_addr = Addr; B->bk_use = BRK_TMP; } static void DbgToggleUserBreak (unsigned Addr) /* Set a breakpoint */ { register BreakPoint* B = DbgIsBreak (Addr); if (B) { /* We have a breakpoint, remove it */ B->bk_use = BRK_EMPTY; --DbgBreakCount; } else { /* We don't have a breakpoint, set one */ if (DbgBreakCount >= MAX_USERBREAKS) { ErrorPrompt ("Too many breakpoints - press a key"); } else { /* Test if we can set a breakpoint at that address */ if (!DbgIsRAM (Addr)) { BreakInRomError (); } else { /* Set the breakpoint */ B = DbgGetBreakSlot (); B->bk_addr = Addr; B->bk_use = BRK_USER; ++DbgBreakCount; } } } } static void DbgResetTmpBreaks (void) /* Reset all temporary breakpoints */ { unsigned char i; BreakPoint* B = DbgBreaks; for (i = 0; i < MAX_USERBREAKS; ++i) { if (B->bk_use == BRK_TMP) { B->bk_use = BRK_EMPTY; } ++B; } } static unsigned char DbgTmpBreaksOk (void) /* Check if the temporary breakpoints can be set, if so, return 1, if not, * reset them all and return 0. */ { unsigned char i; BreakPoint* B = DbgBreaks; for (i = 0; i < MAX_USERBREAKS; ++i) { if (B->bk_use == BRK_TMP && !DbgIsRAM (B->bk_addr)) { BreakInRomError (); DbgResetTmpBreaks (); return 0; } ++B; } return 1; } /*****************************************************************************/ /* Assembler window stuff */ /*****************************************************************************/ static unsigned AsmBack (unsigned mem, unsigned char lines) /* Go back in the assembler window the given number of lines (calculate * new start address). */ { unsigned cur; unsigned adr [32]; unsigned char in; unsigned offs = 6; while (1) { in = 0; cur = mem - (lines * 3) - offs; while (1) { cur += DbgDisAsmLen (cur); adr [in] = cur; in = (in + 1) & 0x1F; if (cur >= mem) { if (cur == mem || offs == 12) { /* Found */ return adr [(in - lines - 1) & 0x1F]; } else { /* The requested address is inside an instruction, go back * one more byte and try again. */ ++offs; break; } } } } } static unsigned UpdateAsm (void) /* Update the assembler window starting at the given address */ { char buf [MAX_X]; unsigned char len; unsigned char y; unsigned char width = AsmFrame.fd_width; unsigned char x = AsmFrame.fd_x1 + 1; unsigned m = AsmBack (AsmAddr, 2); for (y = AsmFrame.fd_y1+1; y < AsmFrame.fd_y2; ++y) { len = DbgDisAsm (m, buf, width); if (m == brk_pc) { buf [4] = '-'; buf [5] = '>'; } if (DbgIsBreak (m)) { buf [5] = '*'; } if (m == AsmAddr) { revers (1); cputsxy (1, y, buf); revers (0); } else { cputsxy (1, y, buf); } m += len; } return m; } static unsigned AsmArg16 (void) /* Return a 16 bit argument */ { return *(unsigned*)(AsmAddr+1); } static void AsmFollow (void) /* Follow the current instruction */ { switch (*(unsigned char*) AsmAddr) { case OPC_JMP: case OPC_JSR: AsmAddr = AsmArg16 (); break; case OPC_JMPIND: AsmAddr = *(unsigned*)AsmArg16 (); break; case OPC_BPL: case OPC_BMI: case OPC_BVC: case OPC_BVS: case OPC_BCC: case OPC_BCS: case OPC_BNE: case OPC_BEQ: AsmAddr = AsmAddr + 2 + *(signed char*)(AsmAddr+1); break; case OPC_RTS: AsmAddr = (*(unsigned*) (DbgSP + 0x101) + 1); break; case OPC_RTI: AsmAddr = *(unsigned*) (DbgSP + 0x102); break; } } static void AsmHome (void) /* Set the cursor to home position */ { AsmAddr = brk_pc; } static void InitAsm (void) /* Initialize the asm window */ { AsmHome (); UpdateAsm (); } static char AsmHandler (void) /* Get characters and handle them */ { char c; unsigned Last; while (1) { /* Update the window contents */ Last = UpdateAsm (); /* Read and handle input */ switch (c = GetKeyUpdate ()) { case '+': AsmAddr = Last; break; case '-': AsmAddr = AsmBack (AsmAddr, AsmFrame.fd_height); break; case 't': #ifdef CH_F2 case CH_F2: #endif DbgToggleUserBreak (AsmAddr); break; case 'f': AsmFollow (); break; case 'g': InputGoto (&AsmAddr); break; case 'o': AsmHome (); break; case 'p': brk_pc = AsmAddr; break; case 'a': #ifdef CH_CURS_UP case CH_CURS_UP: #endif AsmAddr = AsmBack (AsmAddr, 1); break; case 'z': #ifdef CH_CURS_DOWN case CH_CURS_DOWN: #endif AsmAddr += DbgDisAsmLen (AsmAddr); break; default: return c; } } } /*****************************************************************************/ /* Register window stuff */ /*****************************************************************************/ static unsigned UpdateReg (void) /* Update the register window */ { unsigned char x1 = RegFrame.fd_x1 + 5; unsigned char x2 = x1 + 2; unsigned char y = RegFrame.fd_y1; /* Print the register contents */ gotoxy (x1, ++y); cputhex16 (brk_pc); gotoxy (x2, ++y); cputhex8 (brk_sr); gotoxy (x2, ++y); cputhex8 (brk_a); gotoxy (x2, ++y); cputhex8 (brk_x); gotoxy (x2, ++y); cputhex8 (brk_y); gotoxy (x2, ++y); cputhex8 (DbgSP); gotoxy (x1, ++y); cputhex16 (DbgCS); gotoxy (x1, ++y); cputhex16 (DbgHI); /* Not needed */ return 0; } static void InitReg (void) /* Initialize the register window */ { UpdateReg (); } static char RegHandler (void) /* Get characters and handle them */ { return GetKeyUpdate (); } /*****************************************************************************/ /* Stack window stuff */ /*****************************************************************************/ static unsigned UpdateStack (void) /* Update the stack window */ { unsigned char mem = StackAddr; unsigned char x1 = StackFrame.fd_x1 + 1; unsigned char x2 = x1 + 6; unsigned char y; for (y = StackFrame.fd_y2-1; y > StackFrame.fd_y1; --y) { gotoxy (x1, y); cputhex8 (mem); gotoxy (x2, y); cputhex8 (* (unsigned char*) (mem + 0x100)); ++mem; } return mem; } static void StackHome (void) /* Set the cursor to home position */ { StackAddr = DbgSP + 1; } static void InitStack (void) /* Initialize the stack window */ { StackHome (); UpdateStack (); } static char StackHandler (void) /* Get characters and handle them */ { char c; unsigned char BytesPerPage = StackFrame.fd_height; while (1) { /* Read and handle input */ switch (c = GetKeyUpdate ()) { case '+': StackAddr += BytesPerPage; break; case '-': StackAddr -= BytesPerPage; break; case 'o': StackHome (); break; case 'a': #ifdef CH_CURS_UP: case CH_CURS_UP: #endif --StackAddr; break; case 'z': #ifdef CH_CURS_DOWN case CH_CURS_DOWN: #endif ++StackAddr; break; default: return c; } /* Update the window contents */ UpdateStack (); } } /*****************************************************************************/ /* C Stack window stuff */ /*****************************************************************************/ static unsigned UpdateCStack (void) /* Update the C stack window */ { unsigned mem = CStackAddr; unsigned char x = CStackFrame.fd_x1 + 5; unsigned char y; for (y = CStackFrame.fd_y2-1; y > CStackFrame.fd_y1; --y) { gotoxy (x, y); cputhex16 (* (unsigned*)mem); mem += 2; } cputsxy (CStackFrame.fd_x1+1, CStackFrame.fd_y2-1, "->"); return mem; } static void CStackHome (void) /* Set the cursor to home position */ { CStackAddr = DbgCS; } static void InitCStack (void) /* Initialize the C stack window */ { CStackHome (); UpdateCStack (); } static char CStackHandler (void) /* Get characters and handle them */ { char c; unsigned char BytesPerPage = CStackFrame.fd_height * 2; while (1) { /* Read and handle input */ switch (c = GetKeyUpdate ()) { case '+': CStackAddr += BytesPerPage; break; case '-': CStackAddr -= BytesPerPage; break; case 'o': CStackHome (); break; case 'a': #ifdef CH_CURS_UP case CH_CURS_UP: #endif CStackAddr -= 2; break; case 'z': #ifdef CH_CURS_DOWN case CH_CURS_DOWN: #endif CStackAddr += 2; break; default: return c; } /* Update the window contents */ UpdateCStack (); } } /*****************************************************************************/ /* Dump window stuff */ /*****************************************************************************/ static unsigned UpdateDump (void) /* Update the dump window */ { char Buf [MAX_X]; unsigned char y; unsigned mem = DumpAddr; unsigned char x = DumpFrame.fd_x1 + 1; unsigned char* p = (unsigned char*) mem; for (y = DumpFrame.fd_y1+1; y < DumpFrame.fd_y2; ++y) { cputsxy (x, y, DbgMemDump (mem, Buf, DUMP_BYTES)); mem += DUMP_BYTES; } return mem; } static void DumpHome (void) /* Set the cursor to home position */ { DumpAddr = 0; } static char DumpHandler (void) /* Get characters and handle them */ { char c; unsigned BytesPerPage = DumpFrame.fd_height * 8; while (1) { /* Read and handle input */ switch (c = GetKeyUpdate ()) { case '+': DumpAddr += BytesPerPage; break; case '-': DumpAddr -= BytesPerPage; break; case 'g': InputGoto (&DumpAddr); break; case 'o': DumpHome (); break; case 'a': #ifdef CH_CURS_UP case CH_CURS_UP: #endif DumpAddr -= 8; break; case 'z': #ifdef CH_CURS_DOWN case CH_CURS_DOWN: #endif DumpAddr += 8; break; default: return c; } /* Update the window contents */ UpdateDump (); } } /*****************************************************************************/ /* Help window stuff */ /*****************************************************************************/ static char HelpHandler (void) /* Get characters and handle them */ { /* Activate the frame */ int OldActive = ActiveFrame; ActivateFrame (WIN_HELP, 1); /* Say that we're waiting for a key */ AnyKeyPrompt (); /* Get a character and discard it */ cgetc (); /* Redraw the old stuff */ Redraw (OldActive); /* Done, return no char */ return 0; } /*****************************************************************************/ /* Singlestep */ /*****************************************************************************/ static unsigned GetArg16 (void) /* Read an argument */ { return *(unsigned*)(brk_pc+1); } static unsigned GetStack16 (unsigned char Offs) /* Fetch a 16 bit value from stack top */ { return *(unsigned*)(DbgSP+Offs+0x101); } static void SetRTSBreak (void) /* Set a breakpoint at the return target */ { DbgSetTmpBreak (GetStack16 (0) + 1); } static void SingleStep (char StepInto) { signed char Offs; switch (*(unsigned char*) brk_pc) { case OPC_JMP: /* Set breakpoint at target */ DbgSetTmpBreak (GetArg16 ()); return; case OPC_JMPIND: /* Indirect jump, ignore CPU error when crossing page */ DbgSetTmpBreak (*(unsigned*)GetArg16 ()); return; case OPC_BPL: case OPC_BMI: case OPC_BVC: case OPC_BVS: case OPC_BCC: case OPC_BCS: case OPC_BNE: case OPC_BEQ: /* Be sure not to set the breakpoint twice if this is a jump to * the following instruction. */ Offs = ((signed char*)brk_pc)[1]; if (Offs) { DbgSetTmpBreak (brk_pc + Offs + 2); } break; case OPC_RTS: /* Set a breakpoint at the return target */ SetRTSBreak (); return; case OPC_RTI: /* Set a breakpoint at the return target */ DbgSetTmpBreak (GetStack16 (1)); return; case OPC_JSR: if (StepInto) { /* Set breakpoint at target */ DbgSetTmpBreak (GetArg16 ()); return; } break; } /* Place a breakpoint behind the instruction */ DbgSetTmpBreak (brk_pc + DbgDisAsmLen (brk_pc)); } /*****************************************************************************/ /* High level window handling */ /*****************************************************************************/ static void RedrawStatic (char Frame) /* Redraw static display stuff */ { /* Reset the active frame */ ActiveFrame = -1; /* Clear the screen hide the cursor */ (void) bordercolor (COLOR_BORDER); (void) bgcolor (COLOR_BACKGROUND); clrscr (); cursor (0); /* Build the frame layout of the screen */ (void) textcolor (COLOR_FRAMELOW); DrawFrames (); /* Draw the prompt line */ HelpPrompt (); /* Activate the active frame */ ActivateFrame (Frame, 0); } static void Redraw (char Frame) /* Redraw the display in case it's garbled */ { /* Redraw the static stuff */ RedrawStatic (Frame); /* Init the window contents */ UpdateAsm (); UpdateReg (); UpdateStack (); UpdateCStack (); UpdateDump (); } static char GetKeyUpdate (void) /* Wait for a key updating the windows in the background */ { static unsigned char Win; /* While there are no keys... */ while (!kbhit ()) { switch (Win) { case 0: UpdateAsm (); break; case 1: UpdateStack (); break; case 2: UpdateCStack (); break; case 3: UpdateDump (); break; } Win = (Win + 1) & 0x03; } /* We have a key - return it */ return cgetc (); } /*****************************************************************************/ /* Externally visible functions */ /*****************************************************************************/ void DbgEntry (void) /* Start up the debugger */ { static unsigned char FirstTime = 1; char c; char done; /* If this is the first call, setup the display */ if (FirstTime) { FirstTime = 0; /* Draw the window, default active frame is ASM frame */ RedrawStatic (WIN_ASM); InitAsm (); InitReg (); InitStack (); InitCStack (); UpdateDump (); } /* Only initialize variables here, don't do a display update. The actual * display update will be done while waiting for user input. */ AsmHome (); UpdateReg (); /* Must update this (static later) */ StackHome (); CStackHome (); /* Wait for user input */ done = 0; while (!done) { c = Frames [ActiveFrame]->fd_func (); switch (c) { case '1': case '2': case '3': case '4': case '5': ActivateFrame (c - '1', 0); break; case '?': #ifdef CH_F1 case CH_F1: #endif HelpHandler (); break; case 'u': #ifdef CH_F3 case CH_F3: #endif /* Go until return */ SetRTSBreak (); done = 1; break; case 'h': #ifdef CH_F4 case CH_F4: #endif /* Go to cursor, only possible if cursor not at current PC */ if (AsmAddr != brk_pc) { DbgSetTmpBreak (AsmAddr); done = 1; } break; case ' ': #ifdef CH_F7 case CH_F7: #endif SingleStep (1); if (DbgTmpBreaksOk ()) { /* Could set breakpoints */ done = 1; } break; case '\n': #ifdef CH_F8 case CH_F8: #endif SingleStep (0); if (DbgTmpBreaksOk ()) { /* Could set breakpoints */ done = 1; } break; case 'c': case 0: done = 1; break; case 's': /* Skip instruction */ brk_pc += DbgDisAsmLen (brk_pc); InitAsm (); break; case 'r': /* Redraw screen */ Redraw (ActiveFrame); break; case 'q': /* Quit program */ clrscr (); exit (1); } } }
809
./cc65/src/cc65/textseg.c
/*****************************************************************************/ /* */ /* textseg.c */ /* */ /* Text segment structure */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* Note: This is NOT some sort of code segment, it is used to store lines of * output that are textual (not real code) instead. */ /* common */ #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "output.h" #include "textseg.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ TextSeg* NewTextSeg (SymEntry* Func) /* Create a new text segment, initialize and return it */ { /* Allocate memory for the structure */ TextSeg* S = xmalloc (sizeof (TextSeg)); /* Initialize the fields */ S->Func = Func; InitCollection (&S->Lines); /* Return the new struct */ return S; } void TS_AddVLine (TextSeg* S, const char* Format, va_list ap) /* Add a line to the given text segment */ { /* Format the line */ char Buf [256]; xvsprintf (Buf, sizeof (Buf), Format, ap); /* Add a copy to the data segment */ CollAppend (&S->Lines, xstrdup (Buf)); } void TS_AddLine (TextSeg* S, const char* Format, ...) /* Add a line to the given text segment */ { va_list ap; va_start (ap, Format); TS_AddVLine (S, Format, ap); va_end (ap); } void TS_Output (const TextSeg* S) /* Output the text segment data to the output file */ { unsigned I; /* Get the number of entries in this segment */ unsigned Count = CollCount (&S->Lines); /* If the segment is actually empty, bail out */ if (Count == 0) { return; } /* Output all entries */ for (I = 0; I < Count; ++I) { WriteOutput ("%s\n", (const char*) CollConstAt (&S->Lines, I)); } /* Add an additional newline after the segment output */ WriteOutput ("\n"); }
810
./cc65/src/cc65/compile.c
/*****************************************************************************/ /* */ /* compile.c */ /* */ /* Top level compiler subroutine */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <time.h> /* common */ #include "debugflag.h" #include "version.h" #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "asmlabel.h" #include "asmstmt.h" #include "codegen.h" #include "codeopt.h" #include "compile.h" #include "declare.h" #include "error.h" #include "expr.h" #include "function.h" #include "global.h" #include "input.h" #include "litpool.h" #include "macrotab.h" #include "output.h" #include "pragma.h" #include "preproc.h" #include "standard.h" #include "symtab.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Parse (void) /* Top level parser routine. */ { int comma; SymEntry* Entry; /* Go... */ NextToken (); NextToken (); /* Parse until end of input */ while (CurTok.Tok != TOK_CEOF) { DeclSpec Spec; /* Check for empty statements */ if (CurTok.Tok == TOK_SEMI) { NextToken (); continue; } /* Disallow ASM statements on global level */ if (CurTok.Tok == TOK_ASM) { Error ("__asm__ is not allowed here"); /* Parse and remove the statement for error recovery */ AsmStatement (); ConsumeSemi (); RemoveGlobalCode (); continue; } /* Check for a #pragma */ if (CurTok.Tok == TOK_PRAGMA) { DoPragma (); continue; } /* Read variable defs and functions */ ParseDeclSpec (&Spec, SC_EXTERN | SC_STATIC, T_INT); /* Don't accept illegal storage classes */ if ((Spec.StorageClass & SC_TYPE) == 0) { if ((Spec.StorageClass & SC_AUTO) != 0 || (Spec.StorageClass & SC_REGISTER) != 0) { Error ("Illegal storage class"); Spec.StorageClass = SC_EXTERN | SC_STATIC; } } /* Check if this is only a type declaration */ if (CurTok.Tok == TOK_SEMI) { CheckEmptyDecl (&Spec); NextToken (); continue; } /* Read declarations for this type */ Entry = 0; comma = 0; while (1) { Declaration Decl; /* Read the next declaration */ ParseDecl (&Spec, &Decl, DM_NEED_IDENT); if (Decl.Ident[0] == '\0') { NextToken (); break; } /* Check if we must reserve storage for the variable. We do this, * * - if it is not a typedef or function, * - if we don't had a storage class given ("int i") * - if the storage class is explicitly specified as static, * - or if there is an initialization. * * This means that "extern int i;" will not get storage allocated. */ if ((Decl.StorageClass & SC_FUNC) != SC_FUNC && (Decl.StorageClass & SC_TYPEMASK) != SC_TYPEDEF && ((Spec.Flags & DS_DEF_STORAGE) != 0 || (Decl.StorageClass & (SC_EXTERN|SC_STATIC)) == SC_STATIC || ((Decl.StorageClass & SC_EXTERN) != 0 && CurTok.Tok == TOK_ASSIGN))) { /* We will allocate storage */ Decl.StorageClass |= SC_STORAGE | SC_DEF; } /* If this is a function declarator that is not followed by a comma * or semicolon, it must be followed by a function body. If this is * the case, convert an empty parameter list into one accepting no * parameters (same as void) as required by the standard. */ if ((Decl.StorageClass & SC_FUNC) != 0 && (CurTok.Tok != TOK_COMMA) && (CurTok.Tok != TOK_SEMI)) { FuncDesc* D = GetFuncDesc (Decl.Type); if (D->Flags & FD_EMPTY) { D->Flags = (D->Flags & ~(FD_EMPTY | FD_VARIADIC)) | FD_VOID_PARAM; } } /* Add an entry to the symbol table */ Entry = AddGlobalSym (Decl.Ident, Decl.Type, Decl.StorageClass); /* Add declaration attributes */ SymUseAttr (Entry, &Decl); /* Reserve storage for the variable if we need to */ if (Decl.StorageClass & SC_STORAGE) { /* Get the size of the variable */ unsigned Size = SizeOf (Decl.Type); /* Allow initialization */ if (CurTok.Tok == TOK_ASSIGN) { /* We cannot initialize types of unknown size, or * void types in non ANSI mode. */ if (Size == 0) { if (!IsTypeVoid (Decl.Type)) { if (!IsTypeArray (Decl.Type)) { /* Size is unknown and not an array */ Error ("Variable `%s' has unknown size", Decl.Ident); } } else if (IS_Get (&Standard) != STD_CC65) { /* We cannot declare variables of type void */ Error ("Illegal type for variable `%s'", Decl.Ident); } } /* Switch to the data or rodata segment. For arrays, check * the element qualifiers, since not the array but its * elements are const. */ if (IsQualConst (GetBaseElementType (Decl.Type))) { g_userodata (); } else { g_usedata (); } /* Define a label */ g_defgloblabel (Entry->Name); /* Skip the '=' */ NextToken (); /* Parse the initialization */ ParseInit (Entry->Type); } else { if (IsTypeVoid (Decl.Type)) { /* We cannot declare variables of type void */ Error ("Illegal type for variable `%s'", Decl.Ident); Entry->Flags &= ~(SC_STORAGE | SC_DEF); } else if (Size == 0) { /* Size is unknown. Is it an array? */ if (!IsTypeArray (Decl.Type)) { Error ("Variable `%s' has unknown size", Decl.Ident); } Entry->Flags &= ~(SC_STORAGE | SC_DEF); } /* Allocate storage if it is still needed */ if (Entry->Flags & SC_STORAGE) { /* Switch to the BSS segment */ g_usebss (); /* Define a label */ g_defgloblabel (Entry->Name); /* Allocate space for uninitialized variable */ g_res (Size); } } } /* Check for end of declaration list */ if (CurTok.Tok == TOK_COMMA) { NextToken (); comma = 1; } else { break; } } /* Function declaration? */ if (Entry && IsTypeFunc (Entry->Type)) { /* Function */ if (!comma) { if (CurTok.Tok == TOK_SEMI) { /* Prototype only */ NextToken (); } else { /* Function body. Check for duplicate function definitions */ if (SymIsDef (Entry)) { Error ("Body for function `%s' has already been defined", Entry->Name); } /* Parse the function body */ NewFunc (Entry); } } } else { /* Must be followed by a semicolon */ ConsumeSemi (); } } } void Compile (const char* FileName) /* Top level compile routine. Will setup things and call the parser. */ { char DateStr[32]; char TimeStr[32]; time_t Time; struct tm* TM; /* Since strftime is locale dependent, we need the abbreviated month names * in english. */ static const char MonthNames[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /* Add macros that are always defined */ DefineNumericMacro ("__CC65__", GetVersionAsNumber ()); /* Language standard that is supported */ DefineNumericMacro ("__CC65_STD_C89__", STD_C89); DefineNumericMacro ("__CC65_STD_C99__", STD_C99); DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65); DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard)); /* Optimization macros. Since no source code has been parsed for now, the * IS_Get functions access the values in effect now, regardless of any * changes using #pragma later. */ if (IS_Get (&Optimize)) { long CodeSize = IS_Get (&CodeSizeFactor); DefineNumericMacro ("__OPT__", 1); if (CodeSize > 100) { DefineNumericMacro ("__OPT_i__", CodeSize); } if (IS_Get (&EnableRegVars)) { DefineNumericMacro ("__OPT_r__", 1); } if (IS_Get (&InlineStdFuncs)) { DefineNumericMacro ("__OPT_s__", 1); } } /* __TIME__ and __DATE__ macros */ Time = time (0); TM = localtime (&Time); xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"", MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900); strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM); DefineTextMacro ("__DATE__", DateStr); DefineTextMacro ("__TIME__", TimeStr); /* Other standard macros */ /* DefineNumericMacro ("__STDC__", 1); <- not now */ DefineNumericMacro ("__STDC_HOSTED__", 1); /* Create the base lexical level */ EnterGlobalLevel (); /* Create the global code and data segments */ CreateGlobalSegments (); /* Initialize the literal pool */ InitLiteralPool (); /* Generate the code generator preamble */ g_preamble (); /* Open the input file */ OpenMainFile (FileName); /* Are we supposed to compile or just preprocess the input? */ if (PreprocessOnly) { /* Open the file */ OpenOutputFile (); /* Preprocess each line and write it to the output file */ while (NextLine ()) { Preprocess (); WriteOutput ("%.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } /* Close the output file */ CloseOutputFile (); } else { /* Ok, start the ball rolling... */ Parse (); } if (Debug) { PrintMacroStats (stdout); } /* Print an error report */ ErrorReport (); } void FinishCompile (void) /* Emit literals, externals, debug info, do cleanup and optimizations */ { SymTable* SymTab; SymEntry* Func; /* Walk over all functions, doing cleanup, optimizations ... */ SymTab = GetGlobalSymTab (); Func = SymTab->SymHead; while (Func) { if (SymIsOutputFunc (Func)) { /* Function which is defined and referenced or extern */ MoveLiteralPool (Func->V.F.LitPool); CS_MergeLabels (Func->V.F.Seg->Code); RunOpt (Func->V.F.Seg->Code); } Func = Func->NextSym; } /* Output the literal pool */ OutputLiteralPool (); /* Emit debug infos if enabled */ EmitDebugInfo (); /* Write imported/exported symbols */ EmitExternals (); /* Leave the main lexical level */ LeaveGlobalLevel (); }
811
./cc65/src/cc65/exprdesc.c
/*****************************************************************************/ /* */ /* exprdesc.c */ /* */ /* Expression descriptor structure */ /* */ /* */ /* */ /* (C) 2002-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "strbuf.h" /* cc65 */ #include "asmlabel.h" #include "datatype.h" #include "error.h" #include "exprdesc.h" #include "stackptr.h" #include "symentry.h" #include "exprdesc.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ ExprDesc* ED_Init (ExprDesc* Expr) /* Initialize an ExprDesc */ { Expr->Sym = 0; Expr->Type = 0; Expr->Flags = 0; Expr->Name = 0; Expr->IVal = 0; Expr->FVal = FP_D_Make (0.0); Expr->LVal = 0; Expr->BitOffs = 0; Expr->BitWidth = 0; return Expr; } void ED_MakeBitField (ExprDesc* Expr, unsigned BitOffs, unsigned BitWidth) /* Make this expression a bit field expression */ { Expr->Flags |= E_BITFIELD; Expr->BitOffs = BitOffs; Expr->BitWidth = BitWidth; } void ED_SetCodeRange (ExprDesc* Expr, const CodeMark* Start, const CodeMark* End) /* Set the code range for this expression */ { Expr->Flags |= E_HAVE_MARKS; Expr->Start = *Start; Expr->End = *End; } int ED_CodeRangeIsEmpty (const ExprDesc* Expr) /* Return true if no code was output for this expression */ { /* We must have code marks */ PRECONDITION (Expr->Flags & E_HAVE_MARKS); return CodeRangeIsEmpty (&Expr->Start, &Expr->End); } const char* ED_GetLabelName (const ExprDesc* Expr, long Offs) /* Return the assembler label name of the given expression. Beware: This * function may use a static buffer, so the name may get "lost" on the second * call to the function. */ { static StrBuf Buf = STATIC_STRBUF_INITIALIZER; /* Expr may have it's own offset, adjust Offs accordingly */ Offs += Expr->IVal; /* Generate a label depending on the location */ switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ SB_Printf (&Buf, "$%04X", (int)(Offs & 0xFFFF)); break; case E_LOC_GLOBAL: case E_LOC_STATIC: /* Global or static variable */ if (Offs) { SB_Printf (&Buf, "%s%+ld", SymGetAsmName (Expr->Sym), Offs); } else { SB_Printf (&Buf, "%s", SymGetAsmName (Expr->Sym)); } break; case E_LOC_REGISTER: /* Register variable */ SB_Printf (&Buf, "regbank+%u", (unsigned)((Offs + Expr->Name) & 0xFFFFU)); break; case E_LOC_LITERAL: /* Literal in the literal pool */ if (Offs) { SB_Printf (&Buf, "%s%+ld", LocalLabelName (Expr->Name), Offs); } else { SB_Printf (&Buf, "%s", LocalLabelName (Expr->Name)); } break; default: Internal ("Invalid location in ED_GetLabelName: 0x%04X", ED_GetLoc (Expr)); } /* Return a pointer to the static buffer */ return SB_GetConstBuf (&Buf); } int ED_GetStackOffs (const ExprDesc* Expr, int Offs) /* Get the stack offset of an address on the stack in Expr taking into account * an additional offset in Offs. */ { PRECONDITION (ED_IsLocStack (Expr)); Offs += ((int) Expr->IVal) - StackPtr; CHECK (Offs >= 0); /* Cannot handle negative stack offsets */ return Offs; } ExprDesc* ED_MakeConstAbs (ExprDesc* Expr, long Value, Type* Type) /* Make Expr an absolute const with the given value and type. */ { Expr->Sym = 0; Expr->Type = Type; Expr->Flags = E_LOC_ABS | E_RTYPE_RVAL | (Expr->Flags & E_HAVE_MARKS); Expr->Name = 0; Expr->IVal = Value; Expr->FVal = FP_D_Make (0.0); return Expr; } ExprDesc* ED_MakeConstAbsInt (ExprDesc* Expr, long Value) /* Make Expr a constant integer expression with the given value */ { Expr->Sym = 0; Expr->Type = type_int; Expr->Flags = E_LOC_ABS | E_RTYPE_RVAL | (Expr->Flags & E_HAVE_MARKS); Expr->Name = 0; Expr->IVal = Value; Expr->FVal = FP_D_Make (0.0); return Expr; } ExprDesc* ED_MakeRValExpr (ExprDesc* Expr) /* Convert Expr into a rvalue which is in the primary register without an * offset. */ { Expr->Sym = 0; Expr->Flags &= ~(E_MASK_LOC | E_MASK_RTYPE | E_BITFIELD | E_NEED_TEST | E_CC_SET); Expr->Flags |= (E_LOC_EXPR | E_RTYPE_RVAL); Expr->Name = 0; Expr->IVal = 0; /* No offset */ Expr->FVal = FP_D_Make (0.0); return Expr; } ExprDesc* ED_MakeLValExpr (ExprDesc* Expr) /* Convert Expr into a lvalue which is in the primary register without an * offset. */ { Expr->Sym = 0; Expr->Flags &= ~(E_MASK_LOC | E_MASK_RTYPE | E_BITFIELD | E_NEED_TEST | E_CC_SET); Expr->Flags |= (E_LOC_EXPR | E_RTYPE_LVAL); Expr->Name = 0; Expr->IVal = 0; /* No offset */ Expr->FVal = FP_D_Make (0.0); return Expr; } int ED_IsConst (const ExprDesc* Expr) /* Return true if the expression denotes a constant of some sort. This can be a * numeric constant, the address of a global variable (maybe with offset) or * similar. */ { return ED_IsRVal (Expr) && (Expr->Flags & E_LOC_CONST) != 0; } int ED_IsConstAbsInt (const ExprDesc* Expr) /* Return true if the expression is a constant (numeric) integer. */ { return (Expr->Flags & (E_MASK_LOC|E_MASK_RTYPE)) == (E_LOC_ABS|E_RTYPE_RVAL) && IsClassInt (Expr->Type); } int ED_IsNullPtr (const ExprDesc* Expr) /* Return true if the given expression is a NULL pointer constant */ { return (Expr->Flags & (E_MASK_LOC|E_MASK_RTYPE|E_BITFIELD)) == (E_LOC_ABS|E_RTYPE_RVAL) && Expr->IVal == 0 && IsClassInt (Expr->Type); } int ED_IsBool (const ExprDesc* Expr) /* Return true of the expression can be treated as a boolean, that is, it can * be an operand to a compare operation. */ { /* Either ints, floats, or pointers can be used in a boolean context */ return IsClassInt (Expr->Type) || IsClassFloat (Expr->Type) || IsClassPtr (Expr->Type); } void PrintExprDesc (FILE* F, ExprDesc* E) /* Print an ExprDesc */ { unsigned Flags; char Sep; fprintf (F, "Symbol: %s\n", E->Sym? E->Sym->Name : "(none)"); if (E->Type) { fprintf (F, "Type: "); PrintType (F, E->Type); fprintf (F, "\nRaw type: "); PrintRawType (F, E->Type); } else { fprintf (F, "Type: (unknown)\n" "Raw type: (unknown)\n"); } fprintf (F, "IVal: 0x%08lX\n", E->IVal); fprintf (F, "FVal: %f\n", FP_D_ToFloat (E->FVal)); Flags = E->Flags; Sep = '('; fprintf (F, "Flags: 0x%04X ", Flags); if (Flags & E_LOC_ABS) { fprintf (F, "%cE_LOC_ABS", Sep); Flags &= ~E_LOC_ABS; Sep = ','; } if (Flags & E_LOC_GLOBAL) { fprintf (F, "%cE_LOC_GLOBAL", Sep); Flags &= ~E_LOC_GLOBAL; Sep = ','; } if (Flags & E_LOC_STATIC) { fprintf (F, "%cE_LOC_STATIC", Sep); Flags &= ~E_LOC_STATIC; Sep = ','; } if (Flags & E_LOC_REGISTER) { fprintf (F, "%cE_LOC_REGISTER", Sep); Flags &= ~E_LOC_REGISTER; Sep = ','; } if (Flags & E_LOC_STACK) { fprintf (F, "%cE_LOC_STACK", Sep); Flags &= ~E_LOC_STACK; Sep = ','; } if (Flags & E_LOC_PRIMARY) { fprintf (F, "%cE_LOC_PRIMARY", Sep); Flags &= ~E_LOC_PRIMARY; Sep = ','; } if (Flags & E_LOC_EXPR) { fprintf (F, "%cE_LOC_EXPR", Sep); Flags &= ~E_LOC_EXPR; Sep = ','; } if (Flags & E_LOC_LITERAL) { fprintf (F, "%cE_LOC_LITERAL", Sep); Flags &= ~E_LOC_LITERAL; Sep = ','; } if (Flags & E_RTYPE_LVAL) { fprintf (F, "%cE_RTYPE_LVAL", Sep); Flags &= ~E_RTYPE_LVAL; Sep = ','; } if (Flags & E_BITFIELD) { fprintf (F, "%cE_BITFIELD", Sep); Flags &= ~E_BITFIELD; Sep = ','; } if (Flags & E_NEED_TEST) { fprintf (F, "%cE_NEED_TEST", Sep); Flags &= ~E_NEED_TEST; Sep = ','; } if (Flags & E_CC_SET) { fprintf (F, "%cE_CC_SET", Sep); Flags &= ~E_CC_SET; Sep = ','; } if (Flags) { fprintf (F, "%c,0x%04X", Sep, Flags); Sep = ','; } if (Sep != '(') { fputc (')', F); } fprintf (F, "\nName: 0x%08lX\n", E->Name); } Type* ReplaceType (ExprDesc* Expr, const Type* NewType) /* Replace the type of Expr by a copy of Newtype and return the old type string */ { Type* OldType = Expr->Type; Expr->Type = TypeDup (NewType); return OldType; }
812
./cc65/src/cc65/symtab.c
/*****************************************************************************/ /* */ /* symtab.c */ /* */ /* Symbol table management for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> /* common */ #include "check.h" #include "debugflag.h" #include "hashfunc.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "codegen.h" #include "datatype.h" #include "declare.h" #include "error.h" #include "funcdesc.h" #include "global.h" #include "stackptr.h" #include "symentry.h" #include "typecmp.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* An empty symbol table */ SymTable EmptySymTab = { 0, /* PrevTab */ 0, /* SymHead */ 0, /* SymTail */ 0, /* SymCount */ 1, /* Size */ { 0 } /* Tab[1] */ }; /* Symbol table sizes */ #define SYMTAB_SIZE_GLOBAL 211U #define SYMTAB_SIZE_FUNCTION 29U #define SYMTAB_SIZE_BLOCK 13U #define SYMTAB_SIZE_STRUCT 19U #define SYMTAB_SIZE_LABEL 7U /* The current and root symbol tables */ static unsigned LexicalLevel = 0; /* For safety checks */ static SymTable* SymTab0 = 0; static SymTable* SymTab = 0; static SymTable* TagTab0 = 0; static SymTable* TagTab = 0; static SymTable* LabelTab = 0; /*****************************************************************************/ /* struct SymTable */ /*****************************************************************************/ static SymTable* NewSymTable (unsigned Size) /* Create and return a symbol table for the given lexical level */ { unsigned I; /* Allocate memory for the table */ SymTable* S = xmalloc (sizeof (SymTable) + (Size-1) * sizeof (SymEntry*)); /* Initialize the symbol table structure */ S->PrevTab = 0; S->SymHead = 0; S->SymTail = 0; S->SymCount = 0; S->Size = Size; for (I = 0; I < Size; ++I) { S->Tab[I] = 0; } /* Return the symbol table */ return S; } static void FreeSymTable (SymTable* S) /* Free the given symbo table including all symbols */ { /* Free all symbols */ SymEntry* Sym = S->SymHead; while (Sym) { SymEntry* NextSym = Sym->NextSym; FreeSymEntry (Sym); Sym = NextSym; } /* Free the table itself */ xfree (S); } /*****************************************************************************/ /* Check symbols in a table */ /*****************************************************************************/ static void CheckSymTable (SymTable* Tab) /* Check a symbol table for open references, unused symbols ... */ { SymEntry* Entry = Tab->SymHead; while (Entry) { /* Get the storage flags for tne entry */ unsigned Flags = Entry->Flags; /* Ignore typedef entries */ if (!SymIsTypeDef (Entry)) { /* Check if the symbol is one with storage, and it if it was * defined but not used. */ if (((Flags & SC_AUTO) || (Flags & SC_STATIC)) && (Flags & SC_EXTERN) == 0) { if (SymIsDef (Entry) && !SymIsRef (Entry) && !SymHasAttr (Entry, atUnused)) { if (Flags & SC_PARAM) { if (IS_Get (&WarnUnusedParam)) { Warning ("Parameter `%s' is never used", Entry->Name); } } else { if (IS_Get (&WarnUnusedVar)) { Warning ("`%s' is defined but never used", Entry->Name); } } } } /* If the entry is a label, check if it was defined in the function */ if (Flags & SC_LABEL) { if (!SymIsDef (Entry)) { /* Undefined label */ Error ("Undefined label: `%s'", Entry->Name); } else if (!SymIsRef (Entry)) { /* Defined but not used */ if (IS_Get (&WarnUnusedLabel)) { Warning ("`%s' is defined but never used", Entry->Name); } } } } /* Next entry */ Entry = Entry->NextSym; } } /*****************************************************************************/ /* Handling of lexical levels */ /*****************************************************************************/ unsigned GetLexicalLevel (void) /* Return the current lexical level */ { return LexicalLevel; } void EnterGlobalLevel (void) /* Enter the program global lexical level */ { /* Safety */ PRECONDITION (++LexicalLevel == LEX_LEVEL_GLOBAL); /* Create and assign the symbol table */ SymTab0 = SymTab = NewSymTable (SYMTAB_SIZE_GLOBAL); /* Create and assign the tag table */ TagTab0 = TagTab = NewSymTable (SYMTAB_SIZE_GLOBAL); } void LeaveGlobalLevel (void) /* Leave the program global lexical level */ { /* Safety */ PRECONDITION (LexicalLevel-- == LEX_LEVEL_GLOBAL); /* Check the tables */ CheckSymTable (SymTab0); /* Dump the tables if requested */ if (Debug) { PrintSymTable (SymTab0, stdout, "Global symbol table"); PrintSymTable (TagTab0, stdout, "Global tag table"); } /* Don't delete the symbol and struct tables! */ SymTab = 0; TagTab = 0; } void EnterFunctionLevel (void) /* Enter function lexical level */ { SymTable* S; /* New lexical level */ ++LexicalLevel; /* Get a new symbol table and make it current */ S = NewSymTable (SYMTAB_SIZE_FUNCTION); S->PrevTab = SymTab; SymTab = S; /* Get a new tag table and make it current */ S = NewSymTable (SYMTAB_SIZE_FUNCTION); S->PrevTab = TagTab; TagTab = S; /* Create and assign a new label table */ LabelTab = NewSymTable (SYMTAB_SIZE_LABEL); } void RememberFunctionLevel (struct FuncDesc* F) /* Remember the symbol tables for the level and leave the level without checks */ { /* Leave the lexical level */ --LexicalLevel; /* Remember the tables */ F->SymTab = SymTab; F->TagTab = TagTab; /* Don't delete the tables */ SymTab = SymTab->PrevTab; TagTab = TagTab->PrevTab; } void ReenterFunctionLevel (struct FuncDesc* F) /* Reenter the function lexical level using the existing tables from F */ { /* New lexical level */ ++LexicalLevel; /* Make the tables current again */ F->SymTab->PrevTab = SymTab; SymTab = F->SymTab; F->TagTab->PrevTab = TagTab; TagTab = F->TagTab; /* Create and assign a new label table */ LabelTab = NewSymTable (SYMTAB_SIZE_LABEL); } void LeaveFunctionLevel (void) /* Leave function lexical level */ { /* Leave the lexical level */ --LexicalLevel; /* Check the tables */ CheckSymTable (SymTab); CheckSymTable (LabelTab); /* Drop the label table if it is empty */ if (LabelTab->SymCount == 0) { FreeSymTable (LabelTab); } /* Don't delete the tables */ SymTab = SymTab->PrevTab; TagTab = TagTab->PrevTab; LabelTab = 0; } void EnterBlockLevel (void) /* Enter a nested block in a function */ { SymTable* S; /* New lexical level */ ++LexicalLevel; /* Get a new symbol table and make it current */ S = NewSymTable (SYMTAB_SIZE_BLOCK); S->PrevTab = SymTab; SymTab = S; /* Get a new tag table and make it current */ S = NewSymTable (SYMTAB_SIZE_BLOCK); S->PrevTab = TagTab; TagTab = S; } void LeaveBlockLevel (void) /* Leave a nested block in a function */ { /* Leave the lexical level */ --LexicalLevel; /* Check the tables */ CheckSymTable (SymTab); /* Don't delete the tables */ SymTab = SymTab->PrevTab; TagTab = TagTab->PrevTab; } void EnterStructLevel (void) /* Enter a nested block for a struct definition */ { SymTable* S; /* Get a new symbol table and make it current. Note: Structs and enums * nested in struct scope are NOT local to the struct but visible in the * outside scope. So we will NOT create a new struct or enum table. */ S = NewSymTable (SYMTAB_SIZE_BLOCK); S->PrevTab = SymTab; SymTab = S; } void LeaveStructLevel (void) /* Leave a nested block for a struct definition */ { /* Don't delete the table */ SymTab = SymTab->PrevTab; } /*****************************************************************************/ /* Find functions */ /*****************************************************************************/ static SymEntry* FindSymInTable (const SymTable* T, const char* Name, unsigned Hash) /* Search for an entry in one table */ { /* Get the start of the hash chain */ SymEntry* E = T->Tab [Hash % T->Size]; while (E) { /* Compare the name */ if (strcmp (E->Name, Name) == 0) { /* Found */ return E; } /* Not found, next entry in hash chain */ E = E->NextHash; } /* Not found */ return 0; } static SymEntry* FindSymInTree (const SymTable* Tab, const char* Name) /* Find the symbol with the given name in the table tree that starts with T */ { /* Get the hash over the name */ unsigned Hash = HashStr (Name); /* Check all symbol tables for the symbol */ while (Tab) { /* Try to find the symbol in this table */ SymEntry* E = FindSymInTable (Tab, Name, Hash); /* Bail out if we found it */ if (E != 0) { return E; } /* Repeat the search in the next higher lexical level */ Tab = Tab->PrevTab; } /* Not found */ return 0; } SymEntry* FindSym (const char* Name) /* Find the symbol with the given name */ { return FindSymInTree (SymTab, Name); } SymEntry* FindGlobalSym (const char* Name) /* Find the symbol with the given name in the global symbol table only */ { return FindSymInTable (SymTab0, Name, HashStr (Name)); } SymEntry* FindLocalSym (const char* Name) /* Find the symbol with the given name in the current symbol table only */ { return FindSymInTable (SymTab, Name, HashStr (Name)); } SymEntry* FindTagSym (const char* Name) /* Find the symbol with the given name in the tag table */ { return FindSymInTree (TagTab, Name); } SymEntry* FindStructField (const Type* T, const char* Name) /* Find a struct field in the fields list */ { SymEntry* Field = 0; /* The given type may actually be a pointer to struct */ if (IsTypePtr (T)) { ++T; } /* Non-structs do not have any struct fields... */ if (IsClassStruct (T)) { /* Get a pointer to the struct/union type */ const SymEntry* Struct = GetSymEntry (T); CHECK (Struct != 0); /* Now search in the struct symbol table. Beware: The table may not * exist. */ if (Struct->V.S.SymTab) { Field = FindSymInTable (Struct->V.S.SymTab, Name, HashStr (Name)); } } return Field; } /*****************************************************************************/ /* Add stuff to the symbol table */ /*****************************************************************************/ static void AddSymEntry (SymTable* T, SymEntry* S) /* Add a symbol to a symbol table */ { /* Get the hash value for the name */ unsigned Hash = HashStr (S->Name) % T->Size; /* Insert the symbol into the list of all symbols in this level */ if (T->SymTail) { T->SymTail->NextSym = S; } S->PrevSym = T->SymTail; T->SymTail = S; if (T->SymHead == 0) { /* First symbol */ T->SymHead = S; } ++T->SymCount; /* Insert the symbol into the hash chain */ S->NextHash = T->Tab[Hash]; T->Tab[Hash] = S; /* Tell the symbol in which table it is */ S->Owner = T; } SymEntry* AddStructSym (const char* Name, unsigned Type, unsigned Size, SymTable* Tab) /* Add a struct/union entry and return it */ { SymEntry* Entry; /* Type must be struct or union */ PRECONDITION (Type == SC_STRUCT || Type == SC_UNION); /* Do we have an entry with this name already? */ Entry = FindSymInTable (TagTab, Name, HashStr (Name)); if (Entry) { /* We do have an entry. This may be a forward, so check it. */ if ((Entry->Flags & SC_TYPEMASK) != Type) { /* Existing symbol is not a struct */ Error ("Symbol `%s' is already different kind", Name); } else if (Size > 0 && Entry->V.S.Size > 0) { /* Both structs are definitions. */ Error ("Multiple definition for `%s'", Name); } else { /* Define the struct size if it is given */ if (Size > 0) { Entry->V.S.SymTab = Tab; Entry->V.S.Size = Size; } } } else { /* Create a new entry */ Entry = NewSymEntry (Name, Type); /* Set the struct data */ Entry->V.S.SymTab = Tab; Entry->V.S.Size = Size; /* Add it to the current table */ AddSymEntry (TagTab, Entry); } /* Return the entry */ return Entry; } SymEntry* AddBitField (const char* Name, unsigned Offs, unsigned BitOffs, unsigned Width) /* Add a bit field to the local symbol table and return the symbol entry */ { /* Do we have an entry with this name already? */ SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name)); if (Entry) { /* We have a symbol with this name already */ Error ("Multiple definition for `%s'", Name); } else { /* Create a new entry */ Entry = NewSymEntry (Name, SC_BITFIELD); /* Set the symbol attributes. Bit-fields are always of type unsigned */ Entry->Type = type_uint; Entry->V.B.Offs = Offs; Entry->V.B.BitOffs = BitOffs; Entry->V.B.BitWidth = Width; /* Add the entry to the symbol table */ AddSymEntry (SymTab, Entry); } /* Return the entry */ return Entry; } SymEntry* AddConstSym (const char* Name, const Type* T, unsigned Flags, long Val) /* Add an constant symbol to the symbol table and return it */ { /* Enums must be inserted in the global symbol table */ SymTable* Tab = ((Flags & SC_ENUM) == SC_ENUM)? SymTab0 : SymTab; /* Do we have an entry with this name already? */ SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name)); if (Entry) { if ((Entry->Flags & SC_CONST) != SC_CONST) { Error ("Symbol `%s' is already different kind", Name); } else { Error ("Multiple definition for `%s'", Name); } return Entry; } /* Create a new entry */ Entry = NewSymEntry (Name, Flags); /* Enum values are ints */ Entry->Type = TypeDup (T); /* Set the enum data */ Entry->V.ConstVal = Val; /* Add the entry to the symbol table */ AddSymEntry (Tab, Entry); /* Return the entry */ return Entry; } SymEntry* AddLabelSym (const char* Name, unsigned Flags) /* Add a goto label to the label table */ { /* Do we have an entry with this name already? */ SymEntry* Entry = FindSymInTable (LabelTab, Name, HashStr (Name)); if (Entry) { if (SymIsDef (Entry) && (Flags & SC_DEF) != 0) { /* Trying to define the label more than once */ Error ("Label `%s' is defined more than once", Name); } Entry->Flags |= Flags; } else { /* Create a new entry */ Entry = NewSymEntry (Name, SC_LABEL | Flags); /* Set a new label number */ Entry->V.Label = GetLocalLabel (); /* Generate the assembler name of the label */ Entry->AsmName = xstrdup (LocalLabelName (Entry->V.Label)); /* Add the entry to the label table */ AddSymEntry (LabelTab, Entry); } /* Return the entry */ return Entry; } SymEntry* AddLocalSym (const char* Name, const Type* T, unsigned Flags, int Offs) /* Add a local symbol and return the symbol entry */ { /* Do we have an entry with this name already? */ SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name)); if (Entry) { /* We have a symbol with this name already */ Error ("Multiple definition for `%s'", Name); } else { /* Create a new entry */ Entry = NewSymEntry (Name, Flags); /* Set the symbol attributes */ Entry->Type = TypeDup (T); if ((Flags & SC_AUTO) == SC_AUTO) { Entry->V.Offs = Offs; } else if ((Flags & SC_REGISTER) == SC_REGISTER) { Entry->V.R.RegOffs = Offs; Entry->V.R.SaveOffs = StackPtr; } else if ((Flags & SC_EXTERN) == SC_EXTERN) { Entry->V.Label = Offs; SymSetAsmName (Entry); } else if ((Flags & SC_STATIC) == SC_STATIC) { /* Generate the assembler name from the label number */ Entry->V.Label = Offs; Entry->AsmName = xstrdup (LocalLabelName (Entry->V.Label)); } else if ((Flags & SC_STRUCTFIELD) == SC_STRUCTFIELD) { Entry->V.Offs = Offs; } else { Internal ("Invalid flags in AddLocalSym: %04X", Flags); } /* Add the entry to the symbol table */ AddSymEntry (SymTab, Entry); } /* Return the entry */ return Entry; } SymEntry* AddGlobalSym (const char* Name, const Type* T, unsigned Flags) /* Add an external or global symbol to the symbol table and return the entry */ { /* There is some special handling for functions, so check if it is one */ int IsFunc = IsTypeFunc (T); /* Functions must be inserted in the global symbol table */ SymTable* Tab = IsFunc? SymTab0 : SymTab; /* Do we have an entry with this name already? */ SymEntry* Entry = FindSymInTable (Tab, Name, HashStr (Name)); if (Entry) { Type* EType; /* We have a symbol with this name already */ if (Entry->Flags & SC_TYPE) { Error ("Multiple definition for `%s'", Name); return Entry; } /* Get the type string of the existing symbol */ EType = Entry->Type; /* If we are handling arrays, the old entry or the new entry may be an * incomplete declaration. Accept this, and if the exsting entry is * incomplete, complete it. */ if (IsTypeArray (T) && IsTypeArray (EType)) { /* Get the array sizes */ long Size = GetElementCount (T); long ESize = GetElementCount (EType); if ((Size != UNSPECIFIED && ESize != UNSPECIFIED && Size != ESize) || TypeCmp (T + 1, EType + 1) < TC_EQUAL) { /* Types not identical: Conflicting types */ Error ("Conflicting types for `%s'", Name); return Entry; } else { /* Check if we have a size in the existing definition */ if (ESize == UNSPECIFIED) { /* Existing, size not given, use size from new def */ SetElementCount (EType, Size); } } } else { /* New type must be identical */ if (TypeCmp (EType, T) < TC_EQUAL) { Error ("Conflicting types for `%s'", Name); return Entry; } /* In case of a function, use the new type descriptor, since it * contains pointers to the new symbol tables that are needed if * an actual function definition follows. Be sure not to use the * new descriptor if it contains a function declaration with an * empty parameter list. */ if (IsFunc) { /* Get the function descriptor from the new type */ FuncDesc* F = GetFuncDesc (T); /* Use this new function descriptor if it doesn't contain * an empty parameter list. */ if ((F->Flags & FD_EMPTY) == 0) { Entry->V.F.Func = F; SetFuncDesc (EType, F); } } } /* Add the new flags */ Entry->Flags |= Flags; } else { /* Create a new entry */ Entry = NewSymEntry (Name, Flags); /* Set the symbol attributes */ Entry->Type = TypeDup (T); /* If this is a function, set the function descriptor and clear * additional fields. */ if (IsFunc) { Entry->V.F.Func = GetFuncDesc (Entry->Type); Entry->V.F.Seg = 0; } /* Add the assembler name of the symbol */ SymSetAsmName (Entry); /* Add the entry to the symbol table */ AddSymEntry (Tab, Entry); } /* Return the entry */ return Entry; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ SymTable* GetSymTab (void) /* Return the current symbol table */ { return SymTab; } SymTable* GetGlobalSymTab (void) /* Return the global symbol table */ { return SymTab0; } int SymIsLocal (SymEntry* Sym) /* Return true if the symbol is defined in the highest lexical level */ { return (Sym->Owner == SymTab || Sym->Owner == TagTab); } void MakeZPSym (const char* Name) /* Mark the given symbol as zero page symbol */ { /* Get the symbol table entry */ SymEntry* Entry = FindSymInTable (SymTab, Name, HashStr (Name)); /* Mark the symbol as zeropage */ if (Entry) { Entry->Flags |= SC_ZEROPAGE; } else { Error ("Undefined symbol: `%s'", Name); } } void PrintSymTable (const SymTable* Tab, FILE* F, const char* Header, ...) /* Write the symbol table to the given file */ { unsigned Len; const SymEntry* Entry; /* Print the header */ va_list ap; va_start (ap, Header); fputc ('\n', F); Len = vfprintf (F, Header, ap); va_end (ap); fputc ('\n', F); /* Underline the header */ while (Len--) { fputc ('=', F); } fputc ('\n', F); /* Dump the table */ Entry = Tab->SymHead; if (Entry == 0) { fprintf (F, "(empty)\n"); } else { while (Entry) { DumpSymEntry (F, Entry); Entry = Entry->NextSym; } } fprintf (F, "\n\n\n"); } void EmitExternals (void) /* Write import/export statements for external symbols */ { SymEntry* Entry; Entry = SymTab->SymHead; while (Entry) { unsigned Flags = Entry->Flags; if (Flags & SC_EXTERN) { /* Only defined or referenced externs */ if (SymIsRef (Entry) && !SymIsDef (Entry)) { /* An import */ g_defimport (Entry->Name, Flags & SC_ZEROPAGE); } else if (SymIsDef (Entry)) { /* An export */ g_defexport (Entry->Name, Flags & SC_ZEROPAGE); } } Entry = Entry->NextSym; } } void EmitDebugInfo (void) /* Emit debug infos for the locals of the current scope */ { const char* Head; const SymEntry* Sym; /* Output info for locals if enabled */ if (DebugInfo) { /* For cosmetic reasons in the output file, we will insert two tabs * on global level and just one on local level. */ if (LexicalLevel == LEX_LEVEL_GLOBAL) { Head = "\t.dbg\t\tsym"; } else { Head = "\t.dbg\tsym"; } Sym = SymTab->SymHead; while (Sym) { if ((Sym->Flags & (SC_CONST|SC_TYPE)) == 0) { if (Sym->Flags & SC_AUTO) { AddTextLine ("%s, \"%s\", \"00\", auto, %d", Head, Sym->Name, Sym->V.Offs); } else if (Sym->Flags & SC_REGISTER) { AddTextLine ("%s, \"%s\", \"00\", register, \"regbank\", %d", Head, Sym->Name, Sym->V.R.RegOffs); } else if (SymIsRef (Sym) && !SymIsDef (Sym)) { AddTextLine ("%s, \"%s\", \"00\", %s, \"%s\"", Head, Sym->Name, (Sym->Flags & SC_EXTERN)? "extern" : "static", Sym->AsmName); } } Sym = Sym->NextSym; } } }
813
./cc65/src/cc65/funcdesc.c
/*****************************************************************************/ /* */ /* funcdesc.c */ /* */ /* Function descriptor structure for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" /* cc65 */ #include "funcdesc.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ FuncDesc* NewFuncDesc (void) /* Create a new symbol table with the given name */ { /* Create a new function descriptor */ FuncDesc* F = (FuncDesc*) xmalloc (sizeof (FuncDesc)); /* Nullify the fields */ F->Flags = 0; F->SymTab = 0; F->TagTab = 0; F->ParamCount = 0; F->ParamSize = 0; F->LastParam = 0; /* Return the new struct */ return F; } void FreeFuncDesc (FuncDesc* F) /* Free a function descriptor */ { /* Free the structure */ xfree (F); }
814
./cc65/src/cc65/segments.c
/*****************************************************************************/ /* */ /* segments.c */ /* */ /* Lightweight segment management stuff */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdarg.h> #include <string.h> /* common */ #include "chartype.h" #include "check.h" #include "coll.h" #include "scanner.h" #include "segnames.h" #include "strstack.h" #include "xmalloc.h" /* cc65 */ #include "codeent.h" #include "codeseg.h" #include "dataseg.h" #include "error.h" #include "textseg.h" #include "segments.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Pointer to the current segment list. Output goes here. */ Segments* CS = 0; /* Pointer to the global segment list */ Segments* GS = 0; /* Actual names for the segments */ static StrStack SegmentNames[SEG_COUNT]; /* We're using a collection for the stack instead of a linked list. Since * functions may not be nested (at least in the current implementation), the * maximum stack depth is 2, so there is not really a need for a better * implementation. */ static Collection SegmentStack = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitSegNames (void) /* Initialize the segment names */ { SS_Push (&SegmentNames[SEG_BSS], SEGNAME_BSS); SS_Push (&SegmentNames[SEG_CODE], SEGNAME_CODE); SS_Push (&SegmentNames[SEG_DATA], SEGNAME_DATA); SS_Push (&SegmentNames[SEG_RODATA], SEGNAME_RODATA); } void SetSegName (segment_t Seg, const char* Name) /* Set a new name for a segment */ { SS_Set (&SegmentNames[Seg], Name); } void PushSegName (segment_t Seg, const char* Name) /* Push the current segment name and set a new name for a segment */ { if (SS_IsFull (&SegmentNames[Seg])) { Error ("Segment name stack overflow"); } else { SS_Push (&SegmentNames[Seg], Name); } } void PopSegName (segment_t Seg) /* Restore a segment name from the segment name stack */ { if (SS_GetCount (&SegmentNames[Seg]) < 2) { Error ("Segment name stack is empty"); } else { SS_Drop (&SegmentNames[Seg]); } } const char* GetSegName (segment_t Seg) /* Get the name of the given segment */ { return SS_Get (&SegmentNames[Seg]); } static Segments* NewSegments (SymEntry* Func) /* Initialize a Segments structure (set all fields to NULL) */ { /* Allocate memory */ Segments* S = xmalloc (sizeof (Segments)); /* Initialize the fields */ S->Text = NewTextSeg (Func); S->Code = NewCodeSeg (GetSegName (SEG_CODE), Func); S->Data = NewDataSeg (GetSegName (SEG_DATA), Func); S->ROData = NewDataSeg (GetSegName (SEG_RODATA), Func); S->BSS = NewDataSeg (GetSegName (SEG_BSS), Func); S->CurDSeg = SEG_DATA; /* Return the new struct */ return S; } Segments* PushSegments (SymEntry* Func) /* Make the new segment list current but remember the old one */ { /* Push the current pointer onto the stack */ CollAppend (&SegmentStack, CS); /* Create a new Segments structure */ CS = NewSegments (Func); /* Return the new struct */ return CS; } void PopSegments (void) /* Pop the old segment list (make it current) */ { /* Must have something on the stack */ PRECONDITION (CollCount (&SegmentStack) > 0); /* Pop the last segment and set it as current */ CS = CollPop (&SegmentStack); } void CreateGlobalSegments (void) /* Create the global segments and remember them in GS */ { GS = PushSegments (0); } void UseDataSeg (segment_t DSeg) /* For the current segment list, use the data segment DSeg */ { /* Check the input */ PRECONDITION (CS && DSeg != SEG_CODE); /* Set the new segment to use */ CS->CurDSeg = DSeg; } struct DataSeg* GetDataSeg (void) /* Return the current data segment */ { PRECONDITION (CS != 0); switch (CS->CurDSeg) { case SEG_BSS: return CS->BSS; case SEG_DATA: return CS->Data; case SEG_RODATA: return CS->ROData; default: FAIL ("Invalid data segment"); return 0; } } void AddTextLine (const char* Format, ...) /* Add a line of code to the current text segment */ { va_list ap; va_start (ap, Format); CHECK (CS != 0); TS_AddVLine (CS->Text, Format, ap); va_end (ap); } void AddCodeLine (const char* Format, ...) /* Add a line of code to the current code segment */ { va_list ap; va_start (ap, Format); CHECK (CS != 0); CS_AddVLine (CS->Code, CurTok.LI, Format, ap); va_end (ap); } void AddCode (opc_t OPC, am_t AM, const char* Arg, struct CodeLabel* JumpTo) /* Add a code entry to the current code segment */ { CHECK (CS != 0); CS_AddEntry (CS->Code, NewCodeEntry (OPC, AM, Arg, JumpTo, CurTok.LI)); } void AddDataLine (const char* Format, ...) /* Add a line of data to the current data segment */ { va_list ap; va_start (ap, Format); CHECK (CS != 0); DS_AddVLine (GetDataSeg(), Format, ap); va_end (ap); } int HaveGlobalCode (void) /* Return true if the global code segment contains entries (which is an error) */ { return (CS_GetEntryCount (GS->Code) > 0); } void RemoveGlobalCode (void) /* Remove all code from the global code segment. Used for error recovery. */ { CS_DelEntries (GS->Code, 0, CS_GetEntryCount (GS->Code)); } void OutputSegments (const Segments* S) /* Output the given segments to the output file */ { /* Output the function prologue if the segments came from a function */ CS_OutputPrologue (S->Code); /* Output the text segment */ TS_Output (S->Text); /* Output the three data segments */ DS_Output (S->Data); DS_Output (S->ROData); DS_Output (S->BSS); /* Output the code segment */ CS_Output (S->Code); /* Output the code segment epiloque */ CS_OutputEpilogue (S->Code); }
815
./cc65/src/cc65/asmlabel.c
/*****************************************************************************/ /* */ /* asmlabel.c */ /* */ /* Generate assembler code labels */ /* */ /* */ /* */ /* (C) 2000-2009 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "chartype.h" /* cc65 */ #include "asmlabel.h" #include "error.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned GetLocalLabel (void) /* Get an unused label. Will never return zero. */ { /* Number to generate unique labels */ static unsigned NextLabel = 0; /* Check for an overflow */ if (NextLabel >= 0xFFFF) { Internal ("Local label overflow"); } /* Return the next label */ return ++NextLabel; } const char* LocalLabelName (unsigned L) /* Make a label name from the given label number. The label name will be * created in static storage and overwritten when calling the function * again. */ { static char Buf[64]; sprintf (Buf, "L%04X", L); return Buf; } int IsLocalLabelName (const char* Name) /* Return true if Name is the name of a local label */ { unsigned I; if (Name[0] != 'L' || strlen (Name) != 5) { return 0; } for (I = 1; I <= 4; ++I) { if (!IsXDigit (Name[I])) { return 0; } } /* Local label name */ return 1; }
816
./cc65/src/cc65/opcodes.c
/*****************************************************************************/ /* */ /* opcodes.c */ /* */ /* Opcode and addressing mode definitions */ /* */ /* */ /* */ /* (C) 2001-2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "stdlib.h" #include <string.h> #include <ctype.h> /* common */ #include "check.h" #include "cpu.h" /* cc65 */ #include "codeinfo.h" #include "error.h" #include "opcodes.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Opcode description table */ const OPCDesc OPCTable[OP65_COUNT] = { /* 65XX opcodes */ { OP65_ADC, /* opcode */ "adc", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_AND, /* opcode */ "and", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_ASL, /* opcode */ "asl", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, { OP65_BCC, /* opcode */ "bcc", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA /* flags */ }, { OP65_BCS, /* opcode */ "bcs", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA /* flags */ }, { OP65_BEQ, /* opcode */ "beq", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_ZBRA | OF_FBRA /* flags */ }, { OP65_BIT, /* opcode */ "bit", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_SETF /* flags */ }, { OP65_BMI, /* opcode */ "bmi", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_FBRA /* flags */ }, { OP65_BNE, /* opcode */ "bne", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_ZBRA | OF_FBRA /* flags */ }, { OP65_BPL, /* opcode */ "bpl", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_FBRA /* flags */ }, { OP65_BRA, /* opcode */ "bra", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_UBRA /* flags */ }, { OP65_BRK, /* opcode */ "brk", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_BVC, /* opcode */ "bvc", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA /* flags */ }, { OP65_BVS, /* opcode */ "bvs", /* mnemonic */ 2, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA /* flags */ }, { OP65_CLC, /* opcode */ "clc", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_CLD, /* opcode */ "cld", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_CLI, /* opcode */ "cli", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_CLV, /* opcode */ "clv", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_CMP, /* opcode */ "cmp", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_SETF | OF_CMP /* flags */ }, { OP65_CPX, /* opcode */ "cpx", /* mnemonic */ 0, /* size */ REG_X, /* use */ REG_NONE, /* chg */ OF_SETF | OF_CMP /* flags */ }, { OP65_CPY, /* opcode */ "cpy", /* mnemonic */ 0, /* size */ REG_Y, /* use */ REG_NONE, /* chg */ OF_SETF | OF_CMP /* flags */ }, { OP65_DEA, /* opcode */ "dea", /* mnemonic */ 1, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_DEC, /* opcode */ "dec", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, { OP65_DEX, /* opcode */ "dex", /* mnemonic */ 1, /* size */ REG_X, /* use */ REG_X, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_DEY, /* opcode */ "dey", /* mnemonic */ 1, /* size */ REG_Y, /* use */ REG_Y, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_EOR, /* opcode */ "eor", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_INA, /* opcode */ "ina", /* mnemonic */ 1, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_INC, /* opcode */ "inc", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, { OP65_INX, /* opcode */ "inx", /* mnemonic */ 1, /* size */ REG_X, /* use */ REG_X, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_INY, /* opcode */ "iny", /* mnemonic */ 1, /* size */ REG_Y, /* use */ REG_Y, /* chg */ OF_REG_INCDEC | OF_SETF /* flags */ }, { OP65_JCC, /* opcode */ "jcc", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA /* flags */ }, { OP65_JCS, /* opcode */ "jcs", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA /* flags */ }, { OP65_JEQ, /* opcode */ "jeq", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA | OF_ZBRA | OF_FBRA /* flags */ }, { OP65_JMI, /* opcode */ "jmi", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA | OF_FBRA /* flags */ }, { OP65_JMP, /* opcode */ "jmp", /* mnemonic */ 3, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_UBRA | OF_LBRA /* flags */ }, { OP65_JNE, /* opcode */ "jne", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA | OF_ZBRA | OF_FBRA /* flags */ }, { OP65_JPL, /* opcode */ "jpl", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA | OF_FBRA /* flags */ }, { OP65_JSR, /* opcode */ "jsr", /* mnemonic */ 3, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CALL /* flags */ }, { OP65_JVC, /* opcode */ "jvc", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA /* flags */ }, { OP65_JVS, /* opcode */ "jvs", /* mnemonic */ 5, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_CBRA | OF_LBRA /* flags */ }, { OP65_LDA, /* opcode */ "lda", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_A, /* chg */ OF_LOAD | OF_SETF /* flags */ }, { OP65_LDX, /* opcode */ "ldx", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_X, /* chg */ OF_LOAD | OF_SETF /* flags */ }, { OP65_LDY, /* opcode */ "ldy", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_Y, /* chg */ OF_LOAD | OF_SETF /* flags */ }, { OP65_LSR, /* opcode */ "lsr", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, { OP65_NOP, /* opcode */ "nop", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_ORA, /* opcode */ "ora", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_PHA, /* opcode */ "pha", /* mnemonic */ 1, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_PHP, /* opcode */ "php", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_PHX, /* opcode */ "phx", /* mnemonic */ 1, /* size */ REG_X, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_PHY, /* opcode */ "phy", /* mnemonic */ 1, /* size */ REG_Y, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_PLA, /* opcode */ "pla", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_PLP, /* opcode */ "plp", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_PLX, /* opcode */ "plx", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_X, /* chg */ OF_SETF /* flags */ }, { OP65_PLY, /* opcode */ "ply", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_Y, /* chg */ OF_SETF /* flags */ }, { OP65_ROL, /* opcode */ "rol", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, { OP65_ROR, /* opcode */ "ror", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_SETF | OF_NOIMP /* flags */ }, /* Mark RTI as "uses all registers but doesn't change them", so the * optimizer won't remove preceeding loads. */ { OP65_RTI, /* opcode */ "rti", /* mnemonic */ 1, /* size */ REG_AXY, /* use */ REG_NONE, /* chg */ OF_RET /* flags */ }, { OP65_RTS, /* opcode */ "rts", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_RET /* flags */ }, { OP65_SBC, /* opcode */ "sbc", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_A, /* chg */ OF_SETF /* flags */ }, { OP65_SEC, /* opcode */ "sec", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_SED, /* opcode */ "sed", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_SEI, /* opcode */ "sei", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_NONE /* flags */ }, { OP65_STA, /* opcode */ "sta", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_STORE /* flags */ }, { OP65_STX, /* opcode */ "stx", /* mnemonic */ 0, /* size */ REG_X, /* use */ REG_NONE, /* chg */ OF_STORE /* flags */ }, { OP65_STY, /* opcode */ "sty", /* mnemonic */ 0, /* size */ REG_Y, /* use */ REG_NONE, /* chg */ OF_STORE /* flags */ }, { OP65_STZ, /* opcode */ "stz", /* mnemonic */ 0, /* size */ REG_NONE, /* use */ REG_NONE, /* chg */ OF_STORE /* flags */ }, { OP65_TAX, /* opcode */ "tax", /* mnemonic */ 1, /* size */ REG_A, /* use */ REG_X, /* chg */ OF_XFR | OF_SETF /* flags */ }, { OP65_TAY, /* opcode */ "tay", /* mnemonic */ 1, /* size */ REG_A, /* use */ REG_Y, /* chg */ OF_XFR | OF_SETF /* flags */ }, { OP65_TRB, /* opcode */ "trb", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_SETF /* flags */ }, { OP65_TSB, /* opcode */ "tsb", /* mnemonic */ 0, /* size */ REG_A, /* use */ REG_NONE, /* chg */ OF_SETF /* flags */ }, { OP65_TSX, /* opcode */ "tsx", /* mnemonic */ 1, /* size */ REG_NONE, /* use */ REG_X, /* chg */ OF_XFR | OF_SETF /* flags */ }, { OP65_TXA, /* opcode */ "txa", /* mnemonic */ 1, /* size */ REG_X, /* use */ REG_A, /* chg */ OF_XFR | OF_SETF /* flags */ }, { OP65_TXS, /* opcode */ "txs", /* mnemonic */ 1, /* size */ REG_X, /* use */ REG_NONE, /* chg */ OF_XFR /* flags */ }, { OP65_TYA, /* opcode */ "tya", /* mnemonic */ 1, /* size */ REG_Y, /* use */ REG_A, /* chg */ OF_XFR | OF_SETF /* flags */ }, }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int FindCmp (const void* Key, const void* Desc) /* Compare function for FindOpcode */ { return strcmp (Key, ((OPCDesc*)Desc)->Mnemo); } const OPCDesc* FindOP65 (const char* M) /* Find the given opcode and return the opcode number. If the opcode was not * found, return NULL. */ { unsigned I; unsigned Len; /* Check the length of the given string, then copy it into local * storage, converting it to upper case. */ char Mnemo[sizeof (OPCTable[0].Mnemo)]; Len = strlen (M); if (Len >= sizeof (OPCTable[0].Mnemo)) { /* Invalid length means invalid opcode */ return 0; } for (I = 0; I < Len; ++I) { Mnemo[I] = tolower (M[I]); } Mnemo[I] = '\0'; /* Search for the mnemonic in the table and return the result */ return bsearch (Mnemo, OPCTable, OP65_COUNT, sizeof (OPCTable[0]), FindCmp ); } unsigned GetInsnSize (opc_t OPC, am_t AM) /* Return the size of the given instruction */ { /* Get the opcode desc and check the size given there */ const OPCDesc* D = &OPCTable[OPC]; if (D->Size != 0) { return D->Size; } /* Check the addressing mode. */ switch (AM) { case AM65_IMP: return 1; case AM65_ACC: return 1; case AM65_IMM: return 2; case AM65_ZP: return 2; case AM65_ZPX: return 2; case AM65_ABS: return 3; case AM65_ABSX: return 3; case AM65_ABSY: return 3; case AM65_ZPX_IND: return 2; case AM65_ZP_INDY: return 2; case AM65_ZP_IND: return 2; default: Internal ("Invalid addressing mode"); return 0; } } unsigned char GetAMUseInfo (am_t AM) /* Get usage info for the given addressing mode (addressing modes that use * index registers return REG_r info for these registers). */ { /* Check the addressing mode. */ switch (AM) { case AM65_ACC: return REG_A; case AM65_ZPX: return REG_X; case AM65_ABSX: return REG_X; case AM65_ABSY: return REG_Y; case AM65_ZPX_IND: return REG_X; case AM65_ZP_INDY: return REG_Y; default: return REG_NONE; } } opc_t GetInverseBranch (opc_t OPC) /* Return a branch that reverse the condition of the branch given in OPC */ { switch (OPC) { case OP65_BCC: return OP65_BCS; case OP65_BCS: return OP65_BCC; case OP65_BEQ: return OP65_BNE; case OP65_BMI: return OP65_BPL; case OP65_BNE: return OP65_BEQ; case OP65_BPL: return OP65_BMI; case OP65_BVC: return OP65_BVS; case OP65_BVS: return OP65_BVC; case OP65_JCC: return OP65_JCS; case OP65_JCS: return OP65_JCC; case OP65_JEQ: return OP65_JNE; case OP65_JMI: return OP65_JPL; case OP65_JNE: return OP65_JEQ; case OP65_JPL: return OP65_JMI; case OP65_JVC: return OP65_JVS; case OP65_JVS: return OP65_JVC; default: Internal ("GetInverseBranch: Invalid opcode: %d", OPC); return 0; } } opc_t MakeShortBranch (opc_t OPC) /* Return the short version of the given branch. If the branch is already * a short branch, return the opcode unchanged. */ { switch (OPC) { case OP65_BCC: case OP65_JCC: return OP65_BCC; case OP65_BCS: case OP65_JCS: return OP65_BCS; case OP65_BEQ: case OP65_JEQ: return OP65_BEQ; case OP65_BMI: case OP65_JMI: return OP65_BMI; case OP65_BNE: case OP65_JNE: return OP65_BNE; case OP65_BPL: case OP65_JPL: return OP65_BPL; case OP65_BVC: case OP65_JVC: return OP65_BVC; case OP65_BVS: case OP65_JVS: return OP65_BVS; case OP65_BRA: case OP65_JMP: return (CPUIsets[CPU] & CPU_ISET_65SC02)? OP65_BRA : OP65_JMP; default: Internal ("MakeShortBranch: Invalid opcode: %d", OPC); return 0; } } opc_t MakeLongBranch (opc_t OPC) /* Return the long version of the given branch. If the branch is already * a long branch, return the opcode unchanged. */ { switch (OPC) { case OP65_BCC: case OP65_JCC: return OP65_JCC; case OP65_BCS: case OP65_JCS: return OP65_JCS; case OP65_BEQ: case OP65_JEQ: return OP65_JEQ; case OP65_BMI: case OP65_JMI: return OP65_JMI; case OP65_BNE: case OP65_JNE: return OP65_JNE; case OP65_BPL: case OP65_JPL: return OP65_JPL; case OP65_BVC: case OP65_JVC: return OP65_JVC; case OP65_BVS: case OP65_JVS: return OP65_JVS; case OP65_BRA: case OP65_JMP: return OP65_JMP; default: Internal ("MakeLongBranch: Invalid opcode: %d", OPC); return 0; } } bc_t GetBranchCond (opc_t OPC) /* Get the condition for the conditional branch in OPC */ { switch (OPC) { case OP65_BCC: return BC_CC; case OP65_BCS: return BC_CS; case OP65_BEQ: return BC_EQ; case OP65_BMI: return BC_MI; case OP65_BNE: return BC_NE; case OP65_BPL: return BC_PL; case OP65_BVC: return BC_VC; case OP65_BVS: return BC_VS; case OP65_JCC: return BC_CC; case OP65_JCS: return BC_CS; case OP65_JEQ: return BC_EQ; case OP65_JMI: return BC_MI; case OP65_JNE: return BC_NE; case OP65_JPL: return BC_PL; case OP65_JVC: return BC_VC; case OP65_JVS: return BC_VS; default: Internal ("GetBranchCond: Invalid opcode: %d", OPC); return 0; } } bc_t GetInverseCond (bc_t BC) /* Return the inverse condition of the given one */ { switch (BC) { case BC_CC: return BC_CS; case BC_CS: return BC_CC; case BC_EQ: return BC_NE; case BC_MI: return BC_PL; case BC_NE: return BC_EQ; case BC_PL: return BC_MI; case BC_VC: return BC_VS; case BC_VS: return BC_VC; default: Internal ("GetInverseCond: Invalid condition: %d", BC); return 0; } }
817
./cc65/src/cc65/datatype.c
/*****************************************************************************/ /* */ /* datatype.c */ /* */ /* Type string handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "addrsize.h" #include "check.h" #include "mmodel.h" #include "xmalloc.h" /* cc65 */ #include "codegen.h" #include "datatype.h" #include "error.h" #include "fp.h" #include "funcdesc.h" #include "global.h" #include "symtab.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Predefined type strings */ Type type_schar[] = { TYPE(T_SCHAR), TYPE(T_END) }; Type type_uchar[] = { TYPE(T_UCHAR), TYPE(T_END) }; Type type_int[] = { TYPE(T_INT), TYPE(T_END) }; Type type_uint[] = { TYPE(T_UINT), TYPE(T_END) }; Type type_long[] = { TYPE(T_LONG), TYPE(T_END) }; Type type_ulong[] = { TYPE(T_ULONG), TYPE(T_END) }; Type type_void[] = { TYPE(T_VOID), TYPE(T_END) }; Type type_size_t[] = { TYPE(T_SIZE_T), TYPE(T_END) }; Type type_float[] = { TYPE(T_FLOAT), TYPE(T_END) }; Type type_double[] = { TYPE(T_DOUBLE), TYPE(T_END) }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned TypeLen (const Type* T) /* Return the length of the type string */ { const Type* Start = T; while (T->C != T_END) { ++T; } return T - Start; } Type* TypeCopy (Type* Dest, const Type* Src) /* Copy a type string */ { Type* Orig = Dest; while (1) { *Dest = *Src; if (Src->C == T_END) { break; } Src++; Dest++; } return Orig; } Type* TypeDup (const Type* T) /* Create a copy of the given type on the heap */ { unsigned Len = (TypeLen (T) + 1) * sizeof (Type); return memcpy (xmalloc (Len), T, Len); } Type* TypeAlloc (unsigned Len) /* Allocate memory for a type string of length Len. Len *must* include the * trailing T_END. */ { return xmalloc (Len * sizeof (Type)); } void TypeFree (Type* T) /* Free a type string */ { xfree (T); } int SignExtendChar (int C) /* Do correct sign extension of a character */ { if (IS_Get (&SignedChars) && (C & 0x80) != 0) { return C | ~0xFF; } else { return C & 0xFF; } } TypeCode GetDefaultChar (void) /* Return the default char type (signed/unsigned) depending on the settings */ { return IS_Get (&SignedChars)? T_SCHAR : T_UCHAR; } Type* GetCharArrayType (unsigned Len) /* Return the type for a char array of the given length */ { /* Allocate memory for the type string */ Type* T = TypeAlloc (3); /* array/char/terminator */ /* Fill the type string */ T[0].C = T_ARRAY; T[0].A.L = Len; /* Array length is in the L attribute */ T[1].C = GetDefaultChar (); T[2].C = T_END; /* Return the new type */ return T; } Type* GetImplicitFuncType (void) /* Return a type string for an inplicitly declared function */ { /* Get a new function descriptor */ FuncDesc* F = NewFuncDesc (); /* Allocate memory for the type string */ Type* T = TypeAlloc (3); /* func/returns int/terminator */ /* Prepare the function descriptor */ F->Flags = FD_EMPTY | FD_VARIADIC; F->SymTab = &EmptySymTab; F->TagTab = &EmptySymTab; /* Fill the type string */ T[0].C = T_FUNC | CodeAddrSizeQualifier (); T[0].A.P = F; T[1].C = T_INT; T[2].C = T_END; /* Return the new type */ return T; } Type* PointerTo (const Type* T) /* Return a type string that is "pointer to T". The type string is allocated * on the heap and may be freed after use. */ { /* Get the size of the type string including the terminator */ unsigned Size = TypeLen (T) + 1; /* Allocate the new type string */ Type* P = TypeAlloc (Size + 1); /* Create the return type... */ P[0].C = T_PTR | (T[0].C & T_QUAL_ADDRSIZE); memcpy (P+1, T, Size * sizeof (Type)); /* ...and return it */ return P; } static TypeCode PrintTypeComp (FILE* F, TypeCode C, TypeCode Mask, const char* Name) /* Check for a specific component of the type. If it is there, print the * name and remove it. Return the type with the component removed. */ { if ((C & Mask) == Mask) { fprintf (F, "%s ", Name); C &= ~Mask; } return C; } void PrintType (FILE* F, const Type* T) /* Output translation of type array. */ { /* Walk over the type string */ while (T->C != T_END) { /* Get the type code */ TypeCode C = T->C; /* Print any qualifiers */ C = PrintTypeComp (F, C, T_QUAL_CONST, "const"); C = PrintTypeComp (F, C, T_QUAL_VOLATILE, "volatile"); C = PrintTypeComp (F, C, T_QUAL_RESTRICT, "restrict"); C = PrintTypeComp (F, C, T_QUAL_NEAR, "__near__"); C = PrintTypeComp (F, C, T_QUAL_FAR, "__far__"); C = PrintTypeComp (F, C, T_QUAL_FASTCALL, "__fastcall__"); C = PrintTypeComp (F, C, T_QUAL_CDECL, "__cdecl__"); /* Signedness. Omit the signedness specifier for long and int */ if ((C & T_MASK_TYPE) != T_TYPE_INT && (C & T_MASK_TYPE) != T_TYPE_LONG) { C = PrintTypeComp (F, C, T_SIGN_SIGNED, "signed"); } C = PrintTypeComp (F, C, T_SIGN_UNSIGNED, "unsigned"); /* Now check the real type */ switch (C & T_MASK_TYPE) { case T_TYPE_CHAR: fprintf (F, "char"); break; case T_TYPE_SHORT: fprintf (F, "short"); break; case T_TYPE_INT: fprintf (F, "int"); break; case T_TYPE_LONG: fprintf (F, "long"); break; case T_TYPE_LONGLONG: fprintf (F, "long long"); break; case T_TYPE_FLOAT: fprintf (F, "float"); break; case T_TYPE_DOUBLE: fprintf (F, "double"); break; case T_TYPE_VOID: fprintf (F, "void"); break; case T_TYPE_STRUCT: fprintf (F, "struct %s", ((SymEntry*) T->A.P)->Name); break; case T_TYPE_UNION: fprintf (F, "union %s", ((SymEntry*) T->A.P)->Name); break; case T_TYPE_ARRAY: /* Recursive call */ PrintType (F, T + 1); if (T->A.L == UNSPECIFIED) { fprintf (F, "[]"); } else { fprintf (F, "[%ld]", T->A.L); } return; case T_TYPE_PTR: /* Recursive call */ PrintType (F, T + 1); fprintf (F, "*"); return; case T_TYPE_FUNC: fprintf (F, "function returning "); break; default: fprintf (F, "unknown type: %04lX", T->C); } /* Next element */ ++T; } } void PrintFuncSig (FILE* F, const char* Name, Type* T) /* Print a function signature. */ { /* Get the function descriptor */ const FuncDesc* D = GetFuncDesc (T); /* Print a comment with the function signature */ PrintType (F, GetFuncReturn (T)); if (IsQualNear (T)) { fprintf (F, " __near__"); } if (IsQualFar (T)) { fprintf (F, " __far__"); } if (IsQualFastcall (T)) { fprintf (F, " __fastcall__"); } if (IsQualCDecl (T)) { fprintf (F, " __cdecl__"); } fprintf (F, " %s (", Name); /* Parameters */ if (D->Flags & FD_VOID_PARAM) { fprintf (F, "void"); } else { unsigned I; SymEntry* E = D->SymTab->SymHead; for (I = 0; I < D->ParamCount; ++I) { if (I > 0) { fprintf (F, ", "); } if (SymIsRegVar (E)) { fprintf (F, "register "); } PrintType (F, E->Type); E = E->NextSym; } } /* End of parameter list */ fprintf (F, ")"); } void PrintRawType (FILE* F, const Type* T) /* Print a type string in raw format (for debugging) */ { while (T->C != T_END) { fprintf (F, "%04lX ", T->C); ++T; } fprintf (F, "\n"); } int TypeHasAttr (const Type* T) /* Return true if the given type has attribute data */ { return IsClassStruct (T) || IsTypeArray (T) || IsClassFunc (T); } unsigned SizeOf (const Type* T) /* Compute size of object represented by type array. */ { switch (UnqualifiedType (T->C)) { case T_VOID: return 0; /* Assume voids have size zero */ case T_SCHAR: case T_UCHAR: return SIZEOF_CHAR; case T_SHORT: case T_USHORT: return SIZEOF_SHORT; case T_INT: case T_UINT: return SIZEOF_INT; case T_PTR: case T_FUNC: /* Maybe pointer to function */ return SIZEOF_PTR; case T_LONG: case T_ULONG: return SIZEOF_LONG; case T_LONGLONG: case T_ULONGLONG: return SIZEOF_LONGLONG; case T_ENUM: return SIZEOF_INT; case T_FLOAT: return SIZEOF_FLOAT; case T_DOUBLE: return SIZEOF_DOUBLE; case T_STRUCT: case T_UNION: return ((SymEntry*) T->A.P)->V.S.Size; case T_ARRAY: if (T->A.L == UNSPECIFIED) { /* Array with unspecified size */ return 0; } else { return T->A.L * SizeOf (T + 1); } default: Internal ("Unknown type in SizeOf: %04lX", T->C); return 0; } } unsigned PSizeOf (const Type* T) /* Compute size of pointer object. */ { /* We are expecting a pointer expression */ CHECK (IsClassPtr (T)); /* Skip the pointer or array token itself */ return SizeOf (T + 1); } unsigned CheckedSizeOf (const Type* T) /* Return the size of a data type. If the size is zero, emit an error and * return some valid size instead (so the rest of the compiler doesn't have * to work with invalid sizes). */ { unsigned Size = SizeOf (T); if (Size == 0) { Error ("Size of data type is unknown"); Size = SIZEOF_CHAR; /* Don't return zero */ } return Size; } unsigned CheckedPSizeOf (const Type* T) /* Return the size of a data type that is pointed to by a pointer. If the * size is zero, emit an error and return some valid size instead (so the * rest of the compiler doesn't have to work with invalid sizes). */ { unsigned Size = PSizeOf (T); if (Size == 0) { Error ("Size of data type is unknown"); Size = SIZEOF_CHAR; /* Don't return zero */ } return Size; } unsigned TypeOf (const Type* T) /* Get the code generator base type of the object */ { switch (UnqualifiedType (T->C)) { case T_SCHAR: return CF_CHAR; case T_UCHAR: return CF_CHAR | CF_UNSIGNED; case T_SHORT: case T_INT: case T_ENUM: return CF_INT; case T_USHORT: case T_UINT: case T_PTR: case T_ARRAY: return CF_INT | CF_UNSIGNED; case T_LONG: return CF_LONG; case T_ULONG: return CF_LONG | CF_UNSIGNED; case T_FLOAT: case T_DOUBLE: /* These two are identical in the backend */ return CF_FLOAT; case T_FUNC: return (((FuncDesc*) T->A.P)->Flags & FD_VARIADIC)? 0 : CF_FIXARGC; case T_STRUCT: case T_UNION: /* Address of ... */ return CF_INT | CF_UNSIGNED; default: Error ("Illegal type %04lX", T->C); return CF_INT; } } Type* Indirect (Type* T) /* Do one indirection for the given type, that is, return the type where the * given type points to. */ { /* We are expecting a pointer expression */ CHECK (IsClassPtr (T)); /* Skip the pointer or array token itself */ return T + 1; } Type* ArrayToPtr (Type* T) /* Convert an array to a pointer to it's first element */ { /* Return pointer to first element */ return PointerTo (GetElementType (T)); } int IsVariadicFunc (const Type* T) /* Return true if this is a function type or pointer to function type with * variable parameter list */ { FuncDesc* F = GetFuncDesc (T); return (F->Flags & FD_VARIADIC) != 0; } FuncDesc* GetFuncDesc (const Type* T) /* Get the FuncDesc pointer from a function or pointer-to-function type */ { if (UnqualifiedType (T->C) == T_PTR) { /* Pointer to function */ ++T; } /* Be sure it's a function type */ CHECK (IsClassFunc (T)); /* Get the function descriptor from the type attributes */ return T->A.P; } void SetFuncDesc (Type* T, FuncDesc* F) /* Set the FuncDesc pointer in a function or pointer-to-function type */ { if (UnqualifiedType (T->C) == T_PTR) { /* Pointer to function */ ++T; } /* Be sure it's a function type */ CHECK (IsClassFunc (T)); /* Set the function descriptor */ T->A.P = F; } Type* GetFuncReturn (Type* T) /* Return a pointer to the return type of a function or pointer-to-function type */ { if (UnqualifiedType (T->C) == T_PTR) { /* Pointer to function */ ++T; } /* Be sure it's a function type */ CHECK (IsClassFunc (T)); /* Return a pointer to the return type */ return T + 1; } long GetElementCount (const Type* T) /* Get the element count of the array specified in T (which must be of * array type). */ { CHECK (IsTypeArray (T)); return T->A.L; } void SetElementCount (Type* T, long Count) /* Set the element count of the array specified in T (which must be of * array type). */ { CHECK (IsTypeArray (T)); T->A.L = Count; } Type* GetElementType (Type* T) /* Return the element type of the given array type. */ { CHECK (IsTypeArray (T)); return T + 1; } Type* GetBaseElementType (Type* T) /* Return the base element type of a given type. If T is not an array, this * will return. Otherwise it will return the base element type, which means * the element type that is not an array. */ { while (IsTypeArray (T)) { ++T; } return T; } SymEntry* GetSymEntry (const Type* T) /* Return a SymEntry pointer from a type */ { /* Only structs or unions have a SymEntry attribute */ CHECK (IsClassStruct (T)); /* Return the attribute */ return T->A.P; } void SetSymEntry (Type* T, SymEntry* S) /* Set the SymEntry pointer for a type */ { /* Only structs or unions have a SymEntry attribute */ CHECK (IsClassStruct (T)); /* Set the attribute */ T->A.P = S; } Type* IntPromotion (Type* T) /* Apply the integer promotions to T and return the result. The returned type * string may be T if there is no need to change it. */ { /* We must have an int to apply int promotions */ PRECONDITION (IsClassInt (T)); /* An integer can represent all values from either signed or unsigned char, * so convert chars to int and leave all other types alone. */ if (IsTypeChar (T)) { return type_int; } else { return T; } } Type* PtrConversion (Type* T) /* If the type is a function, convert it to pointer to function. If the * expression is an array, convert it to pointer to first element. Otherwise * return T. */ { if (IsTypeFunc (T)) { return PointerTo (T); } else if (IsTypeArray (T)) { return ArrayToPtr (T); } else { return T; } } TypeCode AddrSizeQualifier (unsigned AddrSize) /* Return T_QUAL_NEAR or T_QUAL_FAR depending on the address size */ { switch (AddrSize) { case ADDR_SIZE_ABS: return T_QUAL_NEAR; case ADDR_SIZE_FAR: return T_QUAL_FAR; default: Error ("Invalid address size"); return T_QUAL_NEAR; } }
818
./cc65/src/cc65/lineinfo.c
/*****************************************************************************/ /* */ /* lineinfo.c */ /* */ /* Source file line info structure */ /* */ /* */ /* */ /* (C) 2001 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "chartype.h" #include "check.h" #include "xmalloc.h" /* cc65 */ #include "global.h" #include "input.h" #include "lineinfo.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Global pointer to line information for the current line */ static LineInfo* CurLineInfo = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static LineInfo* NewLineInfo (struct IFile* F, unsigned LineNum, const StrBuf* Line) /* Create and return a new line info. Ref count will be 1. */ { unsigned Len; LineInfo* LI; const char* S; char* T; /* Get the length of the line and a pointer to the line buffer */ Len = SB_GetLen (Line); S = SB_GetConstBuf (Line); /* Skip leading spaces in Line */ while (Len > 0 && IsBlank (*S)) { ++S; --Len; } /* Allocate memory for the line info and the input line */ LI = xmalloc (sizeof (LineInfo) + Len); /* Initialize the fields */ LI->RefCount = 1; LI->InputFile = F; LI->LineNum = LineNum; /* Copy the line, replacing tabs by spaces in the given line since tabs * will give rather arbitrary results when used in the output later, and * if we do it here, we won't need another copy later. */ T = LI->Line; while (Len--) { if (*S == '\t') { *T = ' '; } else { *T = *S; } ++S; ++T; } /* Add the terminator */ *T = '\0'; /* Return the new struct */ return LI; } static void FreeLineInfo (LineInfo* LI) /* Free a LineInfo structure */ { xfree (LI); } LineInfo* UseLineInfo (LineInfo* LI) /* Increase the reference count of the given line info and return it. */ { CHECK (LI != 0); ++LI->RefCount; return LI; } void ReleaseLineInfo (LineInfo* LI) /* Release a reference to the given line info, free the structure if the * reference count drops to zero. */ { CHECK (LI && LI->RefCount > 0); if (--LI->RefCount == 0) { /* No more references, free it */ FreeLineInfo (LI); } } LineInfo* GetCurLineInfo (void) /* Return a pointer to the current line info. The reference count is NOT * increased, use UseLineInfo for that purpose. */ { return CurLineInfo; } void UpdateLineInfo (struct IFile* F, unsigned LineNum, const StrBuf* Line) /* Update the line info - called if a new line is read */ { /* If a current line info exists, release it */ if (CurLineInfo) { ReleaseLineInfo (CurLineInfo); } /* If we have intermixed assembly switched off, use an empty line instead * of the supplied one to save some memory. */ if (!AddSource) { Line = &EmptyStrBuf; } /* Create a new line info */ CurLineInfo = NewLineInfo (F, LineNum, Line); } const char* GetInputName (const LineInfo* LI) /* Return the file name from a line info */ { PRECONDITION (LI != 0); return GetInputFile (LI->InputFile); } unsigned GetInputLine (const LineInfo* LI) /* Return the line number from a line info */ { PRECONDITION (LI != 0); return LI->LineNum; }
819
./cc65/src/cc65/coptadd.c
/*****************************************************************************/ /* */ /* coptadd.c */ /* */ /* Optimize addition sequences */ /* */ /* */ /* */ /* (C) 2001-2005, Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptadd.h" /*****************************************************************************/ /* Optimize additions */ /*****************************************************************************/ unsigned OptAdd1 (CodeSeg* S) /* Search for the sequence * * ldy #xx * jsr ldaxysp * jsr pushax * ldy #yy * jsr ldaxysp * jsr tosaddax * * and replace it by: * * ldy #xx-1 * lda (sp),y * ldy #yy-3 * clc * adc (sp),y * pha * ldy #xx * lda (sp),y * ldy #yy-2 * adc (sp),y * tax * pla */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[6]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && !CS_RangeHasLabel (S, I+1, 5) && CS_GetEntries (S, L+1, I+1, 5) && CE_IsCallTo (L[1], "ldaxysp") && CE_IsCallTo (L[2], "pushax") && L[3]->OPC == OP65_LDY && CE_IsConstImm (L[3]) && CE_IsCallTo (L[4], "ldaxysp") && CE_IsCallTo (L[5], "tosaddax")) { CodeEntry* X; const char* Arg; /* Correct the stack of the first Y register load */ CE_SetNumArg (L[0], L[0]->Num - 1); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+1); /* ldy #yy-3 */ Arg = MakeHexArg (L[3]->Num - 3); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[4]->LI); CS_InsertEntry (S, X, I+2); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[5]->LI); CS_InsertEntry (S, X, I+3); /* adc (sp),y */ X = NewCodeEntry (OP65_ADC, AM65_ZP_INDY, "sp", 0, L[5]->LI); CS_InsertEntry (S, X, I+4); /* pha */ X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, L[5]->LI); CS_InsertEntry (S, X, I+5); /* ldy #xx (beware: L[0] has changed) */ Arg = MakeHexArg (L[0]->Num + 1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+6); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+7); /* ldy #yy-2 */ Arg = MakeHexArg (L[3]->Num - 2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[4]->LI); CS_InsertEntry (S, X, I+8); /* adc (sp),y */ X = NewCodeEntry (OP65_ADC, AM65_ZP_INDY, "sp", 0, L[5]->LI); CS_InsertEntry (S, X, I+9); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[5]->LI); CS_InsertEntry (S, X, I+10); /* pla */ X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, L[5]->LI); CS_InsertEntry (S, X, I+11); /* Delete the old code */ CS_DelEntries (S, I+12, 5); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptAdd2 (CodeSeg* S) /* Search for the sequence * * ldy #xx * jsr ldaxysp * ldy #yy * jsr addeqysp * * and replace it by: * * ldy #xx-1 * lda (sp),y * ldy #yy * clc * adc (sp),y * sta (sp),y * ldy #xx * lda (sp),y * ldy #yy+1 * adc (sp),y * sta (sp),y * * provided that a/x is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 3) && CE_IsCallTo (L[1], "ldaxysp") && L[2]->OPC == OP65_LDY && CE_IsConstImm (L[2]) && CE_IsCallTo (L[3], "addeqysp") && (GetRegInfo (S, I+4, REG_AX) & REG_AX) == 0) { /* Insert new code behind the addeqysp */ const char* Arg; CodeEntry* X; /* ldy #xx-1 */ Arg = MakeHexArg (L[0]->Num-1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+5); /* ldy #yy */ X = NewCodeEntry (OP65_LDY, AM65_IMM, L[2]->Arg, 0, L[2]->LI); CS_InsertEntry (S, X, I+6); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+7); /* adc (sp),y */ X = NewCodeEntry (OP65_ADC, AM65_ZP_INDY, "sp", 0, L[3]->LI); CS_InsertEntry (S, X, I+8); /* sta (sp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, "sp", 0, L[3]->LI); CS_InsertEntry (S, X, I+9); /* ldy #xx */ X = NewCodeEntry (OP65_LDY, AM65_IMM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+10); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+11); /* ldy #yy+1 */ Arg = MakeHexArg (L[2]->Num+1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[2]->LI); CS_InsertEntry (S, X, I+12); /* adc (sp),y */ X = NewCodeEntry (OP65_ADC, AM65_ZP_INDY, "sp", 0, L[3]->LI); CS_InsertEntry (S, X, I+13); /* sta (sp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, "sp", 0, L[3]->LI); CS_InsertEntry (S, X, I+14); /* Delete the old code */ CS_DelEntries (S, I, 4); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptAdd3 (CodeSeg* S) /* Search for the sequence * * jsr pushax * ldx #$00 * lda xxx * jsr tosaddax * * and replace it by * * clc * adc xxx * bcc L1 * inx * L1: */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "pushax") && CS_GetEntries (S, L+1, I+1, 4) && !CS_RangeHasLabel (S, I+1, 3) && L[1]->OPC == OP65_LDX && CE_IsKnownImm (L[1], 0) && L[2]->OPC == OP65_LDA && CE_IsCallTo (L[3], "tosaddax")) { CodeEntry* X; CodeLabel* Label; /* Insert new code behind the sequence */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+4); /* adc xxx */ X = NewCodeEntry (OP65_ADC, L[2]->AM, L[2]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+5); /* bcc L1 */ Label = CS_GenLabel (S, L[4]); X = NewCodeEntry (OP65_BCC, AM65_BRA, Label->Name, Label, L[3]->LI); CS_InsertEntry (S, X, I+6); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+7); /* Delete the old code */ CS_DelEntries (S, I, 4); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptAdd4 (CodeSeg* S) /* Search for the sequence * * jsr pushax * lda xxx * ldx yyy * jsr tosaddax * * and replace it by * * clc * adc xxx * pha * txa * adc yyy * tax * pla */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "pushax") && CS_GetEntries (S, L+1, I+1, 3) && !CS_RangeHasLabel (S, I+1, 3) && L[1]->OPC == OP65_LDA && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP) && L[2]->OPC == OP65_LDX && (L[2]->AM == AM65_ABS || L[2]->AM == AM65_ZP) && CE_IsCallTo (L[3], "tosaddax")) { CodeEntry* X; /* Insert new code behind the sequence */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+4); /* adc xxx */ X = NewCodeEntry (OP65_ADC, L[1]->AM, L[1]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+5); /* pha */ X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+6); /* txa */ X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+7); /* adc yyy */ X = NewCodeEntry (OP65_ADC, L[2]->AM, L[2]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+8); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+9); /* pla */ X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+10); /* Delete the old code */ CS_DelEntries (S, I, 4); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptAdd5 (CodeSeg* S) /* Search for a call to incaxn and replace it by an 8 bit add if the X register * is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* E; /* Get next entry */ E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && strncmp (E->Arg, "incax", 5) == 0 && IsDigit (E->Arg[5]) && E->Arg[6] == '\0' && !RegXUsed (S, I+1)) { CodeEntry* X; const char* Arg; /* Insert new code behind the sequence */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+1); Arg = MakeHexArg (E->Arg[5] - '0'); X = NewCodeEntry (OP65_ADC, AM65_IMM, Arg, 0, E->LI); CS_InsertEntry (S, X, I+2); /* Delete the old code */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptAdd6 (CodeSeg* S) /* Search for the sequence * * adc ... * bcc L * inx * L: * * and remove the handling of the high byte if X is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_ADC && CS_GetEntries (S, L, I+1, 3) && (L[0]->OPC == OP65_BCC || L[0]->OPC == OP65_JCC) && L[0]->JumpTo != 0 && !CE_HasLabel (L[0]) && L[1]->OPC == OP65_INX && !CE_HasLabel (L[1]) && L[0]->JumpTo->Owner == L[2] && !RegXUsed (S, I+3)) { /* Remove the bcs/dex */ CS_DelEntries (S, I+1, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
820
./cc65/src/cc65/stackptr.c
/*****************************************************************************/ /* */ /* stackptr.c */ /* */ /* Manage the parameter stack pointer */ /* */ /* */ /* */ /* (C) 2004-2006 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "stackptr.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Compiler relative stackpointer */ int StackPtr = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SP_Push (const Type* T) /* Adjust the stackpointer for a push of an argument of the given type */ { StackPtr -= SizeOf (T); } void SP_Pop (const Type* T) /* Adjust the stackpointer for a pop of an argument of the given type */ { StackPtr += SizeOf (T); }
821
./cc65/src/cc65/coptneg.c
/*****************************************************************************/ /* */ /* coptneg.c */ /* */ /* Optimize negation sequences */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptneg.h" /*****************************************************************************/ /* bnega optimizations */ /*****************************************************************************/ unsigned OptBNegA1 (CodeSeg* S) /* Check for * * ldx #$00 * lda .. * jsr bnega * * Remove the ldx if the lda does not use it. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a ldx */ if (E->OPC == OP65_LDX && E->AM == AM65_IMM && (E->Flags & CEF_NUMARG) != 0 && E->Num == 0 && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_LDA && (L[0]->Use & REG_X) == 0 && !CE_HasLabel (L[0]) && CE_IsCallTo (L[1], "bnega") && !CE_HasLabel (L[1])) { /* Remove the ldx instruction */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegA2 (CodeSeg* S) /* Check for * * lda .. * jsr bnega * jeq/jne .. * * Adjust the conditional branch and remove the call to the subroutine. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if ((E->OPC == OP65_ADC || E->OPC == OP65_AND || E->OPC == OP65_DEA || E->OPC == OP65_EOR || E->OPC == OP65_INA || E->OPC == OP65_LDA || E->OPC == OP65_ORA || E->OPC == OP65_PLA || E->OPC == OP65_SBC || E->OPC == OP65_TXA || E->OPC == OP65_TYA) && CS_GetEntries (S, L, I+1, 2) && CE_IsCallTo (L[0], "bnega") && !CE_HasLabel (L[0]) && (L[1]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[1])) { /* Invert the branch */ CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC)); /* Delete the subroutine call */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* bnegax optimizations */ /*****************************************************************************/ unsigned OptBNegAX1 (CodeSeg* S) /* On a call to bnegax, if X is zero, the result depends only on the value in * A, so change the call to a call to bnega. This will get further optimized * later if possible. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to bnegax, and if X is known and zero */ if (E->RI->In.RegX == 0 && CE_IsCallTo (E, "bnegax")) { CodeEntry* X = NewCodeEntry (OP65_JSR, AM65_ABS, "bnega", 0, E->LI); CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX2 (CodeSeg* S) /* Search for the sequence: * * ldy #xx * jsr ldaxysp * jsr bnegax * jne/jeq ... * * and replace it by * * ldy #xx * lda (sp),y * dey * ora (sp),y * jeq/jne ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 3) && CE_IsCallTo (L[1], "ldaxysp") && CE_IsCallTo (L[2], "bnegax") && (L[3]->Info & OF_ZBRA) != 0) { CodeEntry* X; /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+1); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* ora (sp),y */ X = NewCodeEntry (OP65_ORA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* Invert the branch */ CE_ReplaceOPC (L[3], GetInverseBranch (L[3]->OPC)); /* Delete the entries no longer needed. */ CS_DelEntries (S, I+4, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX3 (CodeSeg* S) /* Search for the sequence: * * lda xx * ldx yy * jsr bnegax * jne/jeq ... * * and replace it by * * lda xx * ora xx+1 * jeq/jne ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_LDA && CS_GetEntries (S, L, I+1, 3) && L[0]->OPC == OP65_LDX && !CE_HasLabel (L[0]) && CE_IsCallTo (L[1], "bnegax") && !CE_HasLabel (L[1]) && (L[2]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[2])) { /* ldx --> ora */ CE_ReplaceOPC (L[0], OP65_ORA); /* Invert the branch */ CE_ReplaceOPC (L[2], GetInverseBranch (L[2]->OPC)); /* Delete the subroutine call */ CS_DelEntry (S, I+2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptBNegAX4 (CodeSeg* S) /* Search for the sequence: * * jsr xxx * jsr bnega(x) * jeq/jne ... * * and replace it by: * * jsr xxx * <boolean test> * jne/jeq ... */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg,"bnega",5) == 0 && !CE_HasLabel (L[0]) && (L[1]->Info & OF_ZBRA) != 0 && !CE_HasLabel (L[1])) { CodeEntry* X; /* Check if we're calling bnega or bnegax */ int ByteSized = (strcmp (L[0]->Arg, "bnega") == 0); /* Insert apropriate test code */ if (ByteSized) { /* Test bytes */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); } else { /* Test words */ X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, I+3); } /* Delete the subroutine call */ CS_DelEntry (S, I+1); /* Invert the branch */ CE_ReplaceOPC (L[1], GetInverseBranch (L[1]->OPC)); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* negax optimizations */ /*****************************************************************************/ unsigned OptNegAX1 (CodeSeg* S) /* Search for a call to negax and replace it by * * eor #$FF * clc * adc #$01 * * if X isn't used later. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X isn't used later */ if (CE_IsCallTo (E, "negax") && !RegXUsed (S, I+1)) { CodeEntry* X; /* Add replacement code behind */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_ADC, AM65_IMM, "$01", 0, E->LI); CS_InsertEntry (S, X, I+3); /* Delete the call to negax */ CS_DelEntry (S, I); /* Skip the generated code */ I += 2; /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptNegAX2 (CodeSeg* S) /* Search for a call to negax and replace it by * * ldx #$FF * eor #$FF * clc * adc #$01 * bne L1 * inx * L1: * * if X is known and zero on entry. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* P; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X is known and zero */ if (E->RI->In.RegX == 0 && CE_IsCallTo (E, "negax") && (P = CS_GetNextEntry (S, I)) != 0) { CodeEntry* X; CodeLabel* L; /* Add replacement code behind */ /* ldx #$FF */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); /* eor #$FF */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+2); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+3); /* adc #$01 */ X = NewCodeEntry (OP65_ADC, AM65_IMM, "$01", 0, E->LI); CS_InsertEntry (S, X, I+4); /* Get the label attached to the insn following the call */ L = CS_GenLabel (S, P); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, X, I+5); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+6); /* Delete the call to negax */ CS_DelEntry (S, I); /* Skip the generated code */ I += 5; /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* complax optimizations */ /*****************************************************************************/ unsigned OptComplAX1 (CodeSeg* S) /* Search for a call to complax and replace it by * * eor #$FF * * if X isn't used later. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a call to negax, and if X isn't used later */ if (CE_IsCallTo (E, "complax") && !RegXUsed (S, I+1)) { CodeEntry* X; /* Add replacement code behind */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$FF", 0, E->LI); CS_InsertEntry (S, X, I+1); /* Delete the call to negax */ CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
822
./cc65/src/cc65/stmt.c
/*****************************************************************************/ /* */ /* stmt.c */ /* */ /* Parse a statement */ /* */ /* */ /* */ /* (C) 1998-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "coll.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "function.h" #include "global.h" #include "goto.h" #include "litpool.h" #include "loadexpr.h" #include "locals.h" #include "loop.h" #include "pragma.h" #include "scanner.h" #include "stackptr.h" #include "stmt.h" #include "swstmt.h" #include "symtab.h" #include "testexpr.h" #include "typeconv.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static int CheckLabelWithoutStatement (void) /* Called from Statement() after a label definition. Will check for a * following closing curly brace. This means that a label is not followed * by a statement which is required by the standard. Output an error if so. */ { if (CurTok.Tok == TOK_RCURLY) { Error ("Label at end of compound statement"); return 1; } else { return 0; } } static void CheckTok (token_t Tok, const char* Msg, int* PendingToken) /* Helper function for Statement. Will check for Tok and print Msg if not * found. If PendingToken is NULL, it will the skip the token, otherwise * it will store one to PendingToken. */ { if (CurTok.Tok != Tok) { Error ("%s", Msg); } else if (PendingToken) { *PendingToken = 1; } else { NextToken (); } } static void CheckSemi (int* PendingToken) /* Helper function for Statement. Will check for a semicolon and print an * error message if not found (plus some error recovery). If PendingToken is * NULL, it will the skip the token, otherwise it will store one to * PendingToken. * This function is a special version of CheckTok with the addition of the * error recovery. */ { int HaveToken = (CurTok.Tok == TOK_SEMI); if (!HaveToken) { Error ("`;' expected"); /* Try to be smart about errors */ if (CurTok.Tok == TOK_COLON || CurTok.Tok == TOK_COMMA) { HaveToken = 1; } } if (HaveToken) { if (PendingToken) { *PendingToken = 1; } else { NextToken (); } } } static void SkipPending (int PendingToken) /* Skip the pending token if we have one */ { if (PendingToken) { NextToken (); } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int IfStatement (void) /* Handle an 'if' statement */ { unsigned Label1; unsigned TestResult; int GotBreak; /* Skip the if */ NextToken (); /* Generate a jump label and parse the condition */ Label1 = GetLocalLabel (); TestResult = TestInParens (Label1, 0); /* Parse the if body */ GotBreak = Statement (0); /* Else clause present? */ if (CurTok.Tok != TOK_ELSE) { g_defcodelabel (Label1); /* Since there's no else clause, we're not sure, if the a break * statement is really executed. */ return 0; } else { /* Generate a jump around the else branch */ unsigned Label2 = GetLocalLabel (); g_jump (Label2); /* Skip the else */ NextToken (); /* If the if expression was always true, the code in the else branch * is never executed. Output a warning if this is the case. */ if (TestResult == TESTEXPR_TRUE) { Warning ("Unreachable code"); } /* Define the target for the first test */ g_defcodelabel (Label1); /* Total break only if both branches had a break. */ GotBreak &= Statement (0); /* Generate the label for the else clause */ g_defcodelabel (Label2); /* Done */ return GotBreak; } } static void DoStatement (void) /* Handle the 'do' statement */ { /* Get the loop control labels */ unsigned LoopLabel = GetLocalLabel (); unsigned BreakLabel = GetLocalLabel (); unsigned ContinueLabel = GetLocalLabel (); /* Skip the while token */ NextToken (); /* Add the loop to the loop stack */ AddLoop (BreakLabel, ContinueLabel); /* Define the loop label */ g_defcodelabel (LoopLabel); /* Parse the loop body */ Statement (0); /* Output the label for a continue */ g_defcodelabel (ContinueLabel); /* Parse the end condition */ Consume (TOK_WHILE, "`while' expected"); TestInParens (LoopLabel, 1); ConsumeSemi (); /* Define the break label */ g_defcodelabel (BreakLabel); /* Remove the loop from the loop stack */ DelLoop (); } static void WhileStatement (void) /* Handle the 'while' statement */ { int PendingToken; CodeMark CondCodeStart; /* Start of condition evaluation code */ CodeMark CondCodeEnd; /* End of condition evaluation code */ CodeMark Here; /* "Here" location of code */ /* Get the loop control labels */ unsigned LoopLabel = GetLocalLabel (); unsigned BreakLabel = GetLocalLabel (); unsigned CondLabel = GetLocalLabel (); /* Skip the while token */ NextToken (); /* Add the loop to the loop stack. In case of a while loop, the condition * label is used for continue statements. */ AddLoop (BreakLabel, CondLabel); /* We will move the code that evaluates the while condition to the end of * the loop, so generate a jump here. */ g_jump (CondLabel); /* Remember the current position */ GetCodePos (&CondCodeStart); /* Emit the code position label */ g_defcodelabel (CondLabel); /* Test the loop condition */ TestInParens (LoopLabel, 1); /* Remember the end of the condition evaluation code */ GetCodePos (&CondCodeEnd); /* Define the head label */ g_defcodelabel (LoopLabel); /* Loop body */ Statement (&PendingToken); /* Move the test code here */ GetCodePos (&Here); MoveCode (&CondCodeStart, &CondCodeEnd, &Here); /* Exit label */ g_defcodelabel (BreakLabel); /* Eat remaining tokens that were delayed because of line info * correctness */ SkipPending (PendingToken); /* Remove the loop from the loop stack */ DelLoop (); } static void ReturnStatement (void) /* Handle the 'return' statement */ { ExprDesc Expr; NextToken (); if (CurTok.Tok != TOK_SEMI) { /* Evaluate the return expression */ hie0 (&Expr); /* If we return something in a void function, print an error and * ignore the value. Otherwise convert the value to the type of the * return. */ if (F_HasVoidReturn (CurrentFunc)) { Error ("Returning a value in function with return type void"); } else { /* Convert the return value to the type of the function result */ TypeConversion (&Expr, F_GetReturnType (CurrentFunc)); /* Load the value into the primary */ LoadExpr (CF_NONE, &Expr); } } else if (!F_HasVoidReturn (CurrentFunc) && !F_HasOldStyleIntRet (CurrentFunc)) { Error ("Function `%s' must return a value", F_GetFuncName (CurrentFunc)); } /* Mark the function as having a return statement */ F_ReturnFound (CurrentFunc); /* Cleanup the stack in case we're inside a block with locals */ g_space (StackPtr - F_GetTopLevelSP (CurrentFunc)); /* Output a jump to the function exit code */ g_jump (F_GetRetLab (CurrentFunc)); } static void BreakStatement (void) /* Handle the 'break' statement */ { LoopDesc* L; /* Skip the break */ NextToken (); /* Get the current loop descriptor */ L = CurrentLoop (); /* Check if we are inside a loop */ if (L == 0) { /* Error: No current loop */ Error ("`break' statement not within loop or switch"); return; } /* Correct the stack pointer if needed */ g_space (StackPtr - L->StackPtr); /* Jump to the exit label of the loop */ g_jump (L->BreakLabel); } static void ContinueStatement (void) /* Handle the 'continue' statement */ { LoopDesc* L; /* Skip the continue */ NextToken (); /* Get the current loop descriptor */ L = CurrentLoop (); if (L) { /* Search for a loop that has a continue label. */ do { if (L->ContinueLabel) { break; } L = L->Next; } while (L); } /* Did we find it? */ if (L == 0) { Error ("`continue' statement not within a loop"); return; } /* Correct the stackpointer if needed */ g_space (StackPtr - L->StackPtr); /* Jump to next loop iteration */ g_jump (L->ContinueLabel); } static void ForStatement (void) /* Handle a 'for' statement */ { ExprDesc lval1; ExprDesc lval3; int HaveIncExpr; CodeMark IncExprStart; CodeMark IncExprEnd; int PendingToken; /* Get several local labels needed later */ unsigned TestLabel = GetLocalLabel (); unsigned BreakLabel = GetLocalLabel (); unsigned IncLabel = GetLocalLabel (); unsigned BodyLabel = GetLocalLabel (); /* Skip the FOR token */ NextToken (); /* Add the loop to the loop stack. A continue jumps to the start of the * the increment condition. */ AddLoop (BreakLabel, IncLabel); /* Skip the opening paren */ ConsumeLParen (); /* Parse the initializer expression */ if (CurTok.Tok != TOK_SEMI) { Expression0 (&lval1); } ConsumeSemi (); /* Label for the test expressions */ g_defcodelabel (TestLabel); /* Parse the test expression */ if (CurTok.Tok != TOK_SEMI) { Test (BodyLabel, 1); g_jump (BreakLabel); } else { g_jump (BodyLabel); } ConsumeSemi (); /* Remember the start of the increment expression */ GetCodePos (&IncExprStart); /* Label for the increment expression */ g_defcodelabel (IncLabel); /* Parse the increment expression */ HaveIncExpr = (CurTok.Tok != TOK_RPAREN); if (HaveIncExpr) { Expression0 (&lval3); } /* Jump to the test */ g_jump (TestLabel); /* Remember the end of the increment expression */ GetCodePos (&IncExprEnd); /* Skip the closing paren */ ConsumeRParen (); /* Loop body */ g_defcodelabel (BodyLabel); Statement (&PendingToken); /* If we had an increment expression, move the code to the bottom of * the loop. In this case we don't need to jump there at the end of * the loop body. */ if (HaveIncExpr) { CodeMark Here; GetCodePos (&Here); MoveCode (&IncExprStart, &IncExprEnd, &Here); } else { /* Jump back to the increment expression */ g_jump (IncLabel); } /* Skip a pending token if we have one */ SkipPending (PendingToken); /* Declare the break label */ g_defcodelabel (BreakLabel); /* Remove the loop from the loop stack */ DelLoop (); } static int CompoundStatement (void) /* Compound statement. Allow any number of statements inside braces. The * function returns true if the last statement was a break or return. */ { int GotBreak; /* Remember the stack at block entry */ int OldStack = StackPtr; /* Enter a new lexical level */ EnterBlockLevel (); /* Parse local variable declarations if any */ DeclareLocals (); /* Now process statements in this block */ GotBreak = 0; while (CurTok.Tok != TOK_RCURLY) { if (CurTok.Tok != TOK_CEOF) { GotBreak = Statement (0); } else { break; } } /* Clean up the stack. */ if (!GotBreak) { g_space (StackPtr - OldStack); } StackPtr = OldStack; /* Emit references to imports/exports for this block */ EmitExternals (); /* Leave the lexical level */ LeaveBlockLevel (); return GotBreak; } int Statement (int* PendingToken) /* Statement parser. Returns 1 if the statement does a return/break, returns * 0 otherwise. If the PendingToken pointer is not NULL, the function will * not skip the terminating token of the statement (closing brace or * semicolon), but store true if there is a pending token, and false if there * is none. The token is always checked, so there is no need for the caller to * check this token, it must be skipped, however. If the argument pointer is * NULL, the function will skip the token. */ { ExprDesc Expr; int GotBreak; CodeMark Start, End; /* Assume no pending token */ if (PendingToken) { *PendingToken = 0; } /* Check for a label. A label is always part of a statement, it does not * replace one. */ while (CurTok.Tok == TOK_IDENT && NextTok.Tok == TOK_COLON) { /* Handle the label */ DoLabel (); if (CheckLabelWithoutStatement ()) { return 0; } } switch (CurTok.Tok) { case TOK_LCURLY: NextToken (); GotBreak = CompoundStatement (); CheckTok (TOK_RCURLY, "`{' expected", PendingToken); return GotBreak; case TOK_IF: return IfStatement (); case TOK_WHILE: WhileStatement (); break; case TOK_DO: DoStatement (); break; case TOK_SWITCH: SwitchStatement (); break; case TOK_RETURN: ReturnStatement (); CheckSemi (PendingToken); return 1; case TOK_BREAK: BreakStatement (); CheckSemi (PendingToken); return 1; case TOK_CONTINUE: ContinueStatement (); CheckSemi (PendingToken); return 1; case TOK_FOR: ForStatement (); break; case TOK_GOTO: GotoStatement (); CheckSemi (PendingToken); return 1; case TOK_SEMI: /* Ignore it */ CheckSemi (PendingToken); break; case TOK_PRAGMA: DoPragma (); break; case TOK_CASE: CaseLabel (); CheckLabelWithoutStatement (); break; case TOK_DEFAULT: DefaultLabel (); CheckLabelWithoutStatement (); break; default: /* Remember the current code position */ GetCodePos (&Start); /* Actual statement */ ExprWithCheck (hie0, &Expr); /* Load the result only if it is an lvalue and the type is * marked as volatile. Otherwise the load is useless. */ if (ED_IsLVal (&Expr) && IsQualVolatile (Expr.Type)) { LoadExpr (CF_NONE, &Expr); } /* If the statement didn't generate code, and is not of type * void, emit a warning. */ GetCodePos (&End); if (CodeRangeIsEmpty (&Start, &End) && !IsTypeVoid (Expr.Type) && IS_Get (&WarnNoEffect)) { Warning ("Statement has no effect"); } CheckSemi (PendingToken); } return 0; }
823
./cc65/src/cc65/error.c
/*****************************************************************************/ /* */ /* error.c */ /* */ /* Error handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> /* common */ #include "print.h" /* cc65 */ #include "global.h" #include "input.h" #include "lineinfo.h" #include "scanner.h" #include "stmt.h" #include "error.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Count of errors/warnings */ unsigned ErrorCount = 0; unsigned WarningCount = 0; /* Warning and error options */ IntStack WarnEnable = INTSTACK(1); /* Enable warnings */ IntStack WarningsAreErrors = INTSTACK(0); /* Treat warnings as errors */ /* Warn about: */ IntStack WarnConstComparison= INTSTACK(1); /* - constant comparison results */ IntStack WarnNoEffect = INTSTACK(1); /* - statements without an effect */ IntStack WarnStructParam = INTSTACK(1); /* - structs passed by val */ IntStack WarnUnusedLabel = INTSTACK(1); /* - unused labels */ IntStack WarnUnusedParam = INTSTACK(1); /* - unused parameters */ IntStack WarnUnusedVar = INTSTACK(1); /* - unused variables */ IntStack WarnUnknownPragma = INTSTACK(1); /* - unknown #pragmas */ /* Map the name of a warning to the intstack that holds its state */ typedef struct WarnMapEntry WarnMapEntry; struct WarnMapEntry { IntStack* Stack; const char* Name; }; static WarnMapEntry WarnMap[] = { /* Keep sorted, even if this isn't used for now */ { &WarningsAreErrors, "error" }, { &WarnConstComparison, "const-comparison" }, { &WarnNoEffect, "no-effect" }, { &WarnStructParam, "struct-param" }, { &WarnUnknownPragma, "unknown-pragma" }, { &WarnUnusedLabel, "unused-label" }, { &WarnUnusedParam, "unused-param" }, { &WarnUnusedVar, "unused-var" }, }; /*****************************************************************************/ /* Handling of fatal errors */ /*****************************************************************************/ void Fatal (const char* Format, ...) /* Print a message about a fatal error and die */ { va_list ap; const char* FileName; unsigned LineNum; if (CurTok.LI) { FileName = GetInputName (CurTok.LI); LineNum = GetInputLine (CurTok.LI); } else { FileName = GetCurrentFile (); LineNum = GetCurrentLine (); } fprintf (stderr, "%s(%u): Fatal: ", FileName, LineNum); va_start (ap, Format); vfprintf (stderr, Format, ap); va_end (ap); fprintf (stderr, "\n"); if (Line) { Print (stderr, 1, "Input: %.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } exit (EXIT_FAILURE); } void Internal (const char* Format, ...) /* Print a message about an internal compiler error and die. */ { va_list ap; const char* FileName; unsigned LineNum; if (CurTok.LI) { FileName = GetInputName (CurTok.LI); LineNum = GetInputLine (CurTok.LI); } else { FileName = GetCurrentFile (); LineNum = GetCurrentLine (); } fprintf (stderr, "%s(%u): Internal compiler error:\n", FileName, LineNum); va_start (ap, Format); vfprintf (stderr, Format, ap); va_end (ap); fprintf (stderr, "\n"); if (Line) { fprintf (stderr, "\nInput: %.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } /* Use abort to create a core dump */ abort (); } /*****************************************************************************/ /* Handling of errors */ /*****************************************************************************/ static void IntError (const char* Filename, unsigned LineNo, const char* Msg, va_list ap) /* Print an error message - internal function*/ { fprintf (stderr, "%s(%u): Error: ", Filename, LineNo); vfprintf (stderr, Msg, ap); fprintf (stderr, "\n"); if (Line) { Print (stderr, 1, "Input: %.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } ++ErrorCount; if (ErrorCount > 10) { Fatal ("Too many errors"); } } void Error (const char* Format, ...) /* Print an error message */ { va_list ap; va_start (ap, Format); IntError (GetInputName (CurTok.LI), GetInputLine (CurTok.LI), Format, ap); va_end (ap); } void LIError (const LineInfo* LI, const char* Format, ...) /* Print an error message with the line info given explicitly */ { va_list ap; va_start (ap, Format); IntError (GetInputName (LI), GetInputLine (LI), Format, ap); va_end (ap); } void PPError (const char* Format, ...) /* Print an error message. For use within the preprocessor. */ { va_list ap; va_start (ap, Format); IntError (GetCurrentFile(), GetCurrentLine(), Format, ap); va_end (ap); } /*****************************************************************************/ /* Handling of warnings */ /*****************************************************************************/ static void IntWarning (const char* Filename, unsigned LineNo, const char* Msg, va_list ap) /* Print warning message - internal function. */ { if (IS_Get (&WarningsAreErrors)) { /* Treat the warning as an error */ IntError (Filename, LineNo, Msg, ap); } else if (IS_Get (&WarnEnable)) { fprintf (stderr, "%s(%u): Warning: ", Filename, LineNo); vfprintf (stderr, Msg, ap); fprintf (stderr, "\n"); if (Line) { Print (stderr, 1, "Input: %.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } ++WarningCount; } } void Warning (const char* Format, ...) /* Print warning message. */ { va_list ap; va_start (ap, Format); IntWarning (GetInputName (CurTok.LI), GetInputLine (CurTok.LI), Format, ap); va_end (ap); } void LIWarning (const LineInfo* LI, const char* Format, ...) /* Print a warning message with the line info given explicitly */ { va_list ap; va_start (ap, Format); IntWarning (GetInputName (LI), GetInputLine (LI), Format, ap); va_end (ap); } void PPWarning (const char* Format, ...) /* Print warning message. For use within the preprocessor. */ { va_list ap; va_start (ap, Format); IntWarning (GetCurrentFile(), GetCurrentLine(), Format, ap); va_end (ap); } IntStack* FindWarning (const char* Name) /* Search for a warning in the WarnMap table and return a pointer to the * intstack that holds its state. Return NULL if there is no such warning. */ { unsigned I; /* For now, do a linear search */ for (I = 0; I < sizeof(WarnMap) / sizeof (WarnMap[0]); ++I) { if (strcmp (WarnMap[I].Name, Name) == 0) { return WarnMap[I].Stack; } } return 0; } void ListWarnings (FILE* F) /* Print a list of warning types/names to the given file */ { unsigned I; for (I = 0; I < sizeof(WarnMap) / sizeof (WarnMap[0]); ++I) { fprintf (F, "%s\n", WarnMap[I].Name); } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void ErrorReport (void) /* Report errors (called at end of compile) */ { Print (stdout, 1, "%u errors, %u warnings\n", ErrorCount, WarningCount); }
824
./cc65/src/cc65/expr.c
/* expr.c * * Ullrich von Bassewitz, 21.06.1998 */ #include <stdio.h> #include <stdlib.h> /* common */ #include "check.h" #include "debugflag.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "asmstmt.h" #include "assignment.h" #include "codegen.h" #include "declare.h" #include "error.h" #include "funcdesc.h" #include "function.h" #include "global.h" #include "litpool.h" #include "loadexpr.h" #include "macrotab.h" #include "preproc.h" #include "scanner.h" #include "shiftexpr.h" #include "stackptr.h" #include "standard.h" #include "stdfunc.h" #include "symtab.h" #include "typecmp.h" #include "typeconv.h" #include "expr.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Generator attributes */ #define GEN_NOPUSH 0x01 /* Don't push lhs */ #define GEN_COMM 0x02 /* Operator is commutative */ /* Map a generator function and its attributes to a token */ typedef struct { token_t Tok; /* Token to map to */ unsigned Flags; /* Flags for generator function */ void (*Func) (unsigned, unsigned long); /* Generator func */ } GenDesc; /* Descriptors for the operations */ static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add }; static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub }; static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul }; static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div }; static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod }; static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl }; static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr }; static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and }; static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor }; static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or }; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static unsigned GlobalModeFlags (const ExprDesc* Expr) /* Return the addressing mode flags for the given expression */ { switch (ED_GetLoc (Expr)) { case E_LOC_ABS: return CF_ABSOLUTE; case E_LOC_GLOBAL: return CF_EXTERNAL; case E_LOC_STATIC: return CF_STATIC; case E_LOC_REGISTER: return CF_REGVAR; case E_LOC_STACK: return CF_NONE; case E_LOC_PRIMARY: return CF_NONE; case E_LOC_EXPR: return CF_NONE; case E_LOC_LITERAL: return CF_STATIC; /* Same as static */ default: Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags); /* NOTREACHED */ return 0; } } void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr) /* Call an expression function with checks. */ { /* Remember the stack pointer */ int OldSP = StackPtr; /* Call the expression function */ (*Func) (Expr); /* Do some checks if code generation is still constistent */ if (StackPtr != OldSP) { if (Debug) { Error ("Code generation messed up: " "StackPtr is %d, should be %d", StackPtr, OldSP); } else { Internal ("Code generation messed up: " "StackPtr is %d, should be %d", StackPtr, OldSP); } } } void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr) /* Call an expression function with checks and record start and end of the * generated code. */ { CodeMark Start, End; GetCodePos (&Start); ExprWithCheck (Func, Expr); GetCodePos (&End); ED_SetCodeRange (Expr, &Start, &End); } static Type* promoteint (Type* lhst, Type* rhst) /* In an expression with two ints, return the type of the result */ { /* Rules for integer types: * - If one of the values is a long, the result is long. * - If one of the values is unsigned, the result is also unsigned. * - Otherwise the result is an int. */ if (IsTypeLong (lhst) || IsTypeLong (rhst)) { if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) { return type_ulong; } else { return type_long; } } else { if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) { return type_uint; } else { return type_int; } } } static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush) /* Adjust the two values for a binary operation. lhs is expected on stack or * to be constant, rhs is expected to be in the primary register or constant. * The function will put the type of the result into lhs and return the * code generator flags for the operation. * If NoPush is given, it is assumed that the operation does not expect the lhs * to be on stack, and that lhs is in a register instead. * Beware: The function does only accept int types. */ { unsigned ltype, rtype; unsigned flags; /* Get the type strings */ Type* lhst = lhs->Type; Type* rhst = rhs->Type; /* Generate type adjustment code if needed */ ltype = TypeOf (lhst); if (ED_IsLocAbs (lhs)) { ltype |= CF_CONST; } if (NoPush) { /* Value is in primary register*/ ltype |= CF_REG; } rtype = TypeOf (rhst); if (ED_IsLocAbs (rhs)) { rtype |= CF_CONST; } flags = g_typeadjust (ltype, rtype); /* Set the type of the result */ lhs->Type = promoteint (lhst, rhst); /* Return the code generator flags */ return flags; } static const GenDesc* FindGen (token_t Tok, const GenDesc* Table) /* Find a token in a generator table */ { while (Table->Tok != TOK_INVALID) { if (Table->Tok == Tok) { return Table; } ++Table; } return 0; } static int TypeSpecAhead (void) /* Return true if some sort of type is waiting (helper for cast and sizeof() * in hie10). */ { SymEntry* Entry; /* There's a type waiting if: * * We have an opening paren, and * a. the next token is a type, or * b. the next token is a type qualifier, or * c. the next token is a typedef'd type */ return CurTok.Tok == TOK_LPAREN && ( TokIsType (&NextTok) || TokIsTypeQual (&NextTok) || (NextTok.Tok == TOK_IDENT && (Entry = FindSym (NextTok.Ident)) != 0 && SymIsTypeDef (Entry))); } void PushAddr (const ExprDesc* Expr) /* If the expression contains an address that was somehow evaluated, * push this address on the stack. This is a helper function for all * sorts of implicit or explicit assignment functions where the lvalue * must be saved if it's not constant, before evaluating the rhs. */ { /* Get the address on stack if needed */ if (ED_IsLocExpr (Expr)) { /* Push the address (always a pointer) */ g_push (CF_PTR, 0); } } static void WarnConstCompareResult (void) /* If the result of a comparison is constant, this is suspicious when not in * preprocessor mode. */ { if (!Preprocessing && IS_Get (&WarnConstComparison) != 0) { Warning ("Result of comparison is constant"); } } /*****************************************************************************/ /* code */ /*****************************************************************************/ static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall) /* Parse a function parameter list and pass the parameters to the called * function. Depending on several criteria this may be done by just pushing * each parameter separately, or creating the parameter frame once and then * storing into this frame. * The function returns the size of the parameters pushed. */ { ExprDesc Expr; /* Initialize variables */ SymEntry* Param = 0; /* Keep gcc silent */ unsigned ParamSize = 0; /* Size of parameters pushed */ unsigned ParamCount = 0; /* Number of parameters pushed */ unsigned FrameSize = 0; /* Size of parameter frame */ unsigned FrameParams = 0; /* Number of params in frame */ int FrameOffs = 0; /* Offset into parameter frame */ int Ellipsis = 0; /* Function is variadic */ /* As an optimization, we may allocate the complete parameter frame at * once instead of pushing each parameter as it comes. We may do that, * if... * * - optimizations that increase code size are enabled (allocating the * stack frame at once gives usually larger code). * - we have more than one parameter to push (don't count the last param * for __fastcall__ functions). * * The FrameSize variable will contain a value > 0 if storing into a frame * (instead of pushing) is enabled. * */ if (IS_Get (&CodeSizeFactor) >= 200) { /* Calculate the number and size of the parameters */ FrameParams = Func->ParamCount; FrameSize = Func->ParamSize; if (FrameParams > 0 && IsFastcall) { /* Last parameter is not pushed */ FrameSize -= CheckedSizeOf (Func->LastParam->Type); --FrameParams; } /* Do we have more than one parameter in the frame? */ if (FrameParams > 1) { /* Okeydokey, setup the frame */ FrameOffs = StackPtr; g_space (FrameSize); StackPtr -= FrameSize; } else { /* Don't use a preallocated frame */ FrameSize = 0; } } /* Parse the actual parameter list */ while (CurTok.Tok != TOK_RPAREN) { unsigned Flags; /* Count arguments */ ++ParamCount; /* Fetch the pointer to the next argument, check for too many args */ if (ParamCount <= Func->ParamCount) { /* Beware: If there are parameters with identical names, they * cannot go into the same symbol table, which means that in this * case of errorneous input, the number of nodes in the symbol * table and ParamCount are NOT equal. We have to handle this case * below to avoid segmentation violations. Since we know that this * problem can only occur if there is more than one parameter, * we will just use the last one. */ if (ParamCount == 1) { /* First argument */ Param = Func->SymTab->SymHead; } else if (Param->NextSym != 0) { /* Next argument */ Param = Param->NextSym; CHECK ((Param->Flags & SC_PARAM) != 0); } } else if (!Ellipsis) { /* Too many arguments. Do we have an open param list? */ if ((Func->Flags & FD_VARIADIC) == 0) { /* End of param list reached, no ellipsis */ Error ("Too many arguments in function call"); } /* Assume an ellipsis even in case of errors to avoid an error * message for each other argument. */ Ellipsis = 1; } /* Evaluate the parameter expression */ hie1 (&Expr); /* If we don't have an argument spec, accept anything, otherwise * convert the actual argument to the type needed. */ Flags = CF_NONE; if (!Ellipsis) { /* Convert the argument to the parameter type if needed */ TypeConversion (&Expr, Param->Type); /* If we have a prototype, chars may be pushed as chars */ Flags |= CF_FORCECHAR; } else { /* No prototype available. Convert array to "pointer to first * element", and function to "pointer to function". */ Expr.Type = PtrConversion (Expr.Type); } /* Load the value into the primary if it is not already there */ LoadExpr (Flags, &Expr); /* Use the type of the argument for the push */ Flags |= TypeOf (Expr.Type); /* If this is a fastcall function, don't push the last argument */ if (ParamCount != Func->ParamCount || !IsFastcall) { unsigned ArgSize = sizeofarg (Flags); if (FrameSize > 0) { /* We have the space already allocated, store in the frame. * Because of invalid type conversions (that have produced an * error before), we can end up here with a non aligned stack * frame. Since no output will be generated anyway, handle * these cases gracefully instead of doing a CHECK. */ if (FrameSize >= ArgSize) { FrameSize -= ArgSize; } else { FrameSize = 0; } FrameOffs -= ArgSize; /* Store */ g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal); } else { /* Push the argument */ g_push (Flags, Expr.IVal); } /* Calculate total parameter size */ ParamSize += ArgSize; } /* Check for end of argument list */ if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } /* Check if we had enough parameters */ if (ParamCount < Func->ParamCount) { Error ("Too few arguments in function call"); } /* The function returns the size of all parameters pushed onto the stack. * However, if there are parameters missing (which is an error and was * flagged by the compiler) AND a stack frame was preallocated above, * we would loose track of the stackpointer and generate an internal error * later. So we correct the value by the parameters that should have been * pushed to avoid an internal compiler error. Since an error was * generated before, no code will be output anyway. */ return ParamSize + FrameSize; } static void FunctionCall (ExprDesc* Expr) /* Perform a function call. */ { FuncDesc* Func; /* Function descriptor */ int IsFuncPtr; /* Flag */ unsigned ParamSize; /* Number of parameter bytes */ CodeMark Mark; int PtrOffs = 0; /* Offset of function pointer on stack */ int IsFastcall = 0; /* True if it's a fast call function */ int PtrOnStack = 0; /* True if a pointer copy is on stack */ /* Skip the left paren */ NextToken (); /* Get a pointer to the function descriptor from the type string */ Func = GetFuncDesc (Expr->Type); /* Handle function pointers transparently */ IsFuncPtr = IsTypeFuncPtr (Expr->Type); if (IsFuncPtr) { /* Check wether it's a fastcall function that has parameters */ IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0); /* Things may be difficult, depending on where the function pointer * resides. If the function pointer is an expression of some sort * (not a local or global variable), we have to evaluate this * expression now and save the result for later. Since calls to * function pointers may be nested, we must save it onto the stack. * For fastcall functions we do also need to place a copy of the * pointer on stack, since we cannot use a/x. */ PtrOnStack = IsFastcall || !ED_IsConst (Expr); if (PtrOnStack) { /* Not a global or local variable, or a fastcall function. Load * the pointer into the primary and mark it as an expression. */ LoadExpr (CF_NONE, Expr); ED_MakeRValExpr (Expr); /* Remember the code position */ GetCodePos (&Mark); /* Push the pointer onto the stack and remember the offset */ g_push (CF_PTR, 0); PtrOffs = StackPtr; } } else { /* Check function attributes */ if (Expr->Sym && SymHasAttr (Expr->Sym, atNoReturn)) { /* For now, handle as if a return statement was encountered */ F_ReturnFound (CurrentFunc); } /* Check for known standard functions and inline them */ if (Expr->Name != 0) { int StdFunc = FindStdFunc ((const char*) Expr->Name); if (StdFunc >= 0) { /* Inline this function */ HandleStdFunc (StdFunc, Func, Expr); return; } } /* If we didn't inline the function, get fastcall info */ IsFastcall = IsQualFastcall (Expr->Type); } /* Parse the parameter list */ ParamSize = FunctionParamList (Func, IsFastcall); /* We need the closing paren here */ ConsumeRParen (); /* Special handling for function pointers */ if (IsFuncPtr) { /* If the function is not a fastcall function, load the pointer to * the function into the primary. */ if (!IsFastcall) { /* Not a fastcall function - we may use the primary */ if (PtrOnStack) { /* If we have no parameters, the pointer is still in the * primary. Remove the code to push it and correct the * stack pointer. */ if (ParamSize == 0) { RemoveCode (&Mark); PtrOnStack = 0; } else { /* Load from the saved copy */ g_getlocal (CF_PTR, PtrOffs); } } else { /* Load from original location */ LoadExpr (CF_NONE, Expr); } /* Call the function */ g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs); } else { /* Fastcall function. We cannot use the primary for the function * pointer and must therefore use an offset to the stack location. * Since fastcall functions may never be variadic, we can use the * index register for this purpose. */ g_callind (CF_LOCAL, ParamSize, PtrOffs); } /* If we have a pointer on stack, remove it */ if (PtrOnStack) { g_drop (SIZEOF_PTR); pop (CF_PTR); } /* Skip T_PTR */ ++Expr->Type; } else { /* Normal function */ g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize); } /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } static void Primary (ExprDesc* E) /* This is the lowest level of the expression parser. */ { SymEntry* Sym; /* Initialize fields in the expression stucture */ ED_Init (E); /* Character and integer constants. */ if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) { E->IVal = CurTok.IVal; E->Flags = E_LOC_ABS | E_RTYPE_RVAL; E->Type = CurTok.Type; NextToken (); return; } /* Floating point constant */ if (CurTok.Tok == TOK_FCONST) { E->FVal = CurTok.FVal; E->Flags = E_LOC_ABS | E_RTYPE_RVAL; E->Type = CurTok.Type; NextToken (); return; } /* Process parenthesized subexpression by calling the whole parser * recursively. */ if (CurTok.Tok == TOK_LPAREN) { NextToken (); hie0 (E); ConsumeRParen (); return; } /* If we run into an identifier in preprocessing mode, we assume that this * is an undefined macro and replace it by a constant value of zero. */ if (Preprocessing && CurTok.Tok == TOK_IDENT) { NextToken (); ED_MakeConstAbsInt (E, 0); return; } /* All others may only be used if the expression evaluation is not called * recursively by the preprocessor. */ if (Preprocessing) { /* Illegal expression in PP mode */ Error ("Preprocessor expression expected"); ED_MakeConstAbsInt (E, 1); return; } switch (CurTok.Tok) { case TOK_IDENT: /* Identifier. Get a pointer to the symbol table entry */ Sym = E->Sym = FindSym (CurTok.Ident); /* Is the symbol known? */ if (Sym) { /* We found the symbol - skip the name token */ NextToken (); /* Check for illegal symbol types */ CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL); if (Sym->Flags & SC_TYPE) { /* Cannot use type symbols */ Error ("Variable identifier expected"); /* Assume an int type to make E valid */ E->Flags = E_LOC_STACK | E_RTYPE_LVAL; E->Type = type_int; return; } /* Mark the symbol as referenced */ Sym->Flags |= SC_REF; /* The expression type is the symbol type */ E->Type = Sym->Type; /* Check for legal symbol types */ if ((Sym->Flags & SC_CONST) == SC_CONST) { /* Enum or some other numeric constant */ E->Flags = E_LOC_ABS | E_RTYPE_RVAL; E->IVal = Sym->V.ConstVal; } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) { /* Function */ E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL; E->Name = (unsigned long) Sym->Name; } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) { /* Local variable. If this is a parameter for a variadic * function, we have to add some address calculations, and the * address is not const. */ if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) { /* Variadic parameter */ g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc)); E->Flags = E_LOC_EXPR | E_RTYPE_LVAL; } else { /* Normal parameter */ E->Flags = E_LOC_STACK | E_RTYPE_LVAL; E->IVal = Sym->V.Offs; } } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) { /* Register variable, zero page based */ E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL; E->Name = Sym->V.R.RegOffs; } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) { /* Static variable */ if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) { E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL; E->Name = (unsigned long) Sym->Name; } else { E->Flags = E_LOC_STATIC | E_RTYPE_LVAL; E->Name = Sym->V.Label; } } else { /* Local static variable */ E->Flags = E_LOC_STATIC | E_RTYPE_LVAL; E->Name = Sym->V.Offs; } /* We've made all variables lvalues above. However, this is * not always correct: An array is actually the address of its * first element, which is a rvalue, and a function is a * rvalue, too, because we cannot store anything in a function. * So fix the flags depending on the type. */ if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) { ED_MakeRVal (E); } } else { /* We did not find the symbol. Remember the name, then skip it */ ident Ident; strcpy (Ident, CurTok.Ident); NextToken (); /* IDENT is either an auto-declared function or an undefined variable. */ if (CurTok.Tok == TOK_LPAREN) { /* C99 doesn't allow calls to undefined functions, so * generate an error and otherwise a warning. Declare a * function returning int. For that purpose, prepare a * function signature for a function having an empty param * list and returning int. */ if (IS_Get (&Standard) >= STD_C99) { Error ("Call to undefined function `%s'", Ident); } else { Warning ("Call to undefined function `%s'", Ident); } Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC); E->Type = Sym->Type; E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL; E->Name = (unsigned long) Sym->Name; } else { /* Undeclared Variable */ Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0); E->Flags = E_LOC_STACK | E_RTYPE_LVAL; E->Type = type_int; Error ("Undefined symbol: `%s'", Ident); } } break; case TOK_SCONST: case TOK_WCSCONST: /* String literal */ E->LVal = UseLiteral (CurTok.SVal); E->Type = GetCharArrayType (GetLiteralSize (CurTok.SVal)); E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL; E->IVal = 0; E->Name = GetLiteralLabel (CurTok.SVal); NextToken (); break; case TOK_ASM: /* ASM statement */ AsmStatement (); E->Flags = E_LOC_EXPR | E_RTYPE_RVAL; E->Type = type_void; break; case TOK_A: /* Register pseudo variable */ E->Type = type_uchar; E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL; NextToken (); break; case TOK_AX: /* Register pseudo variable */ E->Type = type_uint; E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL; NextToken (); break; case TOK_EAX: /* Register pseudo variable */ E->Type = type_ulong; E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL; NextToken (); break; default: /* Illegal primary. Be sure to skip the token to avoid endless * error loops. */ Error ("Expression expected"); NextToken (); ED_MakeConstAbsInt (E, 1); break; } } static void ArrayRef (ExprDesc* Expr) /* Handle an array reference. This function needs a rewrite. */ { int ConstBaseAddr; ExprDesc Subscript; CodeMark Mark1; CodeMark Mark2; TypeCode Qualifiers; Type* ElementType; Type* tptr1; /* Skip the bracket */ NextToken (); /* Get the type of left side */ tptr1 = Expr->Type; /* We can apply a special treatment for arrays that have a const base * address. This is true for most arrays and will produce a lot better * code. Check if this is a const base address. */ ConstBaseAddr = ED_IsRVal (Expr) && (ED_IsLocConst (Expr) || ED_IsLocStack (Expr)); /* If we have a constant base, we delay the address fetch */ GetCodePos (&Mark1); if (!ConstBaseAddr) { /* Get a pointer to the array into the primary */ LoadExpr (CF_NONE, Expr); /* Get the array pointer on stack. Do not push more than 16 * bit, even if this value is greater, since we cannot handle * other than 16bit stuff when doing indexing. */ GetCodePos (&Mark2); g_push (CF_PTR, 0); } /* TOS now contains ptr to array elements. Get the subscript. */ MarkedExprWithCheck (hie0, &Subscript); /* Check the types of array and subscript. We can either have a * pointer/array to the left, in which case the subscript must be of an * integer type, or we have an integer to the left, in which case the * subscript must be a pointer/array. * Since we do the necessary checking here, we can rely later on the * correct types. */ Qualifiers = T_QUAL_NONE; if (IsClassPtr (Expr->Type)) { if (!IsClassInt (Subscript.Type)) { Error ("Array subscript is not an integer"); /* To avoid any compiler errors, make the expression a valid int */ ED_MakeConstAbsInt (&Subscript, 0); } if (IsTypeArray (Expr->Type)) { Qualifiers = GetQualifier (Expr->Type); } ElementType = Indirect (Expr->Type); } else if (IsClassInt (Expr->Type)) { if (!IsClassPtr (Subscript.Type)) { Error ("Subscripted value is neither array nor pointer"); /* To avoid compiler errors, make the subscript a char[] at * address 0. */ ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1)); } else if (IsTypeArray (Subscript.Type)) { Qualifiers = GetQualifier (Subscript.Type); } ElementType = Indirect (Subscript.Type); } else { Error ("Cannot subscript"); /* To avoid compiler errors, fake both the array and the subscript, so * we can just proceed. */ ED_MakeConstAbs (Expr, 0, GetCharArrayType (1)); ED_MakeConstAbsInt (&Subscript, 0); ElementType = Indirect (Expr->Type); } /* The element type has the combined qualifiers from itself and the array, * it is a member of (if any). */ if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) { ElementType = TypeDup (ElementType); ElementType->C |= Qualifiers; } /* If the subscript is a bit-field, load it and make it an rvalue */ if (ED_IsBitField (&Subscript)) { LoadExpr (CF_NONE, &Subscript); ED_MakeRValExpr (&Subscript); } /* Check if the subscript is constant absolute value */ if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) { /* The array subscript is a numeric constant. If we had pushed the * array base address onto the stack before, we can remove this value, * since we can generate expression+offset. */ if (!ConstBaseAddr) { RemoveCode (&Mark2); } else { /* Get an array pointer into the primary */ LoadExpr (CF_NONE, Expr); } if (IsClassPtr (Expr->Type)) { /* Lhs is pointer/array. Scale the subscript value according to * the element size. */ Subscript.IVal *= CheckedSizeOf (ElementType); /* Remove the address load code */ RemoveCode (&Mark1); /* In case of an array, we can adjust the offset of the expression * already in Expr. If the base address was a constant, we can even * remove the code that loaded the address into the primary. */ if (IsTypeArray (Expr->Type)) { /* Adjust the offset */ Expr->IVal += Subscript.IVal; } else { /* It's a pointer, so we do have to load it into the primary * first (if it's not already there). */ if (ConstBaseAddr || ED_IsLVal (Expr)) { LoadExpr (CF_NONE, Expr); ED_MakeRValExpr (Expr); } /* Use the offset */ Expr->IVal = Subscript.IVal; } } else { /* Scale the rhs value according to the element type */ g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType)); /* Add the subscript. Since arrays are indexed by integers, * we will ignore the true type of the subscript here and * use always an int. #### Use offset but beware of LoadExpr! */ g_inc (CF_INT | CF_CONST, Subscript.IVal); } } else { /* Array subscript is not constant. Load it into the primary */ GetCodePos (&Mark2); LoadExpr (CF_NONE, &Subscript); /* Do scaling */ if (IsClassPtr (Expr->Type)) { /* Indexing is based on unsigneds, so we will just use the integer * portion of the index (which is in (e)ax, so there's no further * action required). */ g_scale (CF_INT, CheckedSizeOf (ElementType)); } else { /* Get the int value on top. If we come here, we're sure, both * values are 16 bit (the first one was truncated if necessary * and the second one is a pointer). Note: If ConstBaseAddr is * true, we don't have a value on stack, so to "swap" both, just * push the subscript. */ if (ConstBaseAddr) { g_push (CF_INT, 0); LoadExpr (CF_NONE, Expr); ConstBaseAddr = 0; } else { g_swap (CF_INT); } /* Scale it */ g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType)); } /* The offset is now in the primary register. It we didn't have a * constant base address for the lhs, the lhs address is already * on stack, and we must add the offset. If the base address was * constant, we call special functions to add the address to the * offset value. */ if (!ConstBaseAddr) { /* The array base address is on stack and the subscript is in the * primary. Add both. */ g_add (CF_INT, 0); } else { /* The subscript is in the primary, and the array base address is * in Expr. If the subscript has itself a constant address, it is * often a better idea to reverse again the order of the * evaluation. This will generate better code if the subscript is * a byte sized variable. But beware: This is only possible if the * subscript was not scaled, that is, if this was a byte array * or pointer. */ if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) && CheckedSizeOf (ElementType) == SIZEOF_CHAR) { unsigned Flags; /* Reverse the order of evaluation */ if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) { Flags = CF_CHAR; } else { Flags = CF_INT; } RemoveCode (&Mark2); /* Get a pointer to the array into the primary. */ LoadExpr (CF_NONE, Expr); /* Add the variable */ if (ED_IsLocStack (&Subscript)) { g_addlocal (Flags, Subscript.IVal); } else { Flags |= GlobalModeFlags (&Subscript); g_addstatic (Flags, Subscript.Name, Subscript.IVal); } } else { if (ED_IsLocAbs (Expr)) { /* Constant numeric address. Just add it */ g_inc (CF_INT, Expr->IVal); } else if (ED_IsLocStack (Expr)) { /* Base address is a local variable address */ if (IsTypeArray (Expr->Type)) { g_addaddr_local (CF_INT, Expr->IVal); } else { g_addlocal (CF_PTR, Expr->IVal); } } else { /* Base address is a static variable address */ unsigned Flags = CF_INT | GlobalModeFlags (Expr); if (ED_IsRVal (Expr)) { /* Add the address of the location */ g_addaddr_static (Flags, Expr->Name, Expr->IVal); } else { /* Add the contents of the location */ g_addstatic (Flags, Expr->Name, Expr->IVal); } } } } /* The result is an expression in the primary */ ED_MakeRValExpr (Expr); } /* Result is of element type */ Expr->Type = ElementType; /* An array element is actually a variable. So the rules for variables * with respect to the reference type apply: If it's an array, it is * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue, * but an array cannot contain functions). */ if (IsTypeArray (Expr->Type)) { ED_MakeRVal (Expr); } else { ED_MakeLVal (Expr); } /* Consume the closing bracket */ ConsumeRBrack (); } static void StructRef (ExprDesc* Expr) /* Process struct field after . or ->. */ { ident Ident; SymEntry* Field; Type* FinalType; TypeCode Q; /* Skip the token and check for an identifier */ NextToken (); if (CurTok.Tok != TOK_IDENT) { Error ("Identifier expected"); /* Make the expression an integer at address zero */ ED_MakeConstAbs (Expr, 0, type_int); return; } /* Get the symbol table entry and check for a struct field */ strcpy (Ident, CurTok.Ident); NextToken (); Field = FindStructField (Expr->Type, Ident); if (Field == 0) { Error ("Struct/union has no field named `%s'", Ident); /* Make the expression an integer at address zero */ ED_MakeConstAbs (Expr, 0, type_int); return; } /* If we have a struct pointer that is an lvalue and not already in the * primary, load it now. */ if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) { /* Load into the primary */ LoadExpr (CF_NONE, Expr); /* Make it an lvalue expression */ ED_MakeLValExpr (Expr); } /* The type is the type of the field plus any qualifiers from the struct */ if (IsClassStruct (Expr->Type)) { Q = GetQualifier (Expr->Type); } else { Q = GetQualifier (Indirect (Expr->Type)); } if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) { FinalType = Field->Type; } else { FinalType = TypeDup (Field->Type); FinalType->C |= Q; } /* A struct is usually an lvalue. If not, it is a struct in the primary * register. */ if (ED_IsRVal (Expr) && ED_IsLocExpr (Expr) && !IsTypePtr (Expr->Type)) { unsigned Flags = 0; unsigned BitOffs; /* Get the size of the type */ unsigned Size = SizeOf (Expr->Type); /* Safety check */ CHECK (Field->V.Offs + Size <= SIZEOF_LONG); /* The type of the operation depends on the type of the struct */ switch (Size) { case 1: Flags = CF_CHAR | CF_UNSIGNED | CF_CONST; break; case 2: Flags = CF_INT | CF_UNSIGNED | CF_CONST; break; case 3: /* FALLTHROUGH */ case 4: Flags = CF_LONG | CF_UNSIGNED | CF_CONST; break; default: Internal ("Invalid struct size: %u", Size); break; } /* Generate a shift to get the field in the proper position in the * primary. For bit fields, mask the value. */ BitOffs = Field->V.Offs * CHAR_BITS; if (SymIsBitField (Field)) { BitOffs += Field->V.B.BitOffs; g_asr (Flags, BitOffs); /* Mask the value. This is unnecessary if the shift executed above * moved only zeroes into the value. */ if (BitOffs + Field->V.B.BitWidth != Size * CHAR_BITS) { g_and (CF_INT | CF_UNSIGNED | CF_CONST, (0x0001U << Field->V.B.BitWidth) - 1U); } } else { g_asr (Flags, BitOffs); } /* Use the new type */ Expr->Type = FinalType; } else { /* Set the struct field offset */ Expr->IVal += Field->V.Offs; /* Use the new type */ Expr->Type = FinalType; /* An struct member is actually a variable. So the rules for variables * with respect to the reference type apply: If it's an array, it is * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue, * but a struct field cannot be a function). */ if (IsTypeArray (Expr->Type)) { ED_MakeRVal (Expr); } else { ED_MakeLVal (Expr); } /* Make the expression a bit field if necessary */ if (SymIsBitField (Field)) { ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth); } } } static void hie11 (ExprDesc *Expr) /* Handle compound types (structs and arrays) */ { /* Name value used in invalid function calls */ static const char IllegalFunc[] = "illegal_function_call"; /* Evaluate the lhs */ Primary (Expr); /* Check for a rhs */ while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN || CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) { switch (CurTok.Tok) { case TOK_LBRACK: /* Array reference */ ArrayRef (Expr); break; case TOK_LPAREN: /* Function call. */ if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) { /* Not a function */ Error ("Illegal function call"); /* Force the type to be a implicitly defined function, one * returning an int and taking any number of arguments. * Since we don't have a name, invent one. */ ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ()); Expr->Name = (long) IllegalFunc; } /* Call the function */ FunctionCall (Expr); break; case TOK_DOT: if (!IsClassStruct (Expr->Type)) { Error ("Struct expected"); } StructRef (Expr); break; case TOK_PTR_REF: /* If we have an array, convert it to pointer to first element */ if (IsTypeArray (Expr->Type)) { Expr->Type = ArrayToPtr (Expr->Type); } if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) { Error ("Struct pointer expected"); } StructRef (Expr); break; default: Internal ("Invalid token in hie11: %d", CurTok.Tok); } } } void Store (ExprDesc* Expr, const Type* StoreType) /* Store the primary register into the location denoted by Expr. If StoreType * is given, use this type when storing instead of Expr->Type. If StoreType * is NULL, use Expr->Type instead. */ { unsigned Flags; /* If StoreType was not given, use Expr->Type instead */ if (StoreType == 0) { StoreType = Expr->Type; } /* Prepare the code generator flags */ Flags = TypeOf (StoreType) | GlobalModeFlags (Expr); /* Do the store depending on the location */ switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_putstatic (Flags, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global variable */ g_putstatic (Flags, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_putstatic (Flags, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable */ g_putstatic (Flags, Expr->Name, Expr->IVal); break; case E_LOC_STACK: /* Value on the stack */ g_putlocal (Flags, Expr->IVal, 0); break; case E_LOC_PRIMARY: /* The primary register (value is already there) */ break; case E_LOC_EXPR: /* An expression in the primary register */ g_putind (Flags, Expr->IVal); break; default: Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr)); } /* Assume that each one of the stores will invalidate CC */ ED_MarkAsUntested (Expr); } static void PreInc (ExprDesc* Expr) /* Handle the preincrement operators */ { unsigned Flags; unsigned long Val; /* Skip the operator token */ NextToken (); /* Evaluate the expression and check that it is an lvalue */ hie10 (Expr); if (!ED_IsLVal (Expr)) { Error ("Invalid lvalue"); return; } /* We cannot modify const values */ if (IsQualConst (Expr->Type)) { Error ("Increment of read-only variable"); } /* Get the data type */ Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST; /* Get the increment value in bytes */ Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1; /* Check the location of the data */ switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_addeqstatic (Flags, Expr->IVal, 0, Val); break; case E_LOC_GLOBAL: /* Global variable */ g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_REGISTER: /* Register variable */ g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_STACK: /* Value on the stack */ g_addeqlocal (Flags, Expr->IVal, Val); break; case E_LOC_PRIMARY: /* The primary register */ g_inc (Flags, Val); break; case E_LOC_EXPR: /* An expression in the primary register */ g_addeqind (Flags, Expr->IVal, Val); break; default: Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr)); } /* Result is an expression, no reference */ ED_MakeRValExpr (Expr); } static void PreDec (ExprDesc* Expr) /* Handle the predecrement operators */ { unsigned Flags; unsigned long Val; /* Skip the operator token */ NextToken (); /* Evaluate the expression and check that it is an lvalue */ hie10 (Expr); if (!ED_IsLVal (Expr)) { Error ("Invalid lvalue"); return; } /* We cannot modify const values */ if (IsQualConst (Expr->Type)) { Error ("Decrement of read-only variable"); } /* Get the data type */ Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST; /* Get the increment value in bytes */ Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1; /* Check the location of the data */ switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_subeqstatic (Flags, Expr->IVal, 0, Val); break; case E_LOC_GLOBAL: /* Global variable */ g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_REGISTER: /* Register variable */ g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val); break; case E_LOC_STACK: /* Value on the stack */ g_subeqlocal (Flags, Expr->IVal, Val); break; case E_LOC_PRIMARY: /* The primary register */ g_inc (Flags, Val); break; case E_LOC_EXPR: /* An expression in the primary register */ g_subeqind (Flags, Expr->IVal, Val); break; default: Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr)); } /* Result is an expression, no reference */ ED_MakeRValExpr (Expr); } static void PostInc (ExprDesc* Expr) /* Handle the postincrement operator */ { unsigned Flags; NextToken (); /* The expression to increment must be an lvalue */ if (!ED_IsLVal (Expr)) { Error ("Invalid lvalue"); return; } /* We cannot modify const values */ if (IsQualConst (Expr->Type)) { Error ("Increment of read-only variable"); } /* Get the data type */ Flags = TypeOf (Expr->Type); /* Push the address if needed */ PushAddr (Expr); /* Fetch the value and save it (since it's the result of the expression) */ LoadExpr (CF_NONE, Expr); g_save (Flags | CF_FORCECHAR); /* If we have a pointer expression, increment by the size of the type */ if (IsTypePtr (Expr->Type)) { g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1)); } else { g_inc (Flags | CF_CONST | CF_FORCECHAR, 1); } /* Store the result back */ Store (Expr, 0); /* Restore the original value in the primary register */ g_restore (Flags | CF_FORCECHAR); /* The result is always an expression, no reference */ ED_MakeRValExpr (Expr); } static void PostDec (ExprDesc* Expr) /* Handle the postdecrement operator */ { unsigned Flags; NextToken (); /* The expression to increment must be an lvalue */ if (!ED_IsLVal (Expr)) { Error ("Invalid lvalue"); return; } /* We cannot modify const values */ if (IsQualConst (Expr->Type)) { Error ("Decrement of read-only variable"); } /* Get the data type */ Flags = TypeOf (Expr->Type); /* Push the address if needed */ PushAddr (Expr); /* Fetch the value and save it (since it's the result of the expression) */ LoadExpr (CF_NONE, Expr); g_save (Flags | CF_FORCECHAR); /* If we have a pointer expression, increment by the size of the type */ if (IsTypePtr (Expr->Type)) { g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1)); } else { g_dec (Flags | CF_CONST | CF_FORCECHAR, 1); } /* Store the result back */ Store (Expr, 0); /* Restore the original value in the primary register */ g_restore (Flags | CF_FORCECHAR); /* The result is always an expression, no reference */ ED_MakeRValExpr (Expr); } static void UnaryOp (ExprDesc* Expr) /* Handle unary -/+ and ~ */ { unsigned Flags; /* Remember the operator token and skip it */ token_t Tok = CurTok.Tok; NextToken (); /* Get the expression */ hie10 (Expr); /* We can only handle integer types */ if (!IsClassInt (Expr->Type)) { Error ("Argument must have integer type"); ED_MakeConstAbsInt (Expr, 1); } /* Check for a constant expression */ if (ED_IsConstAbs (Expr)) { /* Value is constant */ switch (Tok) { case TOK_MINUS: Expr->IVal = -Expr->IVal; break; case TOK_PLUS: break; case TOK_COMP: Expr->IVal = ~Expr->IVal; break; default: Internal ("Unexpected token: %d", Tok); } } else { /* Value is not constant */ LoadExpr (CF_NONE, Expr); /* Get the type of the expression */ Flags = TypeOf (Expr->Type); /* Handle the operation */ switch (Tok) { case TOK_MINUS: g_neg (Flags); break; case TOK_PLUS: break; case TOK_COMP: g_com (Flags); break; default: Internal ("Unexpected token: %d", Tok); } /* The result is a rvalue in the primary */ ED_MakeRValExpr (Expr); } } void hie10 (ExprDesc* Expr) /* Handle ++, --, !, unary - etc. */ { unsigned long Size; switch (CurTok.Tok) { case TOK_INC: PreInc (Expr); break; case TOK_DEC: PreDec (Expr); break; case TOK_PLUS: case TOK_MINUS: case TOK_COMP: UnaryOp (Expr); break; case TOK_BOOL_NOT: NextToken (); if (evalexpr (CF_NONE, hie10, Expr) == 0) { /* Constant expression */ Expr->IVal = !Expr->IVal; } else { g_bneg (TypeOf (Expr->Type)); ED_MakeRValExpr (Expr); ED_TestDone (Expr); /* bneg will set cc */ } break; case TOK_STAR: NextToken (); ExprWithCheck (hie10, Expr); if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) { /* Not a const, load it into the primary and make it a * calculated value. */ LoadExpr (CF_NONE, Expr); ED_MakeRValExpr (Expr); } /* If the expression is already a pointer to function, the * additional dereferencing operator must be ignored. A function * itself is represented as "pointer to function", so any number * of dereference operators is legal, since the result will * always be converted to "pointer to function". */ if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) { /* Expression not storable */ ED_MakeRVal (Expr); } else { if (IsClassPtr (Expr->Type)) { Expr->Type = Indirect (Expr->Type); } else { Error ("Illegal indirection"); } /* The * operator yields an lvalue */ ED_MakeLVal (Expr); } break; case TOK_AND: NextToken (); ExprWithCheck (hie10, Expr); /* The & operator may be applied to any lvalue, and it may be * applied to functions, even if they're no lvalues. */ if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) { Error ("Illegal address"); } else { if (ED_IsBitField (Expr)) { Error ("Cannot take address of bit-field"); /* Do it anyway, just to avoid further warnings */ Expr->Flags &= ~E_BITFIELD; } Expr->Type = PointerTo (Expr->Type); /* The & operator yields an rvalue */ ED_MakeRVal (Expr); } break; case TOK_SIZEOF: NextToken (); if (TypeSpecAhead ()) { Type T[MAXTYPELEN]; NextToken (); Size = CheckedSizeOf (ParseType (T)); ConsumeRParen (); } else { /* Remember the output queue pointer */ CodeMark Mark; GetCodePos (&Mark); hie10 (Expr); /* If the expression is a literal string, release it, so it * won't be output as data if not used elsewhere. */ if (ED_IsLocLiteral (Expr)) { ReleaseLiteral (Expr->LVal); } /* Calculate the size */ Size = CheckedSizeOf (Expr->Type); /* Remove any generated code */ RemoveCode (&Mark); } ED_MakeConstAbs (Expr, Size, type_size_t); ED_MarkAsUntested (Expr); break; default: if (TypeSpecAhead ()) { /* A typecast */ TypeCast (Expr); } else { /* An expression */ hie11 (Expr); /* Handle post increment */ switch (CurTok.Tok) { case TOK_INC: PostInc (Expr); break; case TOK_DEC: PostDec (Expr); break; default: break; } } break; } } static void hie_internal (const GenDesc* Ops, /* List of generators */ ExprDesc* Expr, void (*hienext) (ExprDesc*), int* UsedGen) /* Helper function */ { ExprDesc Expr2; CodeMark Mark1; CodeMark Mark2; const GenDesc* Gen; token_t Tok; /* The operator token */ unsigned ltype, type; int lconst; /* Left operand is a constant */ int rconst; /* Right operand is a constant */ ExprWithCheck (hienext, Expr); *UsedGen = 0; while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) { /* Tell the caller that we handled it's ops */ *UsedGen = 1; /* All operators that call this function expect an int on the lhs */ if (!IsClassInt (Expr->Type)) { Error ("Integer expression expected"); /* To avoid further errors, make Expr a valid int expression */ ED_MakeConstAbsInt (Expr, 1); } /* Remember the operator token, then skip it */ Tok = CurTok.Tok; NextToken (); /* Get the lhs on stack */ GetCodePos (&Mark1); ltype = TypeOf (Expr->Type); lconst = ED_IsConstAbs (Expr); if (lconst) { /* Constant value */ GetCodePos (&Mark2); /* If the operator is commutative, don't push the left side, if * it's a constant, since we will exchange both operands. */ if ((Gen->Flags & GEN_COMM) == 0) { g_push (ltype | CF_CONST, Expr->IVal); } } else { /* Value not constant */ LoadExpr (CF_NONE, Expr); GetCodePos (&Mark2); g_push (ltype, 0); } /* Get the right hand side */ MarkedExprWithCheck (hienext, &Expr2); /* Check for a constant expression */ rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)); if (!rconst) { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); } /* Check the type of the rhs */ if (!IsClassInt (Expr2.Type)) { Error ("Integer expression expected"); } /* Check for const operands */ if (lconst && rconst) { /* Both operands are constant, remove the generated code */ RemoveCode (&Mark1); /* Get the type of the result */ Expr->Type = promoteint (Expr->Type, Expr2.Type); /* Handle the op differently for signed and unsigned types */ if (IsSignSigned (Expr->Type)) { /* Evaluate the result for signed operands */ signed long Val1 = Expr->IVal; signed long Val2 = Expr2.IVal; switch (Tok) { case TOK_OR: Expr->IVal = (Val1 | Val2); break; case TOK_XOR: Expr->IVal = (Val1 ^ Val2); break; case TOK_AND: Expr->IVal = (Val1 & Val2); break; case TOK_STAR: Expr->IVal = (Val1 * Val2); break; case TOK_DIV: if (Val2 == 0) { Error ("Division by zero"); Expr->IVal = 0x7FFFFFFF; } else { Expr->IVal = (Val1 / Val2); } break; case TOK_MOD: if (Val2 == 0) { Error ("Modulo operation with zero"); Expr->IVal = 0; } else { Expr->IVal = (Val1 % Val2); } break; default: Internal ("hie_internal: got token 0x%X\n", Tok); } } else { /* Evaluate the result for unsigned operands */ unsigned long Val1 = Expr->IVal; unsigned long Val2 = Expr2.IVal; switch (Tok) { case TOK_OR: Expr->IVal = (Val1 | Val2); break; case TOK_XOR: Expr->IVal = (Val1 ^ Val2); break; case TOK_AND: Expr->IVal = (Val1 & Val2); break; case TOK_STAR: Expr->IVal = (Val1 * Val2); break; case TOK_DIV: if (Val2 == 0) { Error ("Division by zero"); Expr->IVal = 0xFFFFFFFF; } else { Expr->IVal = (Val1 / Val2); } break; case TOK_MOD: if (Val2 == 0) { Error ("Modulo operation with zero"); Expr->IVal = 0; } else { Expr->IVal = (Val1 % Val2); } break; default: Internal ("hie_internal: got token 0x%X\n", Tok); } } } else if (lconst && (Gen->Flags & GEN_COMM) && !rconst) { /* The left side is constant, the right side is not, and the * operator allows swapping the operands. We haven't pushed the * left side onto the stack in this case, and will reverse the * operation because this allows for better code. */ unsigned rtype = ltype | CF_CONST; ltype = TypeOf (Expr2.Type); /* Expr2 is now left */ type = CF_CONST; if ((Gen->Flags & GEN_NOPUSH) == 0) { g_push (ltype, 0); ltype |= CF_REG; /* Value is in register */ } /* Determine the type of the operation result. */ type |= g_typeadjust (ltype, rtype); Expr->Type = promoteint (Expr->Type, Expr2.Type); /* Generate code */ Gen->Func (type, Expr->IVal); /* We have a rvalue in the primary now */ ED_MakeRValExpr (Expr); } else { /* If the right hand side is constant, and the generator function * expects the lhs in the primary, remove the push of the primary * now. */ unsigned rtype = TypeOf (Expr2.Type); type = 0; if (rconst) { /* Second value is constant - check for div */ type |= CF_CONST; rtype |= CF_CONST; if (Tok == TOK_DIV && Expr2.IVal == 0) { Error ("Division by zero"); } else if (Tok == TOK_MOD && Expr2.IVal == 0) { Error ("Modulo operation with zero"); } if ((Gen->Flags & GEN_NOPUSH) != 0) { RemoveCode (&Mark2); ltype |= CF_REG; /* Value is in register */ } } /* Determine the type of the operation result. */ type |= g_typeadjust (ltype, rtype); Expr->Type = promoteint (Expr->Type, Expr2.Type); /* Generate code */ Gen->Func (type, Expr2.IVal); /* We have a rvalue in the primary now */ ED_MakeRValExpr (Expr); } } } static void hie_compare (const GenDesc* Ops, /* List of generators */ ExprDesc* Expr, void (*hienext) (ExprDesc*)) /* Helper function for the compare operators */ { ExprDesc Expr2; CodeMark Mark0; CodeMark Mark1; CodeMark Mark2; const GenDesc* Gen; token_t Tok; /* The operator token */ unsigned ltype; int rconst; /* Operand is a constant */ GetCodePos (&Mark0); ExprWithCheck (hienext, Expr); while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) { /* Remember the generator function */ void (*GenFunc) (unsigned, unsigned long) = Gen->Func; /* Remember the operator token, then skip it */ Tok = CurTok.Tok; NextToken (); /* Get the lhs on stack */ GetCodePos (&Mark1); ltype = TypeOf (Expr->Type); if (ED_IsConstAbs (Expr)) { /* Constant value */ GetCodePos (&Mark2); g_push (ltype | CF_CONST, Expr->IVal); } else { /* Value not constant */ LoadExpr (CF_NONE, Expr); GetCodePos (&Mark2); g_push (ltype, 0); } /* Get the right hand side */ MarkedExprWithCheck (hienext, &Expr2); /* Check for a constant expression */ rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)); if (!rconst) { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); } /* Make sure, the types are compatible */ if (IsClassInt (Expr->Type)) { if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) { Error ("Incompatible types"); } } else if (IsClassPtr (Expr->Type)) { if (IsClassPtr (Expr2.Type)) { /* Both pointers are allowed in comparison if they point to * the same type, or if one of them is a void pointer. */ Type* left = Indirect (Expr->Type); Type* right = Indirect (Expr2.Type); if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) { /* Incomatible pointers */ Error ("Incompatible types"); } } else if (!ED_IsNullPtr (&Expr2)) { Error ("Incompatible types"); } } /* Check for const operands */ if (ED_IsConstAbs (Expr) && rconst) { /* If the result is constant, this is suspicious when not in * preprocessor mode. */ WarnConstCompareResult (); /* Both operands are constant, remove the generated code */ RemoveCode (&Mark1); /* Determine if this is a signed or unsigned compare */ if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) && IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) { /* Evaluate the result for signed operands */ signed long Val1 = Expr->IVal; signed long Val2 = Expr2.IVal; switch (Tok) { case TOK_EQ: Expr->IVal = (Val1 == Val2); break; case TOK_NE: Expr->IVal = (Val1 != Val2); break; case TOK_LT: Expr->IVal = (Val1 < Val2); break; case TOK_LE: Expr->IVal = (Val1 <= Val2); break; case TOK_GE: Expr->IVal = (Val1 >= Val2); break; case TOK_GT: Expr->IVal = (Val1 > Val2); break; default: Internal ("hie_compare: got token 0x%X\n", Tok); } } else { /* Evaluate the result for unsigned operands */ unsigned long Val1 = Expr->IVal; unsigned long Val2 = Expr2.IVal; switch (Tok) { case TOK_EQ: Expr->IVal = (Val1 == Val2); break; case TOK_NE: Expr->IVal = (Val1 != Val2); break; case TOK_LT: Expr->IVal = (Val1 < Val2); break; case TOK_LE: Expr->IVal = (Val1 <= Val2); break; case TOK_GE: Expr->IVal = (Val1 >= Val2); break; case TOK_GT: Expr->IVal = (Val1 > Val2); break; default: Internal ("hie_compare: got token 0x%X\n", Tok); } } } else { /* Determine the signedness of the operands */ int LeftSigned = IsSignSigned (Expr->Type); int RightSigned = IsSignSigned (Expr2.Type); /* If the right hand side is constant, and the generator function * expects the lhs in the primary, remove the push of the primary * now. */ unsigned flags = 0; if (rconst) { flags |= CF_CONST; if ((Gen->Flags & GEN_NOPUSH) != 0) { RemoveCode (&Mark2); ltype |= CF_REG; /* Value is in register */ } } /* Determine the type of the operation. */ if (IsTypeChar (Expr->Type) && rconst) { /* Left side is unsigned char, right side is constant. * Determine the minimum and maximum values */ int LeftMin, LeftMax; if (LeftSigned) { LeftMin = -128; LeftMax = 127; } else { LeftMin = 0; LeftMax = 255; } /* An integer value is always represented as a signed in the * ExprDesc structure. This may lead to false results below, * if it is actually unsigned, but interpreted as signed * because of the representation. Fortunately, in this case, * the actual value doesn't matter, since it's always greater * than what can be represented in a char. So correct the * value accordingly. */ if (!RightSigned && Expr2.IVal < 0) { /* Correct the value so it is an unsigned. It will then * anyway match one of the cases below. */ Expr2.IVal = LeftMax + 1; } /* Comparing a char against a constant may have a constant * result. Please note: It is not possible to remove the code * for the compare alltogether, because it may have side * effects. */ switch (Tok) { case TOK_EQ: if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) { ED_MakeConstAbsInt (Expr, 0); WarnConstCompareResult (); goto Done; } break; case TOK_NE: if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) { ED_MakeConstAbsInt (Expr, 1); WarnConstCompareResult (); goto Done; } break; case TOK_LT: if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) { ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax); WarnConstCompareResult (); goto Done; } break; case TOK_LE: if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) { ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax); WarnConstCompareResult (); goto Done; } break; case TOK_GE: if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) { ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin); WarnConstCompareResult (); goto Done; } break; case TOK_GT: if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) { ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin); WarnConstCompareResult (); goto Done; } break; default: Internal ("hie_compare: got token 0x%X\n", Tok); } /* If the result is not already constant (as evaluated in the * switch above), we can execute the operation as a char op, * since the right side constant is in a valid range. */ flags |= (CF_CHAR | CF_FORCECHAR); if (!LeftSigned) { flags |= CF_UNSIGNED; } } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) && GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) { /* Both are chars with the same signedness. We can encode the * operation as a char operation. */ flags |= CF_CHAR; if (rconst) { flags |= CF_FORCECHAR; } if (!LeftSigned) { flags |= CF_UNSIGNED; } } else { unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST); flags |= g_typeadjust (ltype, rtype); } /* If the left side is an unsigned and the right is a constant, * we may be able to change the compares to something more * effective. */ if (!LeftSigned && rconst) { switch (Tok) { case TOK_LT: if (Expr2.IVal == 1) { /* An unsigned compare to one means that the value * must be zero. */ GenFunc = g_eq; Expr2.IVal = 0; } break; case TOK_LE: if (Expr2.IVal == 0) { /* An unsigned compare to zero means that the value * must be zero. */ GenFunc = g_eq; } break; case TOK_GE: if (Expr2.IVal == 1) { /* An unsigned compare to one means that the value * must not be zero. */ GenFunc = g_ne; Expr2.IVal = 0; } break; case TOK_GT: if (Expr2.IVal == 0) { /* An unsigned compare to zero means that the value * must not be zero. */ GenFunc = g_ne; } break; default: break; } } /* Generate code */ GenFunc (flags, Expr2.IVal); /* The result is an rvalue in the primary */ ED_MakeRValExpr (Expr); } /* Result type is always int */ Expr->Type = type_int; Done: /* Condition codes are set */ ED_TestDone (Expr); } } static void hie9 (ExprDesc *Expr) /* Process * and / operators. */ { static const GenDesc hie9_ops[] = { { TOK_STAR, GEN_NOPUSH | GEN_COMM, g_mul }, { TOK_DIV, GEN_NOPUSH, g_div }, { TOK_MOD, GEN_NOPUSH, g_mod }, { TOK_INVALID, 0, 0 } }; int UsedGen; hie_internal (hie9_ops, Expr, hie10, &UsedGen); } static void parseadd (ExprDesc* Expr) /* Parse an expression with the binary plus operator. Expr contains the * unprocessed left hand side of the expression and will contain the * result of the expression on return. */ { ExprDesc Expr2; unsigned flags; /* Operation flags */ CodeMark Mark; /* Remember code position */ Type* lhst; /* Type of left hand side */ Type* rhst; /* Type of right hand side */ /* Skip the PLUS token */ NextToken (); /* Get the left hand side type, initialize operation flags */ lhst = Expr->Type; flags = 0; /* Check for constness on both sides */ if (ED_IsConst (Expr)) { /* The left hand side is a constant of some sort. Good. Get rhs */ ExprWithCheck (hie9, &Expr2); if (ED_IsConstAbs (&Expr2)) { /* Right hand side is a constant numeric value. Get the rhs type */ rhst = Expr2.Type; /* Both expressions are constants. Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst); /* Result type is a pointer */ } else if (IsClassInt (lhst) && IsClassPtr (rhst)) { /* Left is int, right is pointer, must scale lhs */ Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal; /* Result type is a pointer */ Expr->Type = Expr2.Type; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer addition */ Expr->IVal += Expr2.IVal; typeadjust (Expr, &Expr2, 1); } else { /* OOPS */ Error ("Invalid operands for binary operator `+'"); } } else { /* lhs is a constant and rhs is not constant. Load rhs into * the primary. */ LoadExpr (CF_NONE, &Expr2); /* Beware: The check above (for lhs) lets not only pass numeric * constants, but also constant addresses (labels), maybe even * with an offset. We have to check for that here. */ /* First, get the rhs type. */ rhst = Expr2.Type; /* Setup flags */ if (ED_IsLocAbs (Expr)) { /* A numerical constant */ flags |= CF_CONST; } else { /* Constant address label */ flags |= GlobalModeFlags (Expr) | CF_CONSTADDR; } /* Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ g_scale (CF_INT, CheckedPSizeOf (lhst)); /* Operate on pointers, result type is a pointer */ flags |= CF_PTR; /* Generate the code for the add */ if (ED_GetLoc (Expr) == E_LOC_ABS) { /* Numeric constant */ g_inc (flags, Expr->IVal); } else { /* Constant address */ g_addaddr_static (flags, Expr->Name, Expr->IVal); } } else if (IsClassInt (lhst) && IsClassPtr (rhst)) { /* Left is int, right is pointer, must scale lhs. */ unsigned ScaleFactor = CheckedPSizeOf (rhst); /* Operate on pointers, result type is a pointer */ flags |= CF_PTR; Expr->Type = Expr2.Type; /* Since we do already have rhs in the primary, if lhs is * not a numeric constant, and the scale factor is not one * (no scaling), we must take the long way over the stack. */ if (ED_IsLocAbs (Expr)) { /* Numeric constant, scale lhs */ Expr->IVal *= ScaleFactor; /* Generate the code for the add */ g_inc (flags, Expr->IVal); } else if (ScaleFactor == 1) { /* Constant address but no need to scale */ g_addaddr_static (flags, Expr->Name, Expr->IVal); } else { /* Constant address that must be scaled */ g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */ g_getimmed (flags, Expr->Name, Expr->IVal); g_scale (CF_PTR, ScaleFactor); g_add (CF_PTR, 0); } } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer addition */ flags |= typeadjust (Expr, &Expr2, 1); /* Generate the code for the add */ if (ED_IsLocAbs (Expr)) { /* Numeric constant */ g_inc (flags, Expr->IVal); } else { /* Constant address */ g_addaddr_static (flags, Expr->Name, Expr->IVal); } } else { /* OOPS */ Error ("Invalid operands for binary operator `+'"); flags = CF_INT; } /* Result is a rvalue in primary register */ ED_MakeRValExpr (Expr); } } else { /* Left hand side is not constant. Get the value onto the stack. */ LoadExpr (CF_NONE, Expr); /* --> primary register */ GetCodePos (&Mark); g_push (TypeOf (Expr->Type), 0); /* --> stack */ /* Evaluate the rhs */ MarkedExprWithCheck (hie9, &Expr2); /* Check for a constant rhs expression */ if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) { /* Right hand side is a constant. Get the rhs type */ rhst = Expr2.Type; /* Remove pushed value from stack */ RemoveCode (&Mark); /* Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ Expr2.IVal *= CheckedPSizeOf (lhst); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; } else if (IsClassInt (lhst) && IsClassPtr (rhst)) { /* Left is int, right is pointer, must scale lhs (ptr only) */ g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst)); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; Expr->Type = Expr2.Type; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer addition */ flags = typeadjust (Expr, &Expr2, 1); } else { /* OOPS */ Error ("Invalid operands for binary operator `+'"); flags = CF_INT; } /* Generate code for the add */ g_inc (flags | CF_CONST, Expr2.IVal); } else { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); /* lhs and rhs are not constant. Get the rhs type. */ rhst = Expr2.Type; /* Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ g_scale (CF_INT, CheckedPSizeOf (lhst)); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; } else if (IsClassInt (lhst) && IsClassPtr (rhst)) { /* Left is int, right is pointer, must scale lhs */ g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */ g_swap (CF_INT); /* Swap TOS and primary */ g_scale (CF_INT, CheckedPSizeOf (rhst)); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; Expr->Type = Expr2.Type; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer addition. Note: Result is never constant. * Problem here is that typeadjust does not know if the * variable is an rvalue or lvalue, so if both operands * are dereferenced constant numeric addresses, typeadjust * thinks the operation works on constants. Removing * CF_CONST here means handling the symptoms, however, the * whole parser is such a mess that I fear to break anything * when trying to apply another solution. */ flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST; } else { /* OOPS */ Error ("Invalid operands for binary operator `+'"); flags = CF_INT; } /* Generate code for the add */ g_add (flags, 0); } /* Result is a rvalue in primary register */ ED_MakeRValExpr (Expr); } /* Condition codes not set */ ED_MarkAsUntested (Expr); } static void parsesub (ExprDesc* Expr) /* Parse an expression with the binary minus operator. Expr contains the * unprocessed left hand side of the expression and will contain the * result of the expression on return. */ { ExprDesc Expr2; unsigned flags; /* Operation flags */ Type* lhst; /* Type of left hand side */ Type* rhst; /* Type of right hand side */ CodeMark Mark1; /* Save position of output queue */ CodeMark Mark2; /* Another position in the queue */ int rscale; /* Scale factor for the result */ /* Skip the MINUS token */ NextToken (); /* Get the left hand side type, initialize operation flags */ lhst = Expr->Type; rscale = 1; /* Scale by 1, that is, don't scale */ /* Remember the output queue position, then bring the value onto the stack */ GetCodePos (&Mark1); LoadExpr (CF_NONE, Expr); /* --> primary register */ GetCodePos (&Mark2); g_push (TypeOf (lhst), 0); /* --> stack */ /* Parse the right hand side */ MarkedExprWithCheck (hie9, &Expr2); /* Check for a constant rhs expression */ if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) { /* The right hand side is constant. Get the rhs type. */ rhst = Expr2.Type; /* Check left hand side */ if (ED_IsConstAbs (Expr)) { /* Both sides are constant, remove generated code */ RemoveCode (&Mark1); /* Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst); /* Operate on pointers, result type is a pointer */ } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) { /* Left is pointer, right is pointer, must scale result */ if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) { Error ("Incompatible pointer types"); } else { Expr->IVal = (Expr->IVal - Expr2.IVal) / CheckedPSizeOf (lhst); } /* Operate on pointers, result type is an integer */ Expr->Type = type_int; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer subtraction */ typeadjust (Expr, &Expr2, 1); Expr->IVal -= Expr2.IVal; } else { /* OOPS */ Error ("Invalid operands for binary operator `-'"); } /* Result is constant, condition codes not set */ ED_MarkAsUntested (Expr); } else { /* Left hand side is not constant, right hand side is. * Remove pushed value from stack. */ RemoveCode (&Mark2); if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ Expr2.IVal *= CheckedPSizeOf (lhst); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) { /* Left is pointer, right is pointer, must scale result */ if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) { Error ("Incompatible pointer types"); } else { rscale = CheckedPSizeOf (lhst); } /* Operate on pointers, result type is an integer */ flags = CF_PTR; Expr->Type = type_int; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer subtraction */ flags = typeadjust (Expr, &Expr2, 1); } else { /* OOPS */ Error ("Invalid operands for binary operator `-'"); flags = CF_INT; } /* Do the subtraction */ g_dec (flags | CF_CONST, Expr2.IVal); /* If this was a pointer subtraction, we must scale the result */ if (rscale != 1) { g_scale (flags, -rscale); } /* Result is a rvalue in the primary register */ ED_MakeRValExpr (Expr); ED_MarkAsUntested (Expr); } } else { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); /* Right hand side is not constant. Get the rhs type. */ rhst = Expr2.Type; /* Check for pointer arithmetic */ if (IsClassPtr (lhst) && IsClassInt (rhst)) { /* Left is pointer, right is int, must scale rhs */ g_scale (CF_INT, CheckedPSizeOf (lhst)); /* Operate on pointers, result type is a pointer */ flags = CF_PTR; } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) { /* Left is pointer, right is pointer, must scale result */ if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) { Error ("Incompatible pointer types"); } else { rscale = CheckedPSizeOf (lhst); } /* Operate on pointers, result type is an integer */ flags = CF_PTR; Expr->Type = type_int; } else if (IsClassInt (lhst) && IsClassInt (rhst)) { /* Integer subtraction. If the left hand side descriptor says that * the lhs is const, we have to remove this mark, since this is no * longer true, lhs is on stack instead. */ if (ED_IsLocAbs (Expr)) { ED_MakeRValExpr (Expr); } /* Adjust operand types */ flags = typeadjust (Expr, &Expr2, 0); } else { /* OOPS */ Error ("Invalid operands for binary operator `-'"); flags = CF_INT; } /* Generate code for the sub (the & is a hack here) */ g_sub (flags & ~CF_CONST, 0); /* If this was a pointer subtraction, we must scale the result */ if (rscale != 1) { g_scale (flags, -rscale); } /* Result is a rvalue in the primary register */ ED_MakeRValExpr (Expr); ED_MarkAsUntested (Expr); } } void hie8 (ExprDesc* Expr) /* Process + and - binary operators. */ { ExprWithCheck (hie9, Expr); while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) { if (CurTok.Tok == TOK_PLUS) { parseadd (Expr); } else { parsesub (Expr); } } } static void hie6 (ExprDesc* Expr) /* Handle greater-than type comparators */ { static const GenDesc hie6_ops [] = { { TOK_LT, GEN_NOPUSH, g_lt }, { TOK_LE, GEN_NOPUSH, g_le }, { TOK_GE, GEN_NOPUSH, g_ge }, { TOK_GT, GEN_NOPUSH, g_gt }, { TOK_INVALID, 0, 0 } }; hie_compare (hie6_ops, Expr, ShiftExpr); } static void hie5 (ExprDesc* Expr) /* Handle == and != */ { static const GenDesc hie5_ops[] = { { TOK_EQ, GEN_NOPUSH, g_eq }, { TOK_NE, GEN_NOPUSH, g_ne }, { TOK_INVALID, 0, 0 } }; hie_compare (hie5_ops, Expr, hie6); } static void hie4 (ExprDesc* Expr) /* Handle & (bitwise and) */ { static const GenDesc hie4_ops[] = { { TOK_AND, GEN_NOPUSH | GEN_COMM, g_and }, { TOK_INVALID, 0, 0 } }; int UsedGen; hie_internal (hie4_ops, Expr, hie5, &UsedGen); } static void hie3 (ExprDesc* Expr) /* Handle ^ (bitwise exclusive or) */ { static const GenDesc hie3_ops[] = { { TOK_XOR, GEN_NOPUSH | GEN_COMM, g_xor }, { TOK_INVALID, 0, 0 } }; int UsedGen; hie_internal (hie3_ops, Expr, hie4, &UsedGen); } static void hie2 (ExprDesc* Expr) /* Handle | (bitwise or) */ { static const GenDesc hie2_ops[] = { { TOK_OR, GEN_NOPUSH | GEN_COMM, g_or }, { TOK_INVALID, 0, 0 } }; int UsedGen; hie_internal (hie2_ops, Expr, hie3, &UsedGen); } static void hieAndPP (ExprDesc* Expr) /* Process "exp && exp" in preprocessor mode (that is, when the parser is * called recursively from the preprocessor. */ { ExprDesc Expr2; ConstAbsIntExpr (hie2, Expr); while (CurTok.Tok == TOK_BOOL_AND) { /* Skip the && */ NextToken (); /* Get rhs */ ConstAbsIntExpr (hie2, &Expr2); /* Combine the two */ Expr->IVal = (Expr->IVal && Expr2.IVal); } } static void hieOrPP (ExprDesc *Expr) /* Process "exp || exp" in preprocessor mode (that is, when the parser is * called recursively from the preprocessor. */ { ExprDesc Expr2; ConstAbsIntExpr (hieAndPP, Expr); while (CurTok.Tok == TOK_BOOL_OR) { /* Skip the && */ NextToken (); /* Get rhs */ ConstAbsIntExpr (hieAndPP, &Expr2); /* Combine the two */ Expr->IVal = (Expr->IVal || Expr2.IVal); } } static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp) /* Process "exp && exp" */ { int FalseLab; ExprDesc Expr2; ExprWithCheck (hie2, Expr); if (CurTok.Tok == TOK_BOOL_AND) { /* Tell our caller that we're evaluating a boolean */ *BoolOp = 1; /* Get a label that we will use for false expressions */ FalseLab = GetLocalLabel (); /* If the expr hasn't set condition codes, set the force-test flag */ if (!ED_IsTested (Expr)) { ED_MarkForTest (Expr); } /* Load the value */ LoadExpr (CF_FORCECHAR, Expr); /* Generate the jump */ g_falsejump (CF_NONE, FalseLab); /* Parse more boolean and's */ while (CurTok.Tok == TOK_BOOL_AND) { /* Skip the && */ NextToken (); /* Get rhs */ hie2 (&Expr2); if (!ED_IsTested (&Expr2)) { ED_MarkForTest (&Expr2); } LoadExpr (CF_FORCECHAR, &Expr2); /* Do short circuit evaluation */ if (CurTok.Tok == TOK_BOOL_AND) { g_falsejump (CF_NONE, FalseLab); } else { /* Last expression - will evaluate to true */ g_truejump (CF_NONE, TrueLab); } } /* Define the false jump label here */ g_defcodelabel (FalseLab); /* The result is an rvalue in primary */ ED_MakeRValExpr (Expr); ED_TestDone (Expr); /* Condition codes are set */ } } static void hieOr (ExprDesc *Expr) /* Process "exp || exp". */ { ExprDesc Expr2; int BoolOp = 0; /* Did we have a boolean op? */ int AndOp; /* Did we have a && operation? */ unsigned TrueLab; /* Jump to this label if true */ unsigned DoneLab; /* Get a label */ TrueLab = GetLocalLabel (); /* Call the next level parser */ hieAnd (Expr, TrueLab, &BoolOp); /* Any boolean or's? */ if (CurTok.Tok == TOK_BOOL_OR) { /* If the expr hasn't set condition codes, set the force-test flag */ if (!ED_IsTested (Expr)) { ED_MarkForTest (Expr); } /* Get first expr */ LoadExpr (CF_FORCECHAR, Expr); /* For each expression jump to TrueLab if true. Beware: If we * had && operators, the jump is already in place! */ if (!BoolOp) { g_truejump (CF_NONE, TrueLab); } /* Remember that we had a boolean op */ BoolOp = 1; /* while there's more expr */ while (CurTok.Tok == TOK_BOOL_OR) { /* skip the || */ NextToken (); /* Get a subexpr */ AndOp = 0; hieAnd (&Expr2, TrueLab, &AndOp); if (!ED_IsTested (&Expr2)) { ED_MarkForTest (&Expr2); } LoadExpr (CF_FORCECHAR, &Expr2); /* If there is more to come, add shortcut boolean eval. */ g_truejump (CF_NONE, TrueLab); } /* The result is an rvalue in primary */ ED_MakeRValExpr (Expr); ED_TestDone (Expr); /* Condition codes are set */ } /* If we really had boolean ops, generate the end sequence */ if (BoolOp) { DoneLab = GetLocalLabel (); g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */ g_falsejump (CF_NONE, DoneLab); g_defcodelabel (TrueLab); g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */ g_defcodelabel (DoneLab); } } static void hieQuest (ExprDesc* Expr) /* Parse the ternary operator */ { int FalseLab; int TrueLab; CodeMark TrueCodeEnd; ExprDesc Expr2; /* Expression 2 */ ExprDesc Expr3; /* Expression 3 */ int Expr2IsNULL; /* Expression 2 is a NULL pointer */ int Expr3IsNULL; /* Expression 3 is a NULL pointer */ Type* ResultType; /* Type of result */ /* Call the lower level eval routine */ if (Preprocessing) { ExprWithCheck (hieOrPP, Expr); } else { ExprWithCheck (hieOr, Expr); } /* Check if it's a ternary expression */ if (CurTok.Tok == TOK_QUEST) { NextToken (); if (!ED_IsTested (Expr)) { /* Condition codes not set, request a test */ ED_MarkForTest (Expr); } LoadExpr (CF_NONE, Expr); FalseLab = GetLocalLabel (); g_falsejump (CF_NONE, FalseLab); /* Parse second expression. Remember for later if it is a NULL pointer * expression, then load it into the primary. */ ExprWithCheck (hie1, &Expr2); Expr2IsNULL = ED_IsNullPtr (&Expr2); if (!IsTypeVoid (Expr2.Type)) { /* Load it into the primary */ LoadExpr (CF_NONE, &Expr2); ED_MakeRValExpr (&Expr2); Expr2.Type = PtrConversion (Expr2.Type); } /* Remember the current code position */ GetCodePos (&TrueCodeEnd); /* Jump around the evaluation of the third expression */ TrueLab = GetLocalLabel (); ConsumeColon (); g_jump (TrueLab); /* Jump here if the first expression was false */ g_defcodelabel (FalseLab); /* Parse third expression. Remember for later if it is a NULL pointer * expression, then load it into the primary. */ ExprWithCheck (hie1, &Expr3); Expr3IsNULL = ED_IsNullPtr (&Expr3); if (!IsTypeVoid (Expr3.Type)) { /* Load it into the primary */ LoadExpr (CF_NONE, &Expr3); ED_MakeRValExpr (&Expr3); Expr3.Type = PtrConversion (Expr3.Type); } /* Check if any conversions are needed, if so, do them. * Conversion rules for ?: expression are: * - if both expressions are int expressions, default promotion * rules for ints apply. * - if both expressions are pointers of the same type, the * result of the expression is of this type. * - if one of the expressions is a pointer and the other is * a zero constant, the resulting type is that of the pointer * type. * - if both expressions are void expressions, the result is of * type void. * - all other cases are flagged by an error. */ if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) { CodeMark CvtCodeStart; CodeMark CvtCodeEnd; /* Get common type */ ResultType = promoteint (Expr2.Type, Expr3.Type); /* Convert the third expression to this type if needed */ TypeConversion (&Expr3, ResultType); /* Emit conversion code for the second expression, but remember * where it starts end ends. */ GetCodePos (&CvtCodeStart); TypeConversion (&Expr2, ResultType); GetCodePos (&CvtCodeEnd); /* If we had conversion code, move it to the right place */ if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) { MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd); } } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) { /* Must point to same type */ if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) { Error ("Incompatible pointer types"); } /* Result has the common type */ ResultType = Expr2.Type; } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) { /* Result type is pointer, no cast needed */ ResultType = Expr2.Type; } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) { /* Result type is pointer, no cast needed */ ResultType = Expr3.Type; } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) { /* Result type is void */ ResultType = Expr3.Type; } else { Error ("Incompatible types"); ResultType = Expr2.Type; /* Doesn't matter here */ } /* Define the final label */ g_defcodelabel (TrueLab); /* Setup the target expression */ ED_MakeRValExpr (Expr); Expr->Type = ResultType; } } static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op) /* Process "op=" operators. */ { ExprDesc Expr2; unsigned flags; CodeMark Mark; int MustScale; /* op= can only be used with lvalues */ if (!ED_IsLVal (Expr)) { Error ("Invalid lvalue in assignment"); return; } /* The left side must not be const qualified */ if (IsQualConst (Expr->Type)) { Error ("Assignment to const"); } /* There must be an integer or pointer on the left side */ if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) { Error ("Invalid left operand type"); /* Continue. Wrong code will be generated, but the compiler won't * break, so this is the best error recovery. */ } /* Skip the operator token */ NextToken (); /* Determine the type of the lhs */ flags = TypeOf (Expr->Type); MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type); /* Get the lhs address on stack (if needed) */ PushAddr (Expr); /* Fetch the lhs into the primary register if needed */ LoadExpr (CF_NONE, Expr); /* Bring the lhs on stack */ GetCodePos (&Mark); g_push (flags, 0); /* Evaluate the rhs */ MarkedExprWithCheck (hie1, &Expr2); /* The rhs must be an integer (or a float, but we don't support that yet */ if (!IsClassInt (Expr2.Type)) { Error ("Invalid right operand for binary operator `%s'", Op); /* Continue. Wrong code will be generated, but the compiler won't * break, so this is the best error recovery. */ } /* Check for a constant expression */ if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) { /* The resulting value is a constant. If the generator has the NOPUSH * flag set, don't push the lhs. */ if (Gen->Flags & GEN_NOPUSH) { RemoveCode (&Mark); } if (MustScale) { /* lhs is a pointer, scale rhs */ Expr2.IVal *= CheckedSizeOf (Expr->Type+1); } /* If the lhs is character sized, the operation may be later done * with characters. */ if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) { flags |= CF_FORCECHAR; } /* Special handling for add and sub - some sort of a hack, but short code */ if (Gen->Func == g_add) { g_inc (flags | CF_CONST, Expr2.IVal); } else if (Gen->Func == g_sub) { g_dec (flags | CF_CONST, Expr2.IVal); } else { if (Expr2.IVal == 0) { /* Check for div by zero/mod by zero */ if (Gen->Func == g_div) { Error ("Division by zero"); } else if (Gen->Func == g_mod) { Error ("Modulo operation with zero"); } } Gen->Func (flags | CF_CONST, Expr2.IVal); } } else { /* rhs is not constant. Load into the primary */ LoadExpr (CF_NONE, &Expr2); if (MustScale) { /* lhs is a pointer, scale rhs */ g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1)); } /* If the lhs is character sized, the operation may be later done * with characters. */ if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) { flags |= CF_FORCECHAR; } /* Adjust the types of the operands if needed */ Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0); } Store (Expr, 0); ED_MakeRValExpr (Expr); } static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op) /* Process the += and -= operators */ { ExprDesc Expr2; unsigned lflags; unsigned rflags; int MustScale; /* We're currently only able to handle some adressing modes */ if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) { /* Use generic routine */ opeq (Gen, Expr, Op); return; } /* We must have an lvalue */ if (ED_IsRVal (Expr)) { Error ("Invalid lvalue in assignment"); return; } /* The left side must not be const qualified */ if (IsQualConst (Expr->Type)) { Error ("Assignment to const"); } /* There must be an integer or pointer on the left side */ if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) { Error ("Invalid left operand type"); /* Continue. Wrong code will be generated, but the compiler won't * break, so this is the best error recovery. */ } /* Skip the operator */ NextToken (); /* Check if we have a pointer expression and must scale rhs */ MustScale = IsTypePtr (Expr->Type); /* Initialize the code generator flags */ lflags = 0; rflags = 0; /* Evaluate the rhs. We expect an integer here, since float is not * supported */ hie1 (&Expr2); if (!IsClassInt (Expr2.Type)) { Error ("Invalid right operand for binary operator `%s'", Op); /* Continue. Wrong code will be generated, but the compiler won't * break, so this is the best error recovery. */ } if (ED_IsConstAbs (&Expr2)) { /* The resulting value is a constant. Scale it. */ if (MustScale) { Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type)); } rflags |= CF_CONST; lflags |= CF_CONST; } else { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); if (MustScale) { /* lhs is a pointer, scale rhs */ g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type))); } } /* Setup the code generator flags */ lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR; rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR; /* Convert the type of the lhs to that of the rhs */ g_typecast (lflags, rflags); /* Output apropriate code depending on the location */ switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ if (Gen->Tok == TOK_PLUS_ASSIGN) { g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } else { g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } break; case E_LOC_GLOBAL: /* Global variable */ if (Gen->Tok == TOK_PLUS_ASSIGN) { g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } else { g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ if (Gen->Tok == TOK_PLUS_ASSIGN) { g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } else { g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } break; case E_LOC_REGISTER: /* Register variable */ if (Gen->Tok == TOK_PLUS_ASSIGN) { g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } else { g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal); } break; case E_LOC_STACK: /* Value on the stack */ if (Gen->Tok == TOK_PLUS_ASSIGN) { g_addeqlocal (lflags, Expr->IVal, Expr2.IVal); } else { g_subeqlocal (lflags, Expr->IVal, Expr2.IVal); } break; default: Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr)); } /* Expression is a rvalue in the primary now */ ED_MakeRValExpr (Expr); } void hie1 (ExprDesc* Expr) /* Parse first level of expression hierarchy. */ { hieQuest (Expr); switch (CurTok.Tok) { case TOK_ASSIGN: Assignment (Expr); break; case TOK_PLUS_ASSIGN: addsubeq (&GenPASGN, Expr, "+="); break; case TOK_MINUS_ASSIGN: addsubeq (&GenSASGN, Expr, "-="); break; case TOK_MUL_ASSIGN: opeq (&GenMASGN, Expr, "*="); break; case TOK_DIV_ASSIGN: opeq (&GenDASGN, Expr, "/="); break; case TOK_MOD_ASSIGN: opeq (&GenMOASGN, Expr, "%="); break; case TOK_SHL_ASSIGN: opeq (&GenSLASGN, Expr, "<<="); break; case TOK_SHR_ASSIGN: opeq (&GenSRASGN, Expr, ">>="); break; case TOK_AND_ASSIGN: opeq (&GenAASGN, Expr, "&="); break; case TOK_XOR_ASSIGN: opeq (&GenXOASGN, Expr, "^="); break; case TOK_OR_ASSIGN: opeq (&GenOASGN, Expr, "|="); break; default: break; } } void hie0 (ExprDesc *Expr) /* Parse comma operator. */ { hie1 (Expr); while (CurTok.Tok == TOK_COMMA) { NextToken (); hie1 (Expr); } } int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr) /* Will evaluate an expression via the given function. If the result is a * constant, 0 is returned and the value is put in the Expr struct. If the * result is not constant, LoadExpr is called to bring the value into the * primary register and 1 is returned. */ { /* Evaluate */ ExprWithCheck (Func, Expr); /* Check for a constant expression */ if (ED_IsConstAbs (Expr)) { /* Constant expression */ return 0; } else { /* Not constant, load into the primary */ LoadExpr (Flags, Expr); return 1; } } void Expression0 (ExprDesc* Expr) /* Evaluate an expression via hie0 and put the result into the primary register */ { ExprWithCheck (hie0, Expr); LoadExpr (CF_NONE, Expr); } void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr) /* Will evaluate an expression via the given function. If the result is not * a constant of some sort, a diagnostic will be printed, and the value is * replaced by a constant one to make sure there are no internal errors that * result from this input error. */ { ExprWithCheck (Func, Expr); if (!ED_IsConst (Expr)) { Error ("Constant expression expected"); /* To avoid any compiler errors, make the expression a valid const */ ED_MakeConstAbsInt (Expr, 1); } } void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr) /* Will evaluate an expression via the given function. If the result is not * something that may be evaluated in a boolean context, a diagnostic will be * printed, and the value is replaced by a constant one to make sure there * are no internal errors that result from this input error. */ { ExprWithCheck (Func, Expr); if (!ED_IsBool (Expr)) { Error ("Boolean expression expected"); /* To avoid any compiler errors, make the expression a valid int */ ED_MakeConstAbsInt (Expr, 1); } } void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr) /* Will evaluate an expression via the given function. If the result is not * a constant numeric integer value, a diagnostic will be printed, and the * value is replaced by a constant one to make sure there are no internal * errors that result from this input error. */ { ExprWithCheck (Func, Expr); if (!ED_IsConstAbsInt (Expr)) { Error ("Constant integer expression expected"); /* To avoid any compiler errors, make the expression a valid const */ ED_MakeConstAbsInt (Expr, 1); } }
825
./cc65/src/cc65/standard.c
/*****************************************************************************/ /* */ /* standard.c */ /* */ /* Language standard definitions */ /* */ /* */ /* */ /* (C) 2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* cc65 */ #include "standard.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Current language standard, will be set to STD_DEFAULT on startup */ IntStack Standard = INTSTACK(STD_UNKNOWN); /* Table mapping names to standards, sorted by standard. */ static const char* StdNames[STD_COUNT] = { "c89", "c99", "cc65" }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ standard_t FindStandard (const char* Name) /* Find a standard by name. Returns one of the constants defined above. * STD_UNKNOWN is returned if Name doesn't match a standard. */ { unsigned I; /* Check for a standard string */ for (I = 0; I < STD_COUNT; ++I) { if (strcmp (StdNames [I], Name) == 0) { return (standard_t)I; } } /* Not found */ return STD_UNKNOWN; }
826
./cc65/src/cc65/output.c
/*****************************************************************************/ /* */ /* output.c */ /* */ /* Output file handling */ /* */ /* */ /* */ /* (C) 2009-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <errno.h> /* common */ #include "check.h" #include "fname.h" #include "print.h" #include "xmalloc.h" /* cc65 */ #include "error.h" #include "global.h" #include "output.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Name of the output file. Dynamically allocated and read only. */ const char* OutputFilename = 0; /* Output file handle */ FILE* OutputFile = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SetOutputName (const char* Name) /* Sets the name of the output file. */ { OutputFilename = Name; } void MakeDefaultOutputName (const char* InputFilename) /* If the name of the output file is empty or NULL, the name of the output * file is derived from the input file by adjusting the file name extension. */ { if (OutputFilename == 0 || *OutputFilename == '\0') { /* We don't have an output file for now */ const char* Ext = PreprocessOnly? ".i" : ".s"; OutputFilename = MakeFilename (InputFilename, Ext); } } void OpenOutputFile () /* Open the output file. Will call Fatal() in case of failures. */ { /* Output file must not be open and we must have a name*/ PRECONDITION (OutputFile == 0 && OutputFilename != 0); /* Open the file */ OutputFile = fopen (OutputFilename, "w"); if (OutputFile == 0) { Fatal ("Cannot open output file `%s': %s", OutputFilename, strerror (errno)); } Print (stdout, 1, "Opened output file `%s'\n", OutputFilename); } void OpenDebugOutputFile (const char* Name) /* Open an output file for debugging purposes. Will call Fatal() in case of * failures. */ { /* Output file must not be open and we must have a name*/ PRECONDITION (OutputFile == 0); /* Open the file */ OutputFile = fopen (Name, "w"); if (OutputFile == 0) { Fatal ("Cannot open debug output file `%s': %s", Name, strerror (errno)); } Print (stdout, 1, "Opened debug output file `%s'\n", Name); } void CloseOutputFile () /* Close the output file. Will call Fatal() in case of failures. */ { /* Output file must be open */ PRECONDITION (OutputFile != 0); /* Close the file, check for errors */ if (fclose (OutputFile) != 0) { remove (OutputFilename); Fatal ("Cannot write to output file (disk full?)"); } Print (stdout, 1, "Closed output file `%s'\n", OutputFilename); OutputFile = 0; } int WriteOutput (const char* Format, ...) /* Write to the output file using printf like formatting. Returns the number * of chars written. */ { va_list ap; int CharCount; /* Must have an output file */ PRECONDITION (OutputFile != 0); /* Output formatted */ va_start (ap, Format); CharCount = vfprintf (OutputFile, Format, ap); va_end (ap); /* Return the number of chars written */ return CharCount; }
827
./cc65/src/cc65/ident.c
/*****************************************************************************/ /* */ /* ident.c */ /* */ /* Identifier handling for the cc65 compiler */ /* */ /* */ /* */ /* (C) 1998 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" /* cc65 */ #include "ident.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int IsIdent (char c) /* Return true if the given char may start an identifier */ { return (IsAlpha (c) || c == '_'); }
828
./cc65/src/cc65/util.c
/*****************************************************************************/ /* */ /* util.c */ /* */ /* Utility functions for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "util.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int PowerOf2 (unsigned long Val) /* Return the exponent if val is a power of two. Return -1 if val is not a * power of two. */ { int I; unsigned long Mask = 0x0001; for (I = 0; I < 32; ++I) { if (Val == Mask) { return I; } Mask <<= 1; } return -1; }
829
./cc65/src/cc65/goto.c
/*****************************************************************************/ /* */ /* goto.c */ /* */ /* Goto and label handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "codegen.h" #include "error.h" #include "scanner.h" #include "symtab.h" #include "goto.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void GotoStatement (void) /* Process a goto statement. */ { /* Eat the "goto" */ NextToken (); /* Label name must follow */ if (CurTok.Tok != TOK_IDENT) { Error ("Label name expected"); } else { /* Add a new label symbol if we don't have one until now */ SymEntry* Entry = AddLabelSym (CurTok.Ident, SC_REF); /* Jump to the label */ g_jump (Entry->V.Label); } /* Eat the label name */ NextToken (); } void DoLabel (void) /* Define a label. */ { /* Add a label symbol */ SymEntry* Entry = AddLabelSym (CurTok.Ident, SC_DEF); /* Emit the jump label */ g_defcodelabel (Entry->V.Label); /* Eat the ident and colon */ NextToken (); NextToken (); }
830
./cc65/src/cc65/function.c
/*****************************************************************************/ /* */ /* function.c */ /* */ /* Parse function entry/body/exit */ /* */ /* */ /* */ /* (C) 2000-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "codegen.h" #include "error.h" #include "funcdesc.h" #include "global.h" #include "litpool.h" #include "locals.h" #include "scanner.h" #include "stackptr.h" #include "standard.h" #include "stmt.h" #include "symtab.h" #include "function.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Enumeration for function flags */ typedef enum { FF_NONE = 0x0000, FF_HAS_RETURN = 0x0001, /* Function has a return statement */ FF_IS_MAIN = 0x0002, /* This is the main function */ FF_VOID_RETURN = 0x0004, /* Function returning void */ } funcflags_t; /* Structure that holds all data needed for function activation */ struct Function { struct SymEntry* FuncEntry; /* Symbol table entry */ Type* ReturnType; /* Function return type */ FuncDesc* Desc; /* Function descriptor */ int Reserved; /* Reserved local space */ unsigned RetLab; /* Return code label */ int TopLevelSP; /* SP at function top level */ unsigned RegOffs; /* Register variable space offset */ funcflags_t Flags; /* Function flags */ }; /* Pointer to current function */ Function* CurrentFunc = 0; /*****************************************************************************/ /* Subroutines working with struct Function */ /*****************************************************************************/ static Function* NewFunction (struct SymEntry* Sym) /* Create a new function activation structure and return it */ { /* Allocate a new structure */ Function* F = (Function*) xmalloc (sizeof (Function)); /* Initialize the fields */ F->FuncEntry = Sym; F->ReturnType = GetFuncReturn (Sym->Type); F->Desc = GetFuncDesc (Sym->Type); F->Reserved = 0; F->RetLab = GetLocalLabel (); F->TopLevelSP = 0; F->RegOffs = RegisterSpace; F->Flags = IsTypeVoid (F->ReturnType) ? FF_VOID_RETURN : FF_NONE; /* Return the new structure */ return F; } static void FreeFunction (Function* F) /* Free a function activation structure */ { xfree (F); } const char* F_GetFuncName (const Function* F) /* Return the name of the current function */ { return F->FuncEntry->Name; } unsigned F_GetParamCount (const Function* F) /* Return the parameter count for the current function */ { return F->Desc->ParamCount; } unsigned F_GetParamSize (const Function* F) /* Return the parameter size for the current function */ { return F->Desc->ParamSize; } Type* F_GetReturnType (Function* F) /* Get the return type for the function */ { return F->ReturnType; } int F_HasVoidReturn (const Function* F) /* Return true if the function does not have a return value */ { return (F->Flags & FF_VOID_RETURN) != 0; } void F_ReturnFound (Function* F) /* Mark the function as having a return statement */ { F->Flags |= FF_HAS_RETURN; } int F_HasReturn (const Function* F) /* Return true if the function contains a return statement*/ { return (F->Flags & FF_HAS_RETURN) != 0; } int F_IsMainFunc (const Function* F) /* Return true if this is the main function */ { return (F->Flags & FF_IS_MAIN) != 0; } int F_IsVariadic (const Function* F) /* Return true if this is a variadic function */ { return (F->Desc->Flags & FD_VARIADIC) != 0; } int F_IsOldStyle (const Function* F) /* Return true if this is an old style (K&R) function */ { return (F->Desc->Flags & FD_OLDSTYLE) != 0; } int F_HasOldStyleIntRet (const Function* F) /* Return true if this is an old style (K&R) function with an implicit int return */ { return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0; } unsigned F_GetRetLab (const Function* F) /* Return the return jump label */ { return F->RetLab; } int F_GetTopLevelSP (const Function* F) /* Get the value of the stack pointer on function top level */ { return F->TopLevelSP; } int F_ReserveLocalSpace (Function* F, unsigned Size) /* Reserve (but don't allocate) the given local space and return the stack * offset. */ { F->Reserved += Size; return StackPtr - F->Reserved; } int F_GetStackPtr (const Function* F) /* Return the current stack pointer including reserved (but not allocated) * space on the stack. */ { return StackPtr - F->Reserved; } void F_AllocLocalSpace (Function* F) /* Allocate any local space previously reserved. The function will do * nothing if there is no reserved local space. */ { if (F->Reserved > 0) { /* Create space on the stack */ g_space (F->Reserved); /* Correct the stack pointer */ StackPtr -= F->Reserved; /* Nothing more reserved */ F->Reserved = 0; } } int F_AllocRegVar (Function* F, const Type* Type) /* Allocate a register variable for the given variable type. If the allocation * was successful, return the offset of the register variable in the register * bank (zero page storage). If there is no register space left, return -1. */ { /* Allow register variables only on top level and if enabled */ if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) { /* Get the size of the variable */ unsigned Size = CheckedSizeOf (Type); /* Do we have space left? */ if (F->RegOffs >= Size) { /* Space left. We allocate the variables from high to low addresses, * so the adressing is compatible with the saved values on stack. * This allows shorter code when saving/restoring the variables. */ F->RegOffs -= Size; return F->RegOffs; } } /* No space left or no allocation */ return -1; } static void F_RestoreRegVars (Function* F) /* Restore the register variables for the local function if there are any. */ { const SymEntry* Sym; /* If we don't have register variables in this function, bail out early */ if (F->RegOffs == RegisterSpace) { return; } /* Save the accumulator if needed */ if (!F_HasVoidReturn (F)) { g_save (CF_CHAR | CF_FORCECHAR); } /* Get the first symbol from the function symbol table */ Sym = F->FuncEntry->V.F.Func->SymTab->SymHead; /* Walk through all symbols checking for register variables */ while (Sym) { if (SymIsRegVar (Sym)) { /* Check for more than one variable */ int Offs = Sym->V.R.SaveOffs; unsigned Bytes = CheckedSizeOf (Sym->Type); while (1) { /* Find next register variable */ const SymEntry* NextSym = Sym->NextSym; while (NextSym && !SymIsRegVar (NextSym)) { NextSym = NextSym->NextSym; } /* If we have a next one, compare the stack offsets */ if (NextSym) { /* We have a following register variable. Get the size */ int Size = CheckedSizeOf (NextSym->Type); /* Adjacent variable? */ if (NextSym->V.R.SaveOffs + Size != Offs) { /* No */ break; } /* Adjacent variable */ Bytes += Size; Offs -= Size; Sym = NextSym; } else { break; } } /* Restore the memory range */ g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes); } /* Check next symbol */ Sym = Sym->NextSym; } /* Restore the accumulator if needed */ if (!F_HasVoidReturn (F)) { g_restore (CF_CHAR | CF_FORCECHAR); } } static void F_EmitDebugInfo (void) /* Emit debug infos for the current function */ { if (DebugInfo) { /* Get the current function */ const SymEntry* Sym = CurrentFunc->FuncEntry; /* Output info for the function itself */ AddTextLine ("\t.dbg\tfunc, \"%s\", \"00\", %s, \"%s\"", Sym->Name, (Sym->Flags & SC_EXTERN)? "extern" : "static", Sym->AsmName); } } /*****************************************************************************/ /* code */ /*****************************************************************************/ void NewFunc (SymEntry* Func) /* Parse argument declarations and function body. */ { int C99MainFunc = 0;/* Flag for C99 main function returning int */ SymEntry* Param; /* Get the function descriptor from the function entry */ FuncDesc* D = Func->V.F.Func; /* Allocate the function activation record for the function */ CurrentFunc = NewFunction (Func); /* Reenter the lexical level */ ReenterFunctionLevel (D); /* Check if the function header contains unnamed parameters. These are * only allowed in cc65 mode. */ if ((D->Flags & FD_UNNAMED_PARAMS) != 0 && (IS_Get (&Standard) != STD_CC65)) { Error ("Parameter name omitted"); } /* Declare two special functions symbols: __fixargs__ and __argsize__. * The latter is different depending on the type of the function (variadic * or not). */ AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize); if (D->Flags & FD_VARIADIC) { /* Variadic function. The variable must be const. */ static const Type T[] = { TYPE(T_UCHAR | T_QUAL_CONST), TYPE(T_END) }; AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0); } else { /* Non variadic */ AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize); } /* Function body now defined */ Func->Flags |= SC_DEF; /* Special handling for main() */ if (strcmp (Func->Name, "main") == 0) { /* Mark this as the main function */ CurrentFunc->Flags |= FF_IS_MAIN; /* Main cannot be a fastcall function */ if (IsQualFastcall (Func->Type)) { Error ("`main' cannot be declared as __fastcall__"); } /* If cc65 extensions aren't enabled, don't allow a main function that * doesn't return an int. */ if (IS_Get (&Standard) != STD_CC65 && CurrentFunc->ReturnType[0].C != T_INT) { Error ("`main' must always return an int"); } /* Add a forced import of a symbol that is contained in the startup * code. This will force the startup code to be linked in. */ g_importstartup (); /* If main() takes parameters, generate a forced import to a function * that will setup these parameters. This way, programs that do not * need the additional code will not get it. */ if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) { g_importmainargs (); } /* Determine if this is a main function in a C99 environment that * returns an int. */ if (IsTypeInt (F_GetReturnType (CurrentFunc)) && IS_Get (&Standard) == STD_C99) { C99MainFunc = 1; } } /* Allocate code and data segments for this function */ Func->V.F.Seg = PushSegments (Func); /* Allocate a new literal pool */ PushLiteralPool (Func); /* If this is a fastcall function, push the last parameter onto the stack */ if (IsQualFastcall (Func->Type) && D->ParamCount > 0) { unsigned Flags; /* Fastcall functions may never have an ellipsis or the compiler is buggy */ CHECK ((D->Flags & FD_VARIADIC) == 0); /* Generate the push */ if (IsTypeFunc (D->LastParam->Type)) { /* Pointer to function */ Flags = CF_PTR; } else { Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR; } g_push (Flags, 0); } /* Generate function entry code if needed */ g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc)); /* If stack checking code is requested, emit a call to the helper routine */ if (IS_Get (&CheckStack)) { g_stackcheck (); } /* Setup the stack */ StackPtr = 0; /* Walk through the parameter list and allocate register variable space * for parameters declared as register. Generate code to swap the contents * of the register bank with the save area on the stack. */ Param = D->SymTab->SymHead; while (Param && (Param->Flags & SC_PARAM) != 0) { /* Check for a register variable */ if (SymIsRegVar (Param)) { /* Allocate space */ int Reg = F_AllocRegVar (CurrentFunc, Param->Type); /* Could we allocate a register? */ if (Reg < 0) { /* No register available: Convert parameter to auto */ CvtRegVarToAuto (Param); } else { /* Remember the register offset */ Param->V.R.RegOffs = Reg; /* Generate swap code */ g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type)); } } /* Next parameter */ Param = Param->NextSym; } /* Need a starting curly brace */ ConsumeLCurly (); /* Parse local variable declarations if any */ DeclareLocals (); /* Remember the current stack pointer. All variables allocated elsewhere * must be dropped when doing a return from an inner block. */ CurrentFunc->TopLevelSP = StackPtr; /* Now process statements in this block */ while (CurTok.Tok != TOK_RCURLY && CurTok.Tok != TOK_CEOF) { Statement (0); } /* If this is not a void function, and not the main function in a C99 * environment returning int, output a warning if we didn't see a return * statement. */ if (!F_HasVoidReturn (CurrentFunc) && !F_HasReturn (CurrentFunc) && !C99MainFunc) { Warning ("Control reaches end of non-void function"); } /* If this is the main function in a C99 environment returning an int, let * it always return zero. Note: Actual return statements jump to the return * label defined below. * The code is removed by the optimizer if unused. */ if (C99MainFunc) { g_getimmed (CF_INT | CF_CONST, 0, 0); } /* Output the function exit code label */ g_defcodelabel (F_GetRetLab (CurrentFunc)); /* Restore the register variables */ F_RestoreRegVars (CurrentFunc); /* Generate the exit code */ g_leave (); /* Emit references to imports/exports */ EmitExternals (); /* Emit function debug info */ F_EmitDebugInfo (); EmitDebugInfo (); /* Leave the lexical level */ LeaveFunctionLevel (); /* Eat the closing brace */ ConsumeRCurly (); /* Restore the old literal pool, remembering the one for the function */ Func->V.F.LitPool = PopLiteralPool (); /* Switch back to the old segments */ PopSegments (); /* Reset the current function pointer */ FreeFunction (CurrentFunc); CurrentFunc = 0; }
831
./cc65/src/cc65/swstmt.c
/*****************************************************************************/ /* */ /* swstmt.c */ /* */ /* Parse the switch statement */ /* */ /* */ /* */ /* (C) 1998-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <limits.h> /* common */ #include "coll.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "casenode.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "global.h" #include "loop.h" #include "scanner.h" #include "stmt.h" #include "swstmt.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ typedef struct SwitchCtrl SwitchCtrl; struct SwitchCtrl { Collection* Nodes; /* CaseNode tree */ TypeCode ExprType; /* Basic switch expression type */ unsigned Depth; /* Number of bytes the selector type has */ unsigned DefaultLabel; /* Label for the default branch */ }; /* Pointer to current switch control struct */ static SwitchCtrl* Switch = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SwitchStatement (void) /* Handle a switch statement for chars with a cmp cascade for the selector */ { ExprDesc SwitchExpr; /* Switch statement expression */ CodeMark CaseCodeStart; /* Start of code marker */ CodeMark SwitchCodeStart;/* Start of switch code */ CodeMark SwitchCodeEnd; /* End of switch code */ unsigned ExitLabel; /* Exit label */ unsigned SwitchCodeLabel;/* Label for the switch code */ int HaveBreak = 0; /* True if the last statement had a break */ int RCurlyBrace; /* True if last token is right curly brace */ SwitchCtrl* OldSwitch; /* Pointer to old switch control data */ SwitchCtrl SwitchData; /* New switch data */ /* Eat the "switch" token */ NextToken (); /* Read the switch expression and load it into the primary. It must have * integer type. */ ConsumeLParen (); Expression0 (&SwitchExpr); if (!IsClassInt (SwitchExpr.Type)) { Error ("Switch quantity is not an integer"); /* To avoid any compiler errors, make the expression a valid int */ ED_MakeConstAbsInt (&SwitchExpr, 1); } ConsumeRParen (); /* Add a jump to the switch code. This jump is usually unnecessary, * because the switch code will moved up just behind the switch * expression. However, in rare cases, there's a label at the end of * the switch expression. This label will not get moved, so the code * jumps around the switch code, and after moving the switch code, * things look really weird. If we add a jump here, we will never have * a label attached to the current code position, and the jump itself * will get removed by the optimizer if it is unnecessary. */ SwitchCodeLabel = GetLocalLabel (); g_jump (SwitchCodeLabel); /* Remember the current code position. We will move the switch code * to this position later. */ GetCodePos (&CaseCodeStart); /* Setup the control structure, save the old and activate the new one */ SwitchData.Nodes = NewCollection (); SwitchData.ExprType = UnqualifiedType (SwitchExpr.Type[0].C); SwitchData.Depth = SizeOf (SwitchExpr.Type); SwitchData.DefaultLabel = 0; OldSwitch = Switch; Switch = &SwitchData; /* Get the exit label for the switch statement */ ExitLabel = GetLocalLabel (); /* Create a loop so we may use break. */ AddLoop (ExitLabel, 0); /* Make sure a curly brace follows */ if (CurTok.Tok != TOK_LCURLY) { Error ("`{' expected"); } /* Parse the following statement, which will actually be a compound * statement because of the curly brace at the current input position */ HaveBreak = Statement (&RCurlyBrace); /* Check if we had any labels */ if (CollCount (SwitchData.Nodes) == 0 && SwitchData.DefaultLabel == 0) { Warning ("No case labels"); } /* If the last statement did not have a break, we may have an open * label (maybe from an if or similar). Emitting code and then moving * this code to the top will also move the label to the top which is * wrong. So if the last statement did not have a break (which would * carry the label), add a jump to the exit. If it is useless, the * optimizer will remove it later. */ if (!HaveBreak) { g_jump (ExitLabel); } /* Remember the current position */ GetCodePos (&SwitchCodeStart); /* Output the switch code label */ g_defcodelabel (SwitchCodeLabel); /* Generate code */ if (SwitchData.DefaultLabel == 0) { /* No default label, use switch exit */ SwitchData.DefaultLabel = ExitLabel; } g_switch (SwitchData.Nodes, SwitchData.DefaultLabel, SwitchData.Depth); /* Move the code to the front */ GetCodePos (&SwitchCodeEnd); MoveCode (&SwitchCodeStart, &SwitchCodeEnd, &CaseCodeStart); /* Define the exit label */ g_defcodelabel (ExitLabel); /* Exit the loop */ DelLoop (); /* Switch back to the enclosing switch statement if any */ Switch = OldSwitch; /* Free the case value tree */ FreeCaseNodeColl (SwitchData.Nodes); /* If the case statement was (correctly) terminated by a closing curly * brace, skip it now. */ if (RCurlyBrace) { NextToken (); } } void CaseLabel (void) /* Handle a case sabel */ { ExprDesc CaseExpr; /* Case label expression */ long Val; /* Case label value */ unsigned CodeLabel; /* Code label for this case */ /* Skip the "case" token */ NextToken (); /* Read the selector expression */ ConstAbsIntExpr (hie1, &CaseExpr); Val = CaseExpr.IVal; /* Now check if we're inside a switch statement */ if (Switch != 0) { /* Check the range of the expression */ switch (Switch->ExprType) { case T_SCHAR: /* Signed char */ if (Val < -128 || Val > 127) { Error ("Range error"); } break; case T_UCHAR: if (Val < 0 || Val > 255) { Error ("Range error"); } break; case T_SHORT: case T_INT: if (Val < -32768 || Val > 32767) { Error ("Range error"); } break; case T_USHORT: case T_UINT: if (Val < 0 || Val > 65535) { Error ("Range error"); } break; case T_LONG: case T_ULONG: break; default: Internal ("Invalid type: %06lX", Switch->ExprType); } /* Insert the case selector into the selector table */ CodeLabel = InsertCaseValue (Switch->Nodes, Val, Switch->Depth); /* Define this label */ g_defcodelabel (CodeLabel); } else { /* case keyword outside a switch statement */ Error ("Case label not within a switch statement"); } /* Skip the colon */ ConsumeColon (); } void DefaultLabel (void) /* Handle a default label */ { /* Default case */ NextToken (); /* Now check if we're inside a switch statement */ if (Switch != 0) { /* Check if we do already have a default branch */ if (Switch->DefaultLabel == 0) { /* Generate and emit the default label */ Switch->DefaultLabel = GetLocalLabel (); g_defcodelabel (Switch->DefaultLabel); } else { /* We had the default label already */ Error ("Multiple default labels in one switch"); } } else { /* case keyword outside a switch statement */ Error ("`default' label not within a switch statement"); } /* Skip the colon */ ConsumeColon (); }
832
./cc65/src/cc65/coptind.c
/*****************************************************************************/ /* */ /* coptind.c */ /* */ /* Environment independent low level optimizations */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "cpu.h" /* cc65 */ #include "codeent.h" #include "coptind.h" #include "codeinfo.h" #include "codeopt.h" #include "error.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static int MemAccess (CodeSeg* S, unsigned From, unsigned To, const CodeEntry* N) /* Checks a range of code entries if there are any memory accesses to N->Arg */ { /* Get the length of the argument */ unsigned NLen = strlen (N->Arg); /* What to check for? */ enum { None = 0x00, Base = 0x01, /* Check for location without "+1" */ Word = 0x02, /* Check for location with "+1" added */ } What = None; /* If the argument of N is a zero page location that ends with "+1", we * must also check for word accesses to the location without +1. */ if (N->AM == AM65_ZP && NLen > 2 && strcmp (N->Arg + NLen - 2, "+1") == 0) { What |= Base; } /* If the argument is zero page indirect, we must also check for accesses * to "arg+1" */ if (N->AM == AM65_ZP_INDY || N->AM == AM65_ZPX_IND || N->AM == AM65_ZP_IND) { What |= Word; } /* Walk over all code entries */ while (From <= To) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, From); /* Check if there is an argument and if this argument equals Arg in * some variants. */ if (E->Arg[0] != '\0') { unsigned ELen; if (strcmp (E->Arg, N->Arg) == 0) { /* Found an access */ return 1; } ELen = strlen (E->Arg); if ((What & Base) != 0) { if (ELen == NLen - 2 && strncmp (E->Arg, N->Arg, NLen-2) == 0) { /* Found an access */ return 1; } } if ((What & Word) != 0) { if (ELen == NLen + 2 && strncmp (E->Arg, N->Arg, NLen) == 0 && E->Arg[NLen] == '+' && E->Arg[NLen+1] == '1') { /* Found an access */ return 1; } } } /* Next entry */ ++From; } /* Nothing found */ return 0; } static int GetBranchDist (CodeSeg* S, unsigned From, CodeEntry* To) /* Get the branch distance between the two entries and return it. The distance * will be negative for backward jumps and positive for forward jumps. */ { /* Get the index of the branch target */ unsigned TI = CS_GetEntryIndex (S, To); /* Determine the branch distance */ int Distance = 0; if (TI >= From) { /* Forward branch, do not count the current insn */ unsigned J = From+1; while (J < TI) { CodeEntry* N = CS_GetEntry (S, J++); Distance += N->Size; } } else { /* Backward branch */ unsigned J = TI; while (J < From) { CodeEntry* N = CS_GetEntry (S, J++); Distance -= N->Size; } } /* Return the calculated distance */ return Distance; } static int IsShortDist (int Distance) /* Return true if the given distance is a short branch distance */ { return (Distance >= -125 && Distance <= 125); } static short ZPRegVal (unsigned short Use, const RegContents* RC) /* Return the contents of the given zeropage register */ { if ((Use & REG_TMP1) != 0) { return RC->Tmp1; } else if ((Use & REG_PTR1_LO) != 0) { return RC->Ptr1Lo; } else if ((Use & REG_PTR1_HI) != 0) { return RC->Ptr1Hi; } else if ((Use & REG_SREG_LO) != 0) { return RC->SRegLo; } else if ((Use & REG_SREG_HI) != 0) { return RC->SRegHi; } else { return UNKNOWN_REGVAL; } } static short RegVal (unsigned short Use, const RegContents* RC) /* Return the contents of the given register */ { if ((Use & REG_A) != 0) { return RC->RegA; } else if ((Use & REG_X) != 0) { return RC->RegX; } else if ((Use & REG_Y) != 0) { return RC->RegY; } else { return ZPRegVal (Use, RC); } } /*****************************************************************************/ /* Replace jumps to RTS by RTS */ /*****************************************************************************/ unsigned OptRTSJumps1 (CodeSeg* S) /* Replace jumps to RTS by RTS */ { unsigned Changes = 0; /* Walk over all entries minus the last one */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's an unconditional branch to a local target */ if ((E->Info & OF_UBRA) != 0 && E->JumpTo != 0 && E->JumpTo->Owner->OPC == OP65_RTS) { /* Insert an RTS instruction */ CodeEntry* X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+1); /* Delete the jump */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptRTSJumps2 (CodeSeg* S) /* Replace long conditional jumps to RTS or to a final target */ { unsigned Changes = 0; /* Walk over all entries minus the last one */ unsigned I = 0; while (I < CS_GetEntryCount (S) - 1) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's an conditional branch to a local target */ if ((E->Info & OF_CBRA) != 0 && /* Conditional branch */ (E->Info & OF_LBRA) != 0 && /* Long branch */ E->JumpTo != 0) { /* Local label */ /* Get the jump target and the next entry. There's always a next * entry, because we don't cover the last entry in the loop. */ CodeEntry* X = 0; CodeEntry* T = E->JumpTo->Owner; CodeEntry* N = CS_GetNextEntry (S, I); /* Check if it's a jump to an RTS insn */ if (T->OPC == OP65_RTS) { /* It's a jump to RTS. Create a conditional branch around an * RTS insn. */ X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, T->LI); } else if (T->OPC == OP65_JMP && T->JumpTo == 0) { /* It's a jump to a label outside the function. Create a * conditional branch around a jump to the external label. */ X = NewCodeEntry (OP65_JMP, AM65_ABS, T->Arg, T->JumpTo, T->LI); } /* If we have a replacement insn, insert it */ if (X) { CodeLabel* LN; opc_t NewBranch; /* Insert the new insn */ CS_InsertEntry (S, X, I+1); /* Create a conditional branch with the inverse condition * around the replacement insn */ /* Get the new branch opcode */ NewBranch = MakeShortBranch (GetInverseBranch (E->OPC)); /* Get the label attached to N, create a new one if needed */ LN = CS_GenLabel (S, N); /* Generate the branch */ X = NewCodeEntry (NewBranch, AM65_BRA, LN->Name, LN, E->LI); CS_InsertEntry (S, X, I+1); /* Delete the long branch */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Remove dead jumps */ /*****************************************************************************/ unsigned OptDeadJumps (CodeSeg* S) /* Remove dead jumps (jumps to the next instruction) */ { unsigned Changes = 0; /* Walk over all entries minus the last one */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a branch, if it has a local target, and if the target * is the next instruction. */ if (E->AM == AM65_BRA && E->JumpTo && E->JumpTo->Owner == CS_GetNextEntry (S, I)) { /* Delete the dead jump */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } else { /* Next entry */ ++I; } } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Remove dead code */ /*****************************************************************************/ unsigned OptDeadCode (CodeSeg* S) /* Remove dead code (code that follows an unconditional jump or an rts/rti * and has no label) */ { unsigned Changes = 0; /* Walk over all entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; CodeLabel* LN; /* Get this entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's an unconditional branch, and if the next entry has * no labels attached, or if the label is just used so that the insn * can jump to itself. */ if ((E->Info & OF_DEAD) != 0 && /* Dead code follows */ (N = CS_GetNextEntry (S, I)) != 0 && /* Has next entry */ (!CE_HasLabel (N) || /* Don't has a label */ ((N->Info & OF_UBRA) != 0 && /* Uncond branch */ (LN = N->JumpTo) != 0 && /* Jumps to known label */ LN->Owner == N && /* Attached to insn */ CL_GetRefCount (LN) == 1))) { /* Only reference */ /* Delete the next entry */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } else { /* Next entry */ ++I; } } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize jump cascades */ /*****************************************************************************/ unsigned OptJumpCascades (CodeSeg* S) /* Optimize jump cascades (jumps to jumps). In such a case, the jump is * replaced by a jump to the final location. This will in some cases produce * worse code, because some jump targets are no longer reachable by short * branches, but this is quite rare, so there are more advantages than * disadvantages. */ { unsigned Changes = 0; /* Walk over all entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; CodeLabel* OldLabel; /* Get this entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check: * - if it's a branch, * - if it has a jump label, * - if this jump label is not attached to the instruction itself, * - if the target instruction is itself a branch, * - if either the first branch is unconditional or the target of * the second branch is internal to the function. * The latter condition will avoid conditional branches to targets * outside of the function (usually incspx), which won't simplify the * code, since conditional far branches are emulated by a short branch * around a jump. */ if ((E->Info & OF_BRA) != 0 && (OldLabel = E->JumpTo) != 0 && (N = OldLabel->Owner) != E && (N->Info & OF_BRA) != 0 && ((E->Info & OF_CBRA) == 0 || N->JumpTo != 0)) { /* Check if we can use the final target label. This is the case, * if the target branch is an absolut branch, or if it is a * conditional branch checking the same condition as the first one. */ if ((N->Info & OF_UBRA) != 0 || ((E->Info & OF_CBRA) != 0 && GetBranchCond (E->OPC) == GetBranchCond (N->OPC))) { /* This is a jump cascade and we may jump to the final target, * provided that the other insn does not jump to itself. If * this is the case, we can also jump to ourselves, otherwise * insert a jump to the new instruction and remove the old one. */ CodeEntry* X; CodeLabel* LN = N->JumpTo; if (LN != 0 && LN->Owner == N) { /* We found a jump to a jump to itself. Replace our jump * by a jump to itself. */ CodeLabel* LE = CS_GenLabel (S, E); X = NewCodeEntry (E->OPC, E->AM, LE->Name, LE, E->LI); } else { /* Jump to the final jump target */ X = NewCodeEntry (E->OPC, E->AM, N->Arg, N->JumpTo, E->LI); } /* Insert it behind E */ CS_InsertEntry (S, X, I+1); /* Remove E */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; /* Check if both are conditional branches, and the condition of * the second is the inverse of that of the first. In this case, * the second branch will never be taken, and we may jump directly * to the instruction behind this one. */ } else if ((E->Info & OF_CBRA) != 0 && (N->Info & OF_CBRA) != 0) { CodeEntry* X; /* Instruction behind N */ CodeLabel* LX; /* Label attached to X */ /* Get the branch conditions of both branches */ bc_t BC1 = GetBranchCond (E->OPC); bc_t BC2 = GetBranchCond (N->OPC); /* Check the branch conditions */ if (BC1 != GetInverseCond (BC2)) { /* Condition not met */ goto NextEntry; } /* We may jump behind this conditional branch. Get the * pointer to the next instruction */ if ((X = CS_GetNextEntry (S, CS_GetEntryIndex (S, N))) == 0) { /* N is the last entry, bail out */ goto NextEntry; } /* Get the label attached to X, create a new one if needed */ LX = CS_GenLabel (S, X); /* Move the reference from E to the new label */ CS_MoveLabelRef (S, E, LX); /* Remember, we had changes */ ++Changes; } } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize jsr/rts */ /*****************************************************************************/ unsigned OptRTS (CodeSeg* S) /* Optimize subroutine calls followed by an RTS. The subroutine call will get * replaced by a jump. Don't bother to delete the RTS if it does not have a * label, the dead code elimination should take care of it. */ { unsigned Changes = 0; /* Walk over all entries minus the last one */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get this entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a subroutine call and if the following insn is RTS */ if (E->OPC == OP65_JSR && (N = CS_GetNextEntry (S, I)) != 0 && N->OPC == OP65_RTS) { /* Change the jsr to a jmp and use the additional info for a jump */ E->AM = AM65_BRA; CE_ReplaceOPC (E, OP65_JMP); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize jump targets */ /*****************************************************************************/ unsigned OptJumpTarget1 (CodeSeg* S) /* If the instruction preceeding an unconditional branch is the same as the * instruction preceeding the jump target, the jump target may be moved * one entry back. This is a size optimization, since the instruction before * the branch gets removed. */ { unsigned Changes = 0; CodeEntry* E1; /* Entry 1 */ CodeEntry* E2; /* Entry 2 */ CodeEntry* T1; /* Jump target entry 1 */ CodeLabel* TL1; /* Target label 1 */ /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ E2 = CS_GetNextEntry (S, I); /* Check if we have a jump or branch without a label attached, and * a jump target, which is not attached to the jump itself */ if (E2 != 0 && (E2->Info & OF_UBRA) != 0 && !CE_HasLabel (E2) && E2->JumpTo && E2->JumpTo->Owner != E2) { /* Get the entry preceeding the branch target */ T1 = CS_GetPrevEntry (S, CS_GetEntryIndex (S, E2->JumpTo->Owner)); if (T1 == 0) { /* There is no such entry */ goto NextEntry; } /* The entry preceeding the branch target may not be the branch * insn. */ if (T1 == E2) { goto NextEntry; } /* Get the entry preceeding the jump */ E1 = CS_GetEntry (S, I); /* Check if both preceeding instructions are identical */ if (!CodeEntriesAreEqual (E1, T1)) { /* Not equal, try next */ goto NextEntry; } /* Get the label for the instruction preceeding the jump target. * This routine will create a new label if the instruction does * not already have one. */ TL1 = CS_GenLabel (S, T1); /* Change the jump target to point to this new label */ CS_MoveLabelRef (S, E2, TL1); /* If the instruction preceeding the jump has labels attached, * move references to this label to the new label. */ if (CE_HasLabel (E1)) { CS_MoveLabels (S, E1, T1); } /* Remove the entry preceeding the jump */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } else { NextEntry: /* Next entry */ ++I; } } /* Return the number of changes made */ return Changes; } unsigned OptJumpTarget2 (CodeSeg* S) /* If a bcs jumps to a sec insn or a bcc jumps to clc, skip this insn, since * it's job is already done. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* OP that may be skipped */ opc_t OPC; /* Jump target insn, old and new */ CodeEntry* T; CodeEntry* N; /* New jump label */ CodeLabel* L; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a bcc insn */ if (E->OPC == OP65_BCC || E->OPC == OP65_JCC) { OPC = OP65_CLC; } else if (E->OPC == OP65_BCS || E->OPC == OP65_JCS) { OPC = OP65_SEC; } else { /* Not what we're looking for */ goto NextEntry; } /* Must have a jump target */ if (E->JumpTo == 0) { goto NextEntry; } /* Get the owner insn of the jump target and check if it's the one, we * will skip if present. */ T = E->JumpTo->Owner; if (T->OPC != OPC) { goto NextEntry; } /* Get the entry following the branch target */ N = CS_GetNextEntry (S, CS_GetEntryIndex (S, T)); if (N == 0) { /* There is no such entry */ goto NextEntry; } /* Get the label for the instruction following the jump target. * This routine will create a new label if the instruction does * not already have one. */ L = CS_GenLabel (S, N); /* Change the jump target to point to this new label */ CS_MoveLabelRef (S, E, L); /* Remember that we had changes */ ++Changes; NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptJumpTarget3 (CodeSeg* S) /* Jumps to load instructions of a register, that do already have the matching * register contents may skip the load instruction, since it's job is already * done. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a load insn with a label and the next insn is not * a conditional branch that needs the flags from the load. */ if ((E->Info & OF_LOAD) != 0 && CE_IsConstImm (E) && CE_HasLabel (E) && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { unsigned J; int K; /* New jump label */ CodeLabel* LN = 0; /* Walk over all insn that jump here */ for (J = 0; J < CE_GetLabelCount (E); ++J) { /* Get the label */ CodeLabel* L = CE_GetLabel (E, J); /* Loop over all insn that reference this label. Since we may * eventually remove a reference in the loop, we must loop * from end down to start. */ for (K = CL_GetRefCount (L) - 1; K >= 0; --K) { /* Get the entry that jumps here */ CodeEntry* Jump = CL_GetRef (L, K); /* Get the register info from this insn */ short Val = RegVal (E->Chg, &Jump->RI->Out2); /* Check if the outgoing value is the one thats's loaded */ if (Val == (unsigned char) E->Num) { /* Ok, skip the insn. First, generate a label for the * next insn after E. */ if (LN == 0) { LN = CS_GenLabel (S, N); } /* Change the jump target to point to this new label */ CS_MoveLabelRef (S, Jump, LN); /* Remember that we had changes */ ++Changes; } } } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize conditional branches */ /*****************************************************************************/ unsigned OptCondBranches1 (CodeSeg* S) /* Performs several optimization steps: * * - If an immidiate load of a register is followed by a conditional jump that * is never taken because the load of the register sets the flags in such a * manner, remove the conditional branch. * - If the conditional branch is always taken because of the register load, * replace it by a jmp. * - If a conditional branch jumps around an unconditional branch, remove the * conditional branch and make the jump a conditional branch with the * inverse condition of the first one. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; CodeLabel* L; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a register load */ if ((E->Info & OF_LOAD) != 0 && /* It's a load instruction */ E->AM == AM65_IMM && /* ..with immidiate addressing */ (E->Flags & CEF_NUMARG) != 0 && /* ..and a numeric argument. */ (N = CS_GetNextEntry (S, I)) != 0 && /* There is a following entry */ (N->Info & OF_CBRA) != 0 && /* ..which is a conditional branch */ !CE_HasLabel (N)) { /* ..and does not have a label */ /* Get the branch condition */ bc_t BC = GetBranchCond (N->OPC); /* Check the argument against the branch condition */ if ((BC == BC_EQ && E->Num != 0) || (BC == BC_NE && E->Num == 0) || (BC == BC_PL && (E->Num & 0x80) != 0) || (BC == BC_MI && (E->Num & 0x80) == 0)) { /* Remove the conditional branch */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } else if ((BC == BC_EQ && E->Num == 0) || (BC == BC_NE && E->Num != 0) || (BC == BC_PL && (E->Num & 0x80) == 0) || (BC == BC_MI && (E->Num & 0x80) != 0)) { /* The branch is always taken, replace it by a jump */ CE_ReplaceOPC (N, OP65_JMP); /* Remember, we had changes */ ++Changes; } } if ((E->Info & OF_CBRA) != 0 && /* It's a conditional branch */ (L = E->JumpTo) != 0 && /* ..referencing a local label */ (N = CS_GetNextEntry (S, I)) != 0 && /* There is a following entry */ (N->Info & OF_UBRA) != 0 && /* ..which is an uncond branch, */ !CE_HasLabel (N) && /* ..has no label attached */ L->Owner == CS_GetNextEntry (S, I+1)) {/* ..and jump target follows */ /* Replace the jump by a conditional branch with the inverse branch * condition than the branch around it. */ CE_ReplaceOPC (N, GetInverseBranch (E->OPC)); /* Remove the conditional branch */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCondBranches2 (CodeSeg* S) /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows, * we can remove the rol and branch on the state of the carry flag. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a rol insn with A in accu and a branch follows */ if (E->OPC == OP65_ROL && E->AM == AM65_ACC && E->RI->In.RegA == 0 && !CE_HasLabel (E) && (N = CS_GetNextEntry (S, I)) != 0 && (N->Info & OF_ZBRA) != 0 && !RegAUsed (S, I+1)) { /* Replace the branch condition */ switch (GetBranchCond (N->OPC)) { case BC_EQ: CE_ReplaceOPC (N, OP65_JCC); break; case BC_NE: CE_ReplaceOPC (N, OP65_JCS); break; default: Internal ("Unknown branch condition in OptCondBranches2"); } /* Delete the rol insn */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Remove unused loads and stores */ /*****************************************************************************/ unsigned OptUnusedLoads (CodeSeg* S) /* Remove loads of registers where the value loaded is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a register load or transfer insn */ if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0 && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { /* Check which sort of load or transfer it is */ unsigned R; switch (E->OPC) { case OP65_DEA: case OP65_INA: case OP65_LDA: case OP65_TXA: case OP65_TYA: R = REG_A; break; case OP65_DEX: case OP65_INX: case OP65_LDX: case OP65_TAX: R = REG_X; break; case OP65_DEY: case OP65_INY: case OP65_LDY: case OP65_TAY: R = REG_Y; break; default: goto NextEntry; /* OOPS */ } /* Get register usage and check if the register value is used later */ if ((GetRegInfo (S, I+1, R) & R) == 0) { /* Register value is not used, remove the load */ CS_DelEntry (S, I); /* Remember, we had changes. Account the deleted entry in I. */ ++Changes; --I; } } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptUnusedStores (CodeSeg* S) /* Remove stores into zero page registers that aren't used later */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a register load or transfer insn */ if ((E->Info & OF_STORE) != 0 && E->AM == AM65_ZP && (E->Chg & REG_ZP) != 0) { /* Check for the zero page location. We know that there cannot be * more than one zero page location involved in the store. */ unsigned R = E->Chg & REG_ZP; /* Get register usage and check if the register value is used later */ if ((GetRegInfo (S, I+1, R) & R) == 0) { /* Register value is not used, remove the load */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; /* Continue with next insn */ continue; } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptDupLoads (CodeSeg* S) /* Remove loads of registers where the value loaded is already in the register. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Assume we won't delete the entry */ int Delete = 0; /* Get a pointer to the input registers of the insn */ const RegContents* In = &E->RI->In; /* Handle the different instructions */ switch (E->OPC) { case OP65_LDA: if (RegValIsKnown (In->RegA) && /* Value of A is known */ CE_IsKnownImm (E, In->RegA) && /* Value to be loaded is known */ (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */ !CE_UseLoadFlags (N)) { /* Which does not use the flags */ Delete = 1; } break; case OP65_LDX: if (RegValIsKnown (In->RegX) && /* Value of X is known */ CE_IsKnownImm (E, In->RegX) && /* Value to be loaded is known */ (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */ !CE_UseLoadFlags (N)) { /* Which does not use the flags */ Delete = 1; } break; case OP65_LDY: if (RegValIsKnown (In->RegY) && /* Value of Y is known */ CE_IsKnownImm (E, In->RegY) && /* Value to be loaded is known */ (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */ !CE_UseLoadFlags (N)) { /* Which does not use the flags */ Delete = 1; } break; case OP65_STA: /* If we store into a known zero page location, and this * location does already contain the value to be stored, * remove the store. */ if (RegValIsKnown (In->RegA) && /* Value of A is known */ E->AM == AM65_ZP && /* Store into zp */ In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */ Delete = 1; } break; case OP65_STX: /* If we store into a known zero page location, and this * location does already contain the value to be stored, * remove the store. */ if (RegValIsKnown (In->RegX) && /* Value of A is known */ E->AM == AM65_ZP && /* Store into zp */ In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */ Delete = 1; /* If the value in the X register is known and the same as * that in the A register, replace the store by a STA. The * optimizer will then remove the load instruction for X * later. STX does support the zeropage,y addressing mode, * so be sure to check for that. */ } else if (RegValIsKnown (In->RegX) && In->RegX == In->RegA && E->AM != AM65_ABSY && E->AM != AM65_ZPY) { /* Use the A register instead */ CE_ReplaceOPC (E, OP65_STA); } break; case OP65_STY: /* If we store into a known zero page location, and this * location does already contain the value to be stored, * remove the store. */ if (RegValIsKnown (In->RegY) && /* Value of Y is known */ E->AM == AM65_ZP && /* Store into zp */ In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */ Delete = 1; /* If the value in the Y register is known and the same as * that in the A register, replace the store by a STA. The * optimizer will then remove the load instruction for Y * later. If replacement by A is not possible try a * replacement by X, but check for invalid addressing modes * in this case. */ } else if (RegValIsKnown (In->RegY)) { if (In->RegY == In->RegA) { CE_ReplaceOPC (E, OP65_STA); } else if (In->RegY == In->RegX && E->AM != AM65_ABSX && E->AM != AM65_ZPX) { CE_ReplaceOPC (E, OP65_STX); } } break; case OP65_STZ: /* If we store into a known zero page location, and this * location does already contain the value to be stored, * remove the store. */ if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) { if (ZPRegVal (E->Chg, In) == 0) { Delete = 1; } } break; case OP65_TAX: if (RegValIsKnown (In->RegA) && In->RegA == In->RegX && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { /* Value is identical and not followed by a branch */ Delete = 1; } break; case OP65_TAY: if (RegValIsKnown (In->RegA) && In->RegA == In->RegY && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { /* Value is identical and not followed by a branch */ Delete = 1; } break; case OP65_TXA: if (RegValIsKnown (In->RegX) && In->RegX == In->RegA && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { /* Value is identical and not followed by a branch */ Delete = 1; } break; case OP65_TYA: if (RegValIsKnown (In->RegY) && In->RegY == In->RegA && (N = CS_GetNextEntry (S, I)) != 0 && !CE_UseLoadFlags (N)) { /* Value is identical and not followed by a branch */ Delete = 1; } break; default: break; } /* Delete the entry if requested */ if (Delete) { /* Register value is not used, remove the load */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } else { /* Next entry */ ++I; } } /* Return the number of changes made */ return Changes; } unsigned OptStoreLoad (CodeSeg* S) /* Remove a store followed by a load from the same location. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; CodeEntry* X; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it is a store instruction followed by a load from the * same address which is itself not followed by a conditional branch. */ if ((E->Info & OF_STORE) != 0 && (N = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (N) && E->AM == N->AM && ((E->OPC == OP65_STA && N->OPC == OP65_LDA) || (E->OPC == OP65_STX && N->OPC == OP65_LDX) || (E->OPC == OP65_STY && N->OPC == OP65_LDY)) && strcmp (E->Arg, N->Arg) == 0 && (X = CS_GetNextEntry (S, I+1)) != 0 && !CE_UseLoadFlags (X)) { /* Register has already the correct value, remove the load */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptTransfers1 (CodeSeg* S) /* Remove transfers from one register to another and back */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; CodeEntry* X; CodeEntry* P; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if we have two transfer instructions */ if ((E->Info & OF_XFR) != 0 && (N = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (N) && (N->Info & OF_XFR) != 0) { /* Check if it's a transfer and back */ if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) || (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) || (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) || (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) { /* If the next insn is a conditional branch, check if the insn * preceeding the first xfr will set the flags right, otherwise we * may not remove the sequence. */ if ((X = CS_GetNextEntry (S, I+1)) == 0) { goto NextEntry; } if (CE_UseLoadFlags (X)) { if (I == 0) { /* No preceeding entry */ goto NextEntry; } P = CS_GetEntry (S, I-1); if ((P->Info & OF_SETF) == 0) { /* Does not set the flags */ goto NextEntry; } } /* Remove both transfers */ CS_DelEntry (S, I+1); CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptTransfers2 (CodeSeg* S) /* Replace loads followed by a register transfer by a load with the second * register if possible. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if we have a load followed by a transfer where the loaded * register is not used later. */ if ((E->Info & OF_LOAD) != 0 && (N = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (N) && (N->Info & OF_XFR) != 0 && GetRegInfo (S, I+2, E->Chg) != E->Chg) { CodeEntry* X = 0; if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) { /* LDA/TAX - check for the right addressing modes */ if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS || E->AM == AM65_ABSY) { /* Replace */ X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI); } } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) { /* LDA/TAY - check for the right addressing modes */ if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ZPX || E->AM == AM65_ABS || E->AM == AM65_ABSX) { /* Replace */ X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI); } } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) { /* LDY/TYA. LDA supports all addressing modes LDY does */ X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI); } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) { /* LDX/TXA. LDA doesn't support zp,y, so we must map it to * abs,y instead. */ am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM; X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI); } /* If we have a load entry, add it and remove the old stuff */ if (X) { CS_InsertEntry (S, X, I+2); CS_DelEntries (S, I, 2); ++Changes; --I; /* Correct for one entry less */ } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptTransfers3 (CodeSeg* S) /* Replace a register transfer followed by a store of the second register by a * store of the first register if this is possible. */ { unsigned Changes = 0; unsigned UsedRegs = REG_NONE; /* Track used registers */ unsigned Xfer = 0; /* Index of transfer insn */ unsigned Store = 0; /* Index of store insn */ CodeEntry* XferEntry = 0; /* Pointer to xfer insn */ CodeEntry* StoreEntry = 0; /* Pointer to store insn */ enum { Initialize, Search, FoundXfer, FoundStore } State = Initialize; /* Walk over the entries. Look for a xfer instruction that is followed by * a store later, where the value of the register is not used later. */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); switch (State) { case Initialize: /* Clear the list of used registers */ UsedRegs = REG_NONE; /* FALLTHROUGH */ case Search: if (E->Info & OF_XFR) { /* Found start of sequence */ Xfer = I; XferEntry = E; State = FoundXfer; } break; case FoundXfer: /* If we find a conditional jump, abort the sequence, since * handling them makes things really complicated. */ if (E->Info & OF_CBRA) { /* Switch back to searching */ I = Xfer; State = Initialize; /* Does this insn use the target register of the transfer? */ } else if ((E->Use & XferEntry->Chg) != 0) { /* It it's a store instruction, and the block is a basic * block, proceed. Otherwise restart */ if ((E->Info & OF_STORE) != 0 && CS_IsBasicBlock (S, Xfer, I)) { Store = I; StoreEntry = E; State = FoundStore; } else { I = Xfer; State = Initialize; } /* Does this insn change the target register of the transfer? */ } else if (E->Chg & XferEntry->Chg) { /* We *may* add code here to remove the transfer, but I'm * currently not sure about the consequences, so I won't * do that and bail out instead. */ I = Xfer; State = Initialize; /* Does this insn have a label? */ } else if (CE_HasLabel (E)) { /* Too complex to handle - bail out */ I = Xfer; State = Initialize; } else { /* Track used registers */ UsedRegs |= E->Use; } break; case FoundStore: /* We are at the instruction behind the store. If the register * isn't used later, and we have an address mode match, we can * replace the transfer by a store and remove the store here. */ if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0 && (StoreEntry->AM == AM65_ABS || StoreEntry->AM == AM65_ZP) && (StoreEntry->AM != AM65_ZP || (StoreEntry->Chg & UsedRegs) == 0) && !MemAccess (S, Xfer+1, Store-1, StoreEntry)) { /* Generate the replacement store insn */ CodeEntry* X = 0; switch (XferEntry->OPC) { case OP65_TXA: X = NewCodeEntry (OP65_STX, StoreEntry->AM, StoreEntry->Arg, 0, StoreEntry->LI); break; case OP65_TAX: X = NewCodeEntry (OP65_STA, StoreEntry->AM, StoreEntry->Arg, 0, StoreEntry->LI); break; case OP65_TYA: X = NewCodeEntry (OP65_STY, StoreEntry->AM, StoreEntry->Arg, 0, StoreEntry->LI); break; case OP65_TAY: X = NewCodeEntry (OP65_STA, StoreEntry->AM, StoreEntry->Arg, 0, StoreEntry->LI); break; default: break; } /* If we have a replacement store, change the code */ if (X) { /* Insert after the xfer insn */ CS_InsertEntry (S, X, Xfer+1); /* Remove the xfer instead */ CS_DelEntry (S, Xfer); /* Remove the final store */ CS_DelEntry (S, Store); /* Correct I so we continue with the next insn */ I -= 2; /* Remember we had changes */ ++Changes; } else { /* Restart after last xfer insn */ I = Xfer; } } else { /* Restart after last xfer insn */ I = Xfer; } State = Initialize; break; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptTransfers4 (CodeSeg* S) /* Replace a load of a register followed by a transfer insn of the same register * by a load of the second register if possible. */ { unsigned Changes = 0; unsigned Load = 0; /* Index of load insn */ unsigned Xfer = 0; /* Index of transfer insn */ CodeEntry* LoadEntry = 0; /* Pointer to load insn */ CodeEntry* XferEntry = 0; /* Pointer to xfer insn */ enum { Search, FoundLoad, FoundXfer } State = Search; /* Walk over the entries. Look for a load instruction that is followed by * a load later. */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); switch (State) { case Search: if (E->Info & OF_LOAD) { /* Found start of sequence */ Load = I; LoadEntry = E; State = FoundLoad; } break; case FoundLoad: /* If we find a conditional jump, abort the sequence, since * handling them makes things really complicated. */ if (E->Info & OF_CBRA) { /* Switch back to searching */ I = Load; State = Search; /* Does this insn use the target register of the load? */ } else if ((E->Use & LoadEntry->Chg) != 0) { /* It it's a xfer instruction, and the block is a basic * block, proceed. Otherwise restart */ if ((E->Info & OF_XFR) != 0 && CS_IsBasicBlock (S, Load, I)) { Xfer = I; XferEntry = E; State = FoundXfer; } else { I = Load; State = Search; } /* Does this insn change the target register of the load? */ } else if (E->Chg & LoadEntry->Chg) { /* We *may* add code here to remove the load, but I'm * currently not sure about the consequences, so I won't * do that and bail out instead. */ I = Load; State = Search; } break; case FoundXfer: /* We are at the instruction behind the xfer. If the register * isn't used later, and we have an address mode match, we can * replace the transfer by a load and remove the initial load. */ if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0 && (LoadEntry->AM == AM65_ABS || LoadEntry->AM == AM65_ZP || LoadEntry->AM == AM65_IMM) && !MemAccess (S, Load+1, Xfer-1, LoadEntry)) { /* Generate the replacement load insn */ CodeEntry* X = 0; switch (XferEntry->OPC) { case OP65_TXA: case OP65_TYA: X = NewCodeEntry (OP65_LDA, LoadEntry->AM, LoadEntry->Arg, 0, LoadEntry->LI); break; case OP65_TAX: X = NewCodeEntry (OP65_LDX, LoadEntry->AM, LoadEntry->Arg, 0, LoadEntry->LI); break; case OP65_TAY: X = NewCodeEntry (OP65_LDY, LoadEntry->AM, LoadEntry->Arg, 0, LoadEntry->LI); break; default: break; } /* If we have a replacement load, change the code */ if (X) { /* Insert after the xfer insn */ CS_InsertEntry (S, X, Xfer+1); /* Remove the xfer instead */ CS_DelEntry (S, Xfer); /* Remove the initial load */ CS_DelEntry (S, Load); /* Correct I so we continue with the next insn */ I -= 2; /* Remember we had changes */ ++Changes; } else { /* Restart after last xfer insn */ I = Xfer; } } else { /* Restart after last xfer insn */ I = Xfer; } State = Search; break; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPushPop (CodeSeg* S) /* Remove a PHA/PLA sequence were A is not used later */ { unsigned Changes = 0; unsigned Push = 0; /* Index of push insn */ unsigned Pop = 0; /* Index of pop insn */ unsigned ChgA = 0; /* Flag for A changed */ enum { Searching, FoundPush, FoundPop } State = Searching; /* Walk over the entries. Look for a push instruction that is followed by * a pop later, where the pop is not followed by an conditional branch, * and where the value of the A register is not used later on. * Look out for the following problems: * * - There may be another PHA/PLA inside the sequence: Restart it. * - If the PLA has a label, all jumps to this label must be inside * the sequence, otherwise we cannot remove the PHA/PLA. */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* X; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); switch (State) { case Searching: if (E->OPC == OP65_PHA) { /* Found start of sequence */ Push = I; ChgA = 0; State = FoundPush; } break; case FoundPush: if (E->OPC == OP65_PHA) { /* Inner push/pop, restart */ Push = I; ChgA = 0; } else if (E->OPC == OP65_PLA) { /* Found a matching pop */ Pop = I; /* Check that the block between Push and Pop is a basic * block (one entry, one exit). Otherwise ignore it. */ if (CS_IsBasicBlock (S, Push, Pop)) { State = FoundPop; } else { /* Go into searching mode again */ State = Searching; } } else if (E->Chg & REG_A) { ChgA = 1; } break; case FoundPop: /* We're at the instruction after the PLA. * Check for the following conditions: * - If this instruction is a store of A that doesn't use * another register, if the instruction does not have a * label, and A is not used later, we may replace the PHA * by the store and remove pla if several other conditions * are met. * - If this instruction is not a conditional branch, and A * is either unused later, or not changed by the code * between push and pop, we may remove PHA and PLA. */ if (E->OPC == OP65_STA && (E->AM == AM65_ABS || E->AM == AM65_ZP) && !CE_HasLabel (E) && !RegAUsed (S, I+1) && !MemAccess (S, Push+1, Pop-1, E)) { /* Insert a STA after the PHA */ X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI); CS_InsertEntry (S, X, Push+1); /* Remove the PHA instead */ CS_DelEntry (S, Push); /* Remove the PLA/STA sequence */ CS_DelEntries (S, Pop, 2); /* Correct I so we continue with the next insn */ I -= 2; /* Remember we had changes */ ++Changes; } else if ((E->Info & OF_CBRA) == 0 && (!RegAUsed (S, I) || !ChgA)) { /* We can remove the PHA and PLA instructions */ CS_DelEntry (S, Pop); CS_DelEntry (S, Push); /* Correct I so we continue with the next insn */ I -= 2; /* Remember we had changes */ ++Changes; } /* Go into search mode again */ State = Searching; break; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPrecalc (CodeSeg* S) /* Replace immediate operations with the accu where the current contents are * known by a load of the final value. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Get pointers to the input and output registers of the insn */ const RegContents* Out = &E->RI->Out; const RegContents* In = &E->RI->In; /* Argument for LDn and flag */ const char* Arg = 0; opc_t OPC = OP65_LDA; /* Handle the different instructions */ switch (E->OPC) { case OP65_LDA: if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) { /* Result of load is known */ Arg = MakeHexArg (Out->RegA); } break; case OP65_LDX: if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) { /* Result of load is known but register is X */ Arg = MakeHexArg (Out->RegX); OPC = OP65_LDX; } break; case OP65_LDY: if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) { /* Result of load is known but register is Y */ Arg = MakeHexArg (Out->RegY); OPC = OP65_LDY; } break; case OP65_EOR: if (RegValIsKnown (Out->RegA)) { /* Accu op zp with known contents */ Arg = MakeHexArg (Out->RegA); } break; case OP65_ADC: case OP65_SBC: /* If this is an operation with an immediate operand of zero, * and the register is zero, the operation won't give us any * results we don't already have (including the flags), so * remove it. Something like this is generated as a result of * a compare where parts of the values are known to be zero. */ if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) { /* 0-0 or 0+0 -> remove */ CS_DelEntry (S, I); ++Changes; } break; case OP65_AND: if (CE_IsKnownImm (E, 0xFF)) { /* AND with 0xFF, remove */ CS_DelEntry (S, I); ++Changes; } else if (CE_IsKnownImm (E, 0x00)) { /* AND with 0x00, replace by lda #$00 */ Arg = MakeHexArg (0x00); } else if (RegValIsKnown (Out->RegA)) { /* Accu AND zp with known contents */ Arg = MakeHexArg (Out->RegA); } else if (In->RegA == 0xFF) { /* AND but A contains 0xFF - replace by lda */ CE_ReplaceOPC (E, OP65_LDA); ++Changes; } break; case OP65_ORA: if (CE_IsKnownImm (E, 0x00)) { /* ORA with zero, remove */ CS_DelEntry (S, I); ++Changes; } else if (CE_IsKnownImm (E, 0xFF)) { /* ORA with 0xFF, replace by lda #$ff */ Arg = MakeHexArg (0xFF); } else if (RegValIsKnown (Out->RegA)) { /* Accu AND zp with known contents */ Arg = MakeHexArg (Out->RegA); } else if (In->RegA == 0) { /* ORA but A contains 0x00 - replace by lda */ CE_ReplaceOPC (E, OP65_LDA); ++Changes; } break; default: break; } /* Check if we have to replace the insn by LDA */ if (Arg) { CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize branch types */ /*****************************************************************************/ unsigned OptBranchDist (CodeSeg* S) /* Change branches for the distance needed. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's a conditional branch to a local label. */ if (E->Info & OF_CBRA) { /* Is this a branch to a local symbol? */ if (E->JumpTo != 0) { /* Check if the branch distance is short */ int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner)); /* Make the branch short/long according to distance */ if ((E->Info & OF_LBRA) == 0 && !IsShort) { /* Short branch but long distance */ CE_ReplaceOPC (E, MakeLongBranch (E->OPC)); ++Changes; } else if ((E->Info & OF_LBRA) != 0 && IsShort) { /* Long branch but short distance */ CE_ReplaceOPC (E, MakeShortBranch (E->OPC)); ++Changes; } } else if ((E->Info & OF_LBRA) == 0) { /* Short branch to external symbol - make it long */ CE_ReplaceOPC (E, MakeLongBranch (E->OPC)); ++Changes; } } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && (E->Info & OF_UBRA) != 0 && E->JumpTo != 0 && IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) { /* The jump is short and may be replaced by a BRA on the 65C02 CPU */ CE_ReplaceOPC (E, OP65_BRA); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize indirect loads */ /*****************************************************************************/ unsigned OptIndLoads1 (CodeSeg* S) /* Change * * lda (zp),y * * into * * lda (zp,x) * * provided that x and y are both zero. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's what we're looking for */ if (E->OPC == OP65_LDA && E->AM == AM65_ZP_INDY && E->RI->In.RegY == 0 && E->RI->In.RegX == 0) { /* Replace by the same insn with other addressing mode */ CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZPX_IND, E->Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); /* Remove the old insn */ CS_DelEntry (S, I); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptIndLoads2 (CodeSeg* S) /* Change * * lda (zp,x) * * into * * lda (zp),y * * provided that x and y are both zero. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if it's what we're looking for */ if (E->OPC == OP65_LDA && E->AM == AM65_ZPX_IND && E->RI->In.RegY == 0 && E->RI->In.RegX == 0) { /* Replace by the same insn with other addressing mode */ CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_INDY, E->Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); /* Remove the old insn */ CS_DelEntry (S, I); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
833
./cc65/src/cc65/coptsub.c
/*****************************************************************************/ /* */ /* coptsub.c */ /* */ /* Optimize subtraction sequences */ /* */ /* */ /* */ /* (C) 2001-2006, Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptsub.h" /*****************************************************************************/ /* Optimize subtractions */ /*****************************************************************************/ unsigned OptSub1 (CodeSeg* S) /* Search for the sequence * * sbc ... * bcs L * dex * L: * * and remove the handling of the high byte if X is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_SBC && CS_GetEntries (S, L, I+1, 3) && (L[0]->OPC == OP65_BCS || L[0]->OPC == OP65_JCS) && L[0]->JumpTo != 0 && !CE_HasLabel (L[0]) && L[1]->OPC == OP65_DEX && !CE_HasLabel (L[1]) && L[0]->JumpTo->Owner == L[2] && !RegXUsed (S, I+3)) { /* Remove the bcs/dex */ CS_DelEntries (S, I+1, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptSub2 (CodeSeg* S) /* Search for the sequence * * lda xx * sec * sta tmp1 * lda yy * sbc tmp1 * sta yy * * and replace it by * * sec * lda yy * sbc xx * sta yy */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_LDA && !CS_RangeHasLabel (S, I+1, 5) && CS_GetEntries (S, L, I+1, 5) && L[0]->OPC == OP65_SEC && L[1]->OPC == OP65_STA && strcmp (L[1]->Arg, "tmp1") == 0 && L[2]->OPC == OP65_LDA && L[3]->OPC == OP65_SBC && strcmp (L[3]->Arg, "tmp1") == 0 && L[4]->OPC == OP65_STA && strcmp (L[4]->Arg, L[2]->Arg) == 0) { /* Remove the store to tmp1 */ CS_DelEntry (S, I+2); /* Remove the subtraction */ CS_DelEntry (S, I+3); /* Move the lda to the position of the subtraction and change the * op to SBC. */ CS_MoveEntry (S, I, I+3); CE_ReplaceOPC (E, OP65_SBC); /* If the sequence head had a label, move this label back to the * head. */ if (CE_HasLabel (E)) { CS_MoveLabels (S, E, L[0]); } /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptSub3 (CodeSeg* S) /* Search for a call to decaxn and replace it by an 8 bit sub if the X register * is not used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* E; /* Get next entry */ E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && strncmp (E->Arg, "decax", 5) == 0 && IsDigit (E->Arg[5]) && E->Arg[6] == '\0' && !RegXUsed (S, I+1)) { CodeEntry* X; const char* Arg; /* Insert new code behind the sequence */ X = NewCodeEntry (OP65_SEC, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+1); Arg = MakeHexArg (E->Arg[5] - '0'); X = NewCodeEntry (OP65_SBC, AM65_IMM, Arg, 0, E->LI); CS_InsertEntry (S, X, I+2); /* Delete the old code */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
834
./cc65/src/cc65/loadexpr.c
/*****************************************************************************/ /* */ /* loadexpr.c */ /* */ /* Load an expression into the primary register */ /* */ /* */ /* */ /* (C) 2004-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codegen.h" #include "error.h" #include "exprdesc.h" #include "global.h" #include "loadexpr.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void LoadConstant (unsigned Flags, ExprDesc* Expr) /* Load the primary register with some constant value. */ { switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Number constant */ g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global symbol, load address */ g_getimmed ((Flags | CF_EXTERNAL) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static symbol or literal, load address */ g_getimmed ((Flags | CF_STATIC) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable. Taking the address is usually not * allowed. */ if (IS_Get (&AllowRegVarAddr) == 0) { Error ("Cannot take the address of a register variable"); } g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->IVal); break; case E_LOC_STACK: g_leasp (Expr->IVal); break; default: Internal ("Unknown constant type: %04X", Expr->Flags); } } void LoadExpr (unsigned Flags, struct ExprDesc* Expr) /* Load an expression into the primary register if it is not already there. */ { if (ED_IsLVal (Expr)) { /* Dereferenced lvalue. If this is a bit field its type is unsigned. * But if the field is completely contained in the lower byte, we will * throw away the high byte anyway and may therefore load just the * low byte. */ if (ED_IsBitField (Expr)) { Flags |= (Expr->BitOffs + Expr->BitWidth <= CHAR_BITS)? CF_CHAR : CF_INT; Flags |= CF_UNSIGNED; } else { Flags |= TypeOf (Expr->Type); } if (ED_NeedsTest (Expr)) { Flags |= CF_TEST; } switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_getstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global variable */ g_getstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_getstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable */ g_getstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal); break; case E_LOC_STACK: /* Value on the stack */ g_getlocal (Flags, Expr->IVal); break; case E_LOC_PRIMARY: /* The primary register - just test if necessary */ if (Flags & CF_TEST) { g_test (Flags); } break; case E_LOC_EXPR: /* Reference to address in primary with offset in Expr */ g_getind (Flags, Expr->IVal); break; default: Internal ("Invalid location in LoadExpr: 0x%04X", ED_GetLoc (Expr)); } /* Handle bit fields. The actual type may have been casted or * converted, so be sure to always use unsigned ints for the * operations. */ if (ED_IsBitField (Expr)) { unsigned F = CF_INT | CF_UNSIGNED | CF_CONST | (Flags & CF_TEST); /* Shift right by the bit offset */ g_asr (F, Expr->BitOffs); /* And by the width if the field doesn't end on an int boundary */ if (Expr->BitOffs + Expr->BitWidth != CHAR_BITS && Expr->BitOffs + Expr->BitWidth != INT_BITS) { g_and (F, (0x0001U << Expr->BitWidth) - 1U); } } /* Expression was tested */ ED_TestDone (Expr); } else { /* An rvalue */ if (ED_IsLocExpr (Expr)) { if (Expr->IVal != 0) { /* We have an expression in the primary plus a constant * offset. Adjust the value in the primary accordingly. */ Flags |= TypeOf (Expr->Type); g_inc (Flags | CF_CONST, Expr->IVal); } } else { /* Constant of some sort, load it into the primary */ LoadConstant (Flags, Expr); } /* Are we testing this value? */ if (ED_NeedsTest (Expr)) { /* Yes, force a test */ Flags |= TypeOf (Expr->Type); g_test (Flags); ED_TestDone (Expr); } } }
835
./cc65/src/cc65/symentry.c
/*****************************************************************************/ /* */ /* symentry.c */ /* */ /* Symbol table entries for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xmalloc.h" /* cc65 */ #include "anonname.h" #include "declare.h" #include "error.h" #include "symentry.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ SymEntry* NewSymEntry (const char* Name, unsigned Flags) /* Create a new symbol table with the given name */ { /* Get the length of the name */ unsigned Len = strlen (Name); /* Allocate memory for the symbol entry */ SymEntry* E = xmalloc (sizeof (SymEntry) + Len); /* Initialize the entry */ E->NextHash = 0; E->PrevSym = 0; E->NextSym = 0; E->Link = 0; E->Owner = 0; E->Flags = Flags; E->Type = 0; E->Attr = 0; E->AsmName = 0; memcpy (E->Name, Name, Len+1); /* Return the new entry */ return E; } void FreeSymEntry (SymEntry* E) /* Free a symbol entry */ { TypeFree (E->Type); xfree (E->AsmName); xfree (E); } void DumpSymEntry (FILE* F, const SymEntry* E) /* Dump the given symbol table entry to the file in readable form */ { static const struct { const char* Name; unsigned Val; } Flags [] = { /* Beware: Order is important! */ { "SC_TYPEDEF", SC_TYPEDEF }, { "SC_BITFIELD", SC_BITFIELD }, { "SC_STRUCTFIELD", SC_STRUCTFIELD }, { "SC_UNION", SC_UNION }, { "SC_STRUCT", SC_STRUCT }, { "SC_AUTO", SC_AUTO }, { "SC_REGISTER", SC_REGISTER }, { "SC_STATIC", SC_STATIC }, { "SC_EXTERN", SC_EXTERN }, { "SC_ENUM", SC_ENUM }, { "SC_CONST", SC_CONST }, { "SC_LABEL", SC_LABEL }, { "SC_PARAM", SC_PARAM }, { "SC_FUNC", SC_FUNC }, { "SC_STORAGE", SC_STORAGE }, { "SC_DEF", SC_DEF }, { "SC_REF", SC_REF }, { "SC_ZEROPAGE", SC_ZEROPAGE }, }; unsigned I; unsigned SymFlags; /* Print the name */ fprintf (F, "%s:\n", E->Name); /* Print the assembler name if we have one */ if (E->AsmName) { fprintf (F, " AsmName: %s\n", E->AsmName); } /* Print the flags */ SymFlags = E->Flags; fprintf (F, " Flags: "); for (I = 0; I < sizeof (Flags) / sizeof (Flags[0]) && SymFlags != 0; ++I) { if ((SymFlags & Flags[I].Val) == Flags[I].Val) { SymFlags &= ~Flags[I].Val; fprintf (F, "%s ", Flags[I].Name); } } if (SymFlags != 0) { fprintf (F, "%04X", SymFlags); } fprintf (F, "\n"); /* Print the type */ fprintf (F, " Type: "); if (E->Type) { PrintType (F, E->Type); } else { fprintf (F, "(none)"); } fprintf (F, "\n"); } int SymIsOutputFunc (const SymEntry* Sym) /* Return true if this is a function that must be output */ { /* Symbol must be a function which is defined and either extern or * static and referenced. */ return IsTypeFunc (Sym->Type) && SymIsDef (Sym) && (Sym->Flags & (SC_REF | SC_EXTERN)); } const DeclAttr* SymGetAttr (const SymEntry* Sym, DeclAttrType AttrType) /* Return an attribute for this symbol or NULL if the attribute does not exist */ { /* Beware: We may not even have a collection */ if (Sym->Attr) { unsigned I; for (I = 0; I < CollCount (Sym->Attr); ++I) { /* Get the next attribute */ const DeclAttr* A = CollConstAt (Sym->Attr, I); /* If this is the one we're searching for, return it */ if (A->AttrType == AttrType) { return A; } } } /* Not found */ return 0; } void SymUseAttr (SymEntry* Sym, struct Declaration* D) /* Use the attributes from the declaration for this symbol */ { /* We cannot specify attributes twice */ if ((Sym->Flags & SC_HAVEATTR) != 0) { if (D->Attributes != 0) { Error ("Attributes must be specified in the first declaration"); } return; } /* Move the attributes */ Sym->Attr = D->Attributes; D->Attributes = 0; Sym->Flags |= SC_HAVEATTR; } void SymSetAsmName (SymEntry* Sym) /* Set the assembler name for an external symbol from the name of the symbol */ { unsigned Len; /* Cannot be used to change the name */ PRECONDITION (Sym->AsmName == 0); /* The assembler name starts with an underline */ Len = strlen (Sym->Name); Sym->AsmName = xmalloc (Len + 2); Sym->AsmName[0] = '_'; memcpy (Sym->AsmName+1, Sym->Name, Len+1); } void CvtRegVarToAuto (SymEntry* Sym) /* Convert a register variable to an auto variable */ { /* Change the storage class */ Sym->Flags = (Sym->Flags & ~(SC_REGISTER | SC_STATIC | SC_EXTERN)) | SC_AUTO; /* Transfer the stack offset from register save area to actual offset */ Sym->V.Offs = Sym->V.R.SaveOffs; } void ChangeSymType (SymEntry* Entry, Type* T) /* Change the type of the given symbol */ { TypeFree (Entry->Type); Entry->Type = TypeDup (T); } void ChangeAsmName (SymEntry* Entry, const char* NewAsmName) /* Change the assembler name of the symbol */ { xfree (Entry->AsmName); Entry->AsmName = xstrdup (NewAsmName); } int HasAnonName (const SymEntry* Entry) /* Return true if the symbol entry has an anonymous name */ { return IsAnonName (Entry->Name); }
836
./cc65/src/cc65/coptc02.c
/*****************************************************************************/ /* */ /* coptc02.h */ /* */ /* 65C02 specific optimizations */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roeerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "error.h" #include "coptc02.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned Opt65C02Ind (CodeSeg* S) /* Try to use the indirect addressing mode where possible */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for addressing mode indirect indexed Y where Y is zero. * Note: All opcodes that are available as (zp),y are also available * as (zp), so we can ignore the actual opcode here. */ if (E->AM == AM65_ZP_INDY && E->RI->In.RegY == 0) { /* Replace it by indirect addressing mode */ CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_IND, E->Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned Opt65C02BitOps (CodeSeg* S) /* Use special bit op instructions of the C02 */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && (L[0]->AM == AM65_ZP || L[0]->AM == AM65_ABS) && !CS_RangeHasLabel (S, I+1, 2) && CS_GetEntries (S, L+1, I+1, 2) && (L[1]->OPC == OP65_AND || L[1]->OPC == OP65_ORA) && CE_IsConstImm (L[1]) && L[2]->OPC == OP65_STA && L[2]->AM == L[0]->AM && strcmp (L[2]->Arg, L[0]->Arg) == 0 && !RegAUsed (S, I+3)) { char Buf[32]; CodeEntry* X; /* Use TRB for AND and TSB for ORA */ if (L[1]->OPC == OP65_AND) { /* LDA #XX */ sprintf (Buf, "$%02X", (int) ((~L[1]->Num) & 0xFF)); X = NewCodeEntry (OP65_LDA, AM65_IMM, Buf, 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* TRB */ X = NewCodeEntry (OP65_TRB, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); } else { /* LDA #XX */ sprintf (Buf, "$%02X", (int) L[1]->Num); X = NewCodeEntry (OP65_LDA, AM65_IMM, Buf, 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* TSB */ X = NewCodeEntry (OP65_TSB, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); } /* Delete the old stuff */ CS_DelEntries (S, I, 3); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned Opt65C02Stores (CodeSeg* S) /* Use STZ where possible */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a store with a register value of zero and an addressing * mode available with STZ. */ if (((E->OPC == OP65_STA && E->RI->In.RegA == 0) || (E->OPC == OP65_STX && E->RI->In.RegX == 0) || (E->OPC == OP65_STY && E->RI->In.RegY == 0)) && (E->AM == AM65_ZP || E->AM == AM65_ABS || E->AM == AM65_ZPX || E->AM == AM65_ABSX)) { /* Replace by STZ */ CodeEntry* X = NewCodeEntry (OP65_STZ, E->AM, E->Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); /* Delete the old stuff */ CS_DelEntry (S, I); /* We had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
837
./cc65/src/cc65/stdfunc.c
/*****************************************************************************/ /* */ /* stdfunc.c */ /* */ /* Handle inlining of known functions for the cc65 compiler */ /* */ /* */ /* */ /* (C) 1998-2010 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "attrib.h" #include "check.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "codegen.h" #include "error.h" #include "funcdesc.h" #include "global.h" #include "litpool.h" #include "loadexpr.h" #include "scanner.h" #include "stackptr.h" #include "stdfunc.h" #include "stdnames.h" #include "typeconv.h" /*****************************************************************************/ /* Function forwards */ /*****************************************************************************/ static void StdFunc_memcpy (FuncDesc*, ExprDesc*); static void StdFunc_memset (FuncDesc*, ExprDesc*); static void StdFunc_strcmp (FuncDesc*, ExprDesc*); static void StdFunc_strcpy (FuncDesc*, ExprDesc*); static void StdFunc_strlen (FuncDesc*, ExprDesc*); /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Table with all known functions and their handlers. Must be sorted * alphabetically! */ static struct StdFuncDesc { const char* Name; void (*Handler) (FuncDesc*, ExprDesc*); } StdFuncs[] = { { "memcpy", StdFunc_memcpy }, { "memset", StdFunc_memset }, { "strcmp", StdFunc_strcmp }, { "strcpy", StdFunc_strcpy }, { "strlen", StdFunc_strlen }, }; #define FUNC_COUNT (sizeof (StdFuncs) / sizeof (StdFuncs[0])) typedef struct ArgDesc ArgDesc; struct ArgDesc { const Type* ArgType; /* Required argument type */ ExprDesc Expr; /* Argument expression */ const Type* Type; /* The original type before conversion */ CodeMark Load; /* Start of argument load code */ CodeMark Push; /* Start of argument push code */ CodeMark End; /* End of the code for calculation+push */ unsigned Flags; /* Code generation flags */ }; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static int CmpFunc (const void* Key, const void* Elem) /* Compare function for bsearch */ { return strcmp ((const char*) Key, ((const struct StdFuncDesc*) Elem)->Name); } static long ArrayElementCount (const ArgDesc* Arg) /* Check if the type of the given argument is an array. If so, and if the * element count is known, return it. In all other cases, return UNSPECIFIED. */ { long Count; if (IsTypeArray (Arg->Type)) { Count = GetElementCount (Arg->Type); if (Count == FLEXIBLE) { /* Treat as unknown */ Count = UNSPECIFIED; } } else { Count = UNSPECIFIED; } return Count; } static void ParseArg (ArgDesc* Arg, Type* Type) /* Parse one argument but do not push it onto the stack. Make all fields in * Arg valid. */ { /* We have a prototype, so chars may be pushed as chars */ Arg->Flags = CF_FORCECHAR; /* Remember the required argument type */ Arg->ArgType = Type; /* Read the expression we're going to pass to the function */ MarkedExprWithCheck (hie1, &Arg->Expr); /* Remember the actual argument type */ Arg->Type = Arg->Expr.Type; /* Convert this expression to the expected type */ TypeConversion (&Arg->Expr, Type); /* Remember the following code position */ GetCodePos (&Arg->Load); /* If the value is a constant, set the flag, otherwise load it into the * primary register. */ if (ED_IsConstAbsInt (&Arg->Expr) && ED_CodeRangeIsEmpty (&Arg->Expr)) { /* Remember that we have a constant value */ Arg->Flags |= CF_CONST; } else { /* Load into the primary */ LoadExpr (CF_NONE, &Arg->Expr); } /* Remember the following code position */ GetCodePos (&Arg->Push); GetCodePos (&Arg->End); /* Use the type of the argument for the push */ Arg->Flags |= TypeOf (Arg->Expr.Type); } /*****************************************************************************/ /* memcpy */ /*****************************************************************************/ static void StdFunc_memcpy (FuncDesc* F attribute ((unused)), ExprDesc* Expr) /* Handle the memcpy function */ { /* Argument types: (void*, const void*, size_t) */ static Type Arg1Type[] = { TYPE(T_PTR), TYPE(T_VOID), TYPE(T_END) }; static Type Arg2Type[] = { TYPE(T_PTR), TYPE(T_VOID|T_QUAL_CONST), TYPE(T_END) }; static Type Arg3Type[] = { TYPE(T_SIZE_T), TYPE(T_END) }; ArgDesc Arg1, Arg2, Arg3; unsigned ParamSize = 0; unsigned Label; int Offs; /* Argument #1 */ ParseArg (&Arg1, Arg1Type); g_push (Arg1.Flags, Arg1.Expr.IVal); GetCodePos (&Arg1.End); ParamSize += SizeOf (Arg1Type); ConsumeComma (); /* Argument #2 */ ParseArg (&Arg2, Arg2Type); g_push (Arg2.Flags, Arg2.Expr.IVal); GetCodePos (&Arg2.End); ParamSize += SizeOf (Arg2Type); ConsumeComma (); /* Argument #3. Since memcpy is a fastcall function, we must load the * arg into the primary if it is not already there. This parameter is * also ignored for the calculation of the parameter size, since it is * not passed via the stack. */ ParseArg (&Arg3, Arg3Type); if (Arg3.Flags & CF_CONST) { LoadExpr (CF_NONE, &Arg3.Expr); } /* Emit the actual function call. This will also cleanup the stack. */ g_call (CF_FIXARGC, Func_memcpy, ParamSize); if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal == 0) { /* memcpy has been called with a count argument of zero */ Warning ("Call to memcpy has no effect"); /* Remove all of the generated code but the load of the first * argument, which is what memcpy returns. */ RemoveCode (&Arg1.Push); /* Set the function result to the first argument */ *Expr = Arg1.Expr; /* Bail out, no need for further improvements */ goto ExitPoint; } /* We've generated the complete code for the function now and know the * types of all parameters. Check for situations where better code can * be generated. If such a situation is detected, throw away the * generated, and emit better code. */ if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ((ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr)) || (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr))) && ((ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) || (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr)))) { int Reg1 = ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr); int Reg2 = ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need a label */ Label = GetLocalLabel (); /* Generate memcpy code */ if (Arg3.Expr.IVal <= 127) { AddCodeLine ("ldy #$%02X", (unsigned char) (Arg3.Expr.IVal-1)); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); if (Reg2) { AddCodeLine ("lda (%s),y", ED_GetLabelName (&Arg2.Expr, 0)); } else { AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg2.Expr, 0)); } if (Reg1) { AddCodeLine ("sta (%s),y", ED_GetLabelName (&Arg1.Expr, 0)); } else { AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, 0)); } AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldy #$00"); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); if (Reg2) { AddCodeLine ("lda (%s),y", ED_GetLabelName (&Arg2.Expr, 0)); } else { AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg2.Expr, 0)); } if (Reg1) { AddCodeLine ("sta (%s),y", ED_GetLabelName (&Arg1.Expr, 0)); } else { AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, 0)); } AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } /* memcpy returns the address, so the result is actually identical * to the first argument. */ *Expr = Arg1.Expr; } else if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr) && ED_IsRVal (&Arg1.Expr) && ED_IsLocStack (&Arg1.Expr) && (Arg1.Expr.IVal - StackPtr) + Arg3.Expr.IVal < 256) { /* It is possible to just use one index register even if the stack * offset is not zero, by adjusting the offset to the constant * address accordingly. But we cannot do this if the data in * question is in the register space or at an absolute address less * than 256. Register space is zero page, which means that the * address calculation could overflow in the linker. */ int AllowOneIndex = !ED_IsLocRegister (&Arg2.Expr) && !(ED_IsLocAbs (&Arg2.Expr) && Arg2.Expr.IVal < 256); /* Calculate the real stack offset */ Offs = ED_GetStackOffs (&Arg1.Expr, 0); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need a label */ Label = GetLocalLabel (); /* Generate memcpy code */ if (Arg3.Expr.IVal <= 127 && !AllowOneIndex) { if (Offs == 0) { AddCodeLine ("ldy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal - 1)); g_defcodelabel (Label); AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg2.Expr, -Offs)); AddCodeLine ("sta (sp),y"); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldx #$%02X", (unsigned char) (Arg3.Expr.IVal-1)); AddCodeLine ("ldy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal - 1)); g_defcodelabel (Label); AddCodeLine ("lda %s,x", ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine ("sta (sp),y"); AddCodeLine ("dey"); AddCodeLine ("dex"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } } else { if (Offs == 0 || AllowOneIndex) { AddCodeLine ("ldy #$%02X", (unsigned char) Offs); g_defcodelabel (Label); AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg2.Expr, -Offs)); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal)); AddCodeLine ("bne %s", LocalLabelName (Label)); } else { AddCodeLine ("ldx #$00"); AddCodeLine ("ldy #$%02X", (unsigned char) Offs); g_defcodelabel (Label); AddCodeLine ("lda %s,x", ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("inx"); AddCodeLine ("cpx #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } } /* memcpy returns the address, so the result is actually identical * to the first argument. */ *Expr = Arg1.Expr; } else if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsRVal (&Arg2.Expr) && ED_IsLocStack (&Arg2.Expr) && (Arg2.Expr.IVal - StackPtr) + Arg3.Expr.IVal < 256 && ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) { /* It is possible to just use one index register even if the stack * offset is not zero, by adjusting the offset to the constant * address accordingly. But we cannot do this if the data in * question is in the register space or at an absolute address less * than 256. Register space is zero page, which means that the * address calculation could overflow in the linker. */ int AllowOneIndex = !ED_IsLocRegister (&Arg1.Expr) && !(ED_IsLocAbs (&Arg1.Expr) && Arg1.Expr.IVal < 256); /* Calculate the real stack offset */ Offs = ED_GetStackOffs (&Arg2.Expr, 0); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need a label */ Label = GetLocalLabel (); /* Generate memcpy code */ if (Arg3.Expr.IVal <= 127 && !AllowOneIndex) { if (Offs == 0) { AddCodeLine ("ldy #$%02X", (unsigned char) (Arg3.Expr.IVal - 1)); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, 0)); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldx #$%02X", (unsigned char) (Arg3.Expr.IVal-1)); AddCodeLine ("ldy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal - 1)); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,x", ED_GetLabelName (&Arg1.Expr, 0)); AddCodeLine ("dey"); AddCodeLine ("dex"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } } else { if (Offs == 0 || AllowOneIndex) { AddCodeLine ("ldy #$%02X", (unsigned char) Offs); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, -Offs)); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal)); AddCodeLine ("bne %s", LocalLabelName (Label)); } else { AddCodeLine ("ldx #$00"); AddCodeLine ("ldy #$%02X", (unsigned char) Offs); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,x", ED_GetLabelName (&Arg1.Expr, 0)); AddCodeLine ("iny"); AddCodeLine ("inx"); AddCodeLine ("cpx #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } } /* memcpy returns the address, so the result is actually identical * to the first argument. */ *Expr = Arg1.Expr; } else if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsRVal (&Arg2.Expr) && ED_IsLocStack (&Arg2.Expr) && (Offs = ED_GetStackOffs (&Arg2.Expr, 0)) == 0) { /* Drop the generated code but leave the load of the first argument*/ RemoveCode (&Arg1.Push); /* We need a label */ Label = GetLocalLabel (); /* Generate memcpy code */ AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); if (Arg3.Expr.IVal <= 127) { AddCodeLine ("ldy #$%02X", (unsigned char) (Arg3.Expr.IVal - 1)); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta (ptr1),y"); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldy #$00"); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta (ptr1),y"); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } /* Reload result - X hasn't changed by the code above */ AddCodeLine ("lda ptr1"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } else { /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } ExitPoint: /* We expect the closing brace */ ConsumeRParen (); } /*****************************************************************************/ /* memset */ /*****************************************************************************/ static void StdFunc_memset (FuncDesc* F attribute ((unused)), ExprDesc* Expr) /* Handle the memset function */ { /* Argument types: (void*, int, size_t) */ static Type Arg1Type[] = { TYPE(T_PTR), TYPE(T_VOID), TYPE(T_END) }; static Type Arg2Type[] = { TYPE(T_INT), TYPE(T_END) }; static Type Arg3Type[] = { TYPE(T_SIZE_T), TYPE(T_END) }; ArgDesc Arg1, Arg2, Arg3; int MemSet = 1; /* Use real memset if true */ unsigned ParamSize = 0; unsigned Label; /* Argument #1 */ ParseArg (&Arg1, Arg1Type); g_push (Arg1.Flags, Arg1.Expr.IVal); GetCodePos (&Arg1.End); ParamSize += SizeOf (Arg1Type); ConsumeComma (); /* Argument #2. This argument is special in that we will call another * function if it is a constant zero. */ ParseArg (&Arg2, Arg2Type); if ((Arg2.Flags & CF_CONST) != 0 && Arg2.Expr.IVal == 0) { /* Don't call memset, call bzero instead */ MemSet = 0; } else { /* Push the argument */ g_push (Arg2.Flags, Arg2.Expr.IVal); GetCodePos (&Arg2.End); ParamSize += SizeOf (Arg2Type); } ConsumeComma (); /* Argument #3. Since memset is a fastcall function, we must load the * arg into the primary if it is not already there. This parameter is * also ignored for the calculation of the parameter size, since it is * not passed via the stack. */ ParseArg (&Arg3, Arg3Type); if (Arg3.Flags & CF_CONST) { LoadExpr (CF_NONE, &Arg3.Expr); } /* Emit the actual function call. This will also cleanup the stack. */ g_call (CF_FIXARGC, MemSet? Func_memset : Func__bzero, ParamSize); if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal == 0) { /* memset has been called with a count argument of zero */ Warning ("Call to memset has no effect"); /* Remove all of the generated code but the load of the first * argument, which is what memset returns. */ RemoveCode (&Arg1.Push); /* Set the function result to the first argument */ *Expr = Arg1.Expr; /* Bail out, no need for further improvements */ goto ExitPoint; } /* We've generated the complete code for the function now and know the * types of all parameters. Check for situations where better code can * be generated. If such a situation is detected, throw away the * generated, and emit better code. * Note: Lots of improvements would be possible here, but I will * concentrate on the most common case: memset with arguments 2 and 3 * being constant numerical values. Some checks have shown that this * covers nearly 90% of all memset calls. */ if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsConstAbsInt (&Arg2.Expr) && ((ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) || (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr)))) { int Reg = ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need a label */ Label = GetLocalLabel (); /* Generate memset code */ if (Arg3.Expr.IVal <= 127) { AddCodeLine ("ldy #$%02X", (unsigned char) (Arg3.Expr.IVal-1)); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); if (Reg) { AddCodeLine ("sta (%s),y", ED_GetLabelName (&Arg1.Expr, 0)); } else { AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, 0)); } AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldy #$00"); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); if (Reg) { AddCodeLine ("sta (%s),y", ED_GetLabelName (&Arg1.Expr, 0)); } else { AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, 0)); } AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } /* memset returns the address, so the result is actually identical * to the first argument. */ *Expr = Arg1.Expr; } else if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsConstAbsInt (&Arg2.Expr) && ED_IsRVal (&Arg1.Expr) && ED_IsLocStack (&Arg1.Expr) && (Arg1.Expr.IVal - StackPtr) + Arg3.Expr.IVal < 256) { /* Calculate the real stack offset */ int Offs = ED_GetStackOffs (&Arg1.Expr, 0); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need a label */ Label = GetLocalLabel (); /* Generate memset code */ AddCodeLine ("ldy #$%02X", (unsigned char) Offs); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) (Offs + Arg3.Expr.IVal)); AddCodeLine ("bne %s", LocalLabelName (Label)); /* memset returns the address, so the result is actually identical * to the first argument. */ *Expr = Arg1.Expr; } else if (ED_IsConstAbsInt (&Arg3.Expr) && Arg3.Expr.IVal <= 256 && ED_IsConstAbsInt (&Arg2.Expr) && (Arg2.Expr.IVal != 0 || IS_Get (&CodeSizeFactor) > 200)) { /* Remove all of the generated code but the load of the first * argument. */ RemoveCode (&Arg1.Push); /* We need a label */ Label = GetLocalLabel (); /* Generate code */ AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); if (Arg3.Expr.IVal <= 127) { AddCodeLine ("ldy #$%02X", (unsigned char) (Arg3.Expr.IVal-1)); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); AddCodeLine ("sta (ptr1),y"); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (Label)); } else { AddCodeLine ("ldy #$00"); AddCodeLine ("lda #$%02X", (unsigned char) Arg2.Expr.IVal); g_defcodelabel (Label); AddCodeLine ("sta (ptr1),y"); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Arg3.Expr.IVal); AddCodeLine ("bne %s", LocalLabelName (Label)); } /* Load the function result pointer into a/x (x is still valid). This * code will get removed by the optimizer if it is not used later. */ AddCodeLine ("lda ptr1"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } else { /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } ExitPoint: /* We expect the closing brace */ ConsumeRParen (); } /*****************************************************************************/ /* strcmp */ /*****************************************************************************/ static void StdFunc_strcmp (FuncDesc* F attribute ((unused)), ExprDesc* Expr) /* Handle the strcmp function */ { /* Argument types: (const char*, const char*) */ static Type Arg1Type[] = { TYPE(T_PTR), TYPE(T_CHAR|T_QUAL_CONST), TYPE(T_END) }; static Type Arg2Type[] = { TYPE(T_PTR), TYPE(T_CHAR|T_QUAL_CONST), TYPE(T_END) }; ArgDesc Arg1, Arg2; unsigned ParamSize = 0; long ECount1; long ECount2; int IsArray; int Offs; /* Setup the argument type string */ Arg1Type[1].C = GetDefaultChar () | T_QUAL_CONST; Arg2Type[1].C = GetDefaultChar () | T_QUAL_CONST; /* Argument #1 */ ParseArg (&Arg1, Arg1Type); g_push (Arg1.Flags, Arg1.Expr.IVal); ParamSize += SizeOf (Arg1Type); ConsumeComma (); /* Argument #2. */ ParseArg (&Arg2, Arg2Type); /* Since strcmp is a fastcall function, we must load the * arg into the primary if it is not already there. This parameter is * also ignored for the calculation of the parameter size, since it is * not passed via the stack. */ if (Arg2.Flags & CF_CONST) { LoadExpr (CF_NONE, &Arg2.Expr); } /* Emit the actual function call. This will also cleanup the stack. */ g_call (CF_FIXARGC, Func_strcmp, ParamSize); /* Get the element counts of the arguments. Then get the larger of the * two into ECount1. This removes FLEXIBLE and UNSPECIFIED automatically */ ECount1 = ArrayElementCount (&Arg1); ECount2 = ArrayElementCount (&Arg2); if (ECount2 > ECount1) { ECount1 = ECount2; } /* If the second argument is the empty string literal, we can generate * more efficient code. */ if (ED_IsLocLiteral (&Arg2.Expr) && IS_Get (&WritableStrings) == 0 && GetLiteralSize (Arg2.Expr.LVal) == 1 && GetLiteralStr (Arg2.Expr.LVal)[0] == '\0') { /* Drop the generated code so we have the first argument in the * primary */ RemoveCode (&Arg1.Push); /* We don't need the literal any longer */ ReleaseLiteral (Arg2.Expr.LVal); /* We do now have Arg1 in the primary. Load the first character from * this string and cast to int. This is the function result. */ IsArray = IsTypeArray (Arg1.Type) && ED_IsRVal (&Arg1.Expr); if (IsArray && ED_IsLocStack (&Arg1.Expr) && (Offs = ED_GetStackOffs (&Arg1.Expr, 0) < 256)) { /* Drop the generated code */ RemoveCode (&Arg1.Load); /* Generate code */ AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("ldx #$00"); AddCodeLine ("lda (sp),y"); } else if (IsArray && ED_IsLocConst (&Arg1.Expr)) { /* Drop the generated code */ RemoveCode (&Arg1.Load); /* Generate code */ AddCodeLine ("ldx #$00"); AddCodeLine ("lda %s", ED_GetLabelName (&Arg1.Expr, 0)); } else { /* Drop part of the generated code so we have the first argument * in the primary */ RemoveCode (&Arg1.Push); /* Fetch the first char */ g_getind (CF_CHAR | CF_UNSIGNED, 0); } } else if ((IS_Get (&CodeSizeFactor) >= 165) && ((ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr)) || (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr))) && ((ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) || (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr))) && (IS_Get (&InlineStdFuncs) || (ECount1 > 0 && ECount1 < 256))) { unsigned Entry, Loop, Fin; /* Labels */ const char* Load; const char* Compare; if (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr)) { Load = "lda (%s),y"; } else { Load = "lda %s,y"; } if (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr)) { Compare = "cmp (%s),y"; } else { Compare = "cmp %s,y"; } /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need labels */ Entry = GetLocalLabel (); Loop = GetLocalLabel (); Fin = GetLocalLabel (); /* Generate strcmp code */ AddCodeLine ("ldy #$00"); AddCodeLine ("beq %s", LocalLabelName (Entry)); g_defcodelabel (Loop); AddCodeLine ("tax"); AddCodeLine ("beq %s", LocalLabelName (Fin)); AddCodeLine ("iny"); g_defcodelabel (Entry); AddCodeLine (Load, ED_GetLabelName (&Arg1.Expr, 0)); AddCodeLine (Compare, ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine ("beq %s", LocalLabelName (Loop)); AddCodeLine ("ldx #$01"); AddCodeLine ("bcs %s", LocalLabelName (Fin)); AddCodeLine ("ldx #$FF"); g_defcodelabel (Fin); } else if ((IS_Get (&CodeSizeFactor) > 190) && ((ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr)) || (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr))) && (IS_Get (&InlineStdFuncs) || (ECount1 > 0 && ECount1 < 256))) { unsigned Entry, Loop, Fin; /* Labels */ const char* Compare; if (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr)) { Compare = "cmp (%s),y"; } else { Compare = "cmp %s,y"; } /* Drop the generated code */ RemoveCode (&Arg1.Push); /* We need labels */ Entry = GetLocalLabel (); Loop = GetLocalLabel (); Fin = GetLocalLabel (); /* Store Arg1 into ptr1 */ AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); /* Generate strcmp code */ AddCodeLine ("ldy #$00"); AddCodeLine ("beq %s", LocalLabelName (Entry)); g_defcodelabel (Loop); AddCodeLine ("tax"); AddCodeLine ("beq %s", LocalLabelName (Fin)); AddCodeLine ("iny"); g_defcodelabel (Entry); AddCodeLine ("lda (ptr1),y"); AddCodeLine (Compare, ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine ("beq %s", LocalLabelName (Loop)); AddCodeLine ("ldx #$01"); AddCodeLine ("bcs %s", LocalLabelName (Fin)); AddCodeLine ("ldx #$FF"); g_defcodelabel (Fin); } /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); /* We expect the closing brace */ ConsumeRParen (); } /*****************************************************************************/ /* strcpy */ /*****************************************************************************/ static void StdFunc_strcpy (FuncDesc* F attribute ((unused)), ExprDesc* Expr) /* Handle the strcpy function */ { /* Argument types: (char*, const char*) */ static Type Arg1Type[] = { TYPE(T_PTR), TYPE(T_CHAR), TYPE(T_END) }; static Type Arg2Type[] = { TYPE(T_PTR), TYPE(T_CHAR|T_QUAL_CONST), TYPE(T_END) }; ArgDesc Arg1, Arg2; unsigned ParamSize = 0; long ECount; unsigned L1; /* Setup the argument type string */ Arg1Type[1].C = GetDefaultChar (); Arg2Type[1].C = GetDefaultChar () | T_QUAL_CONST; /* Argument #1 */ ParseArg (&Arg1, Arg1Type); g_push (Arg1.Flags, Arg1.Expr.IVal); GetCodePos (&Arg1.End); ParamSize += SizeOf (Arg1Type); ConsumeComma (); /* Argument #2. Since strcpy is a fastcall function, we must load the * arg into the primary if it is not already there. This parameter is * also ignored for the calculation of the parameter size, since it is * not passed via the stack. */ ParseArg (&Arg2, Arg2Type); if (Arg2.Flags & CF_CONST) { LoadExpr (CF_NONE, &Arg2.Expr); } /* Emit the actual function call. This will also cleanup the stack. */ g_call (CF_FIXARGC, Func_strcpy, ParamSize); /* Get the element count of argument 1 if it is an array */ ECount = ArrayElementCount (&Arg1); /* We've generated the complete code for the function now and know the * types of all parameters. Check for situations where better code can * be generated. If such a situation is detected, throw away the * generated, and emit better code. */ if (((ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr)) || (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr))) && ((ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) || (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr))) && (IS_Get (&InlineStdFuncs) || (ECount != UNSPECIFIED && ECount < 256))) { const char* Load; const char* Store; if (ED_IsLVal (&Arg2.Expr) && ED_IsLocRegister (&Arg2.Expr)) { Load = "lda (%s),y"; } else { Load = "lda %s,y"; } if (ED_IsLVal (&Arg1.Expr) && ED_IsLocRegister (&Arg1.Expr)) { Store = "sta (%s),y"; } else { Store = "sta %s,y"; } /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need labels */ L1 = GetLocalLabel (); /* Generate strcpy code */ AddCodeLine ("ldy #$FF"); g_defcodelabel (L1); AddCodeLine ("iny"); AddCodeLine (Load, ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine (Store, ED_GetLabelName (&Arg1.Expr, 0)); AddCodeLine ("bne %s", LocalLabelName (L1)); /* strcpy returns argument #1 */ *Expr = Arg1.Expr; } else if (ED_IsRVal (&Arg2.Expr) && ED_IsLocStack (&Arg2.Expr) && StackPtr >= -255 && ED_IsRVal (&Arg1.Expr) && ED_IsLocConst (&Arg1.Expr)) { /* It is possible to just use one index register even if the stack * offset is not zero, by adjusting the offset to the constant * address accordingly. But we cannot do this if the data in * question is in the register space or at an absolute address less * than 256. Register space is zero page, which means that the * address calculation could overflow in the linker. */ int AllowOneIndex = !ED_IsLocRegister (&Arg1.Expr) && !(ED_IsLocAbs (&Arg1.Expr) && Arg1.Expr.IVal < 256); /* Calculate the real stack offset */ int Offs = ED_GetStackOffs (&Arg2.Expr, 0); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need labels */ L1 = GetLocalLabel (); /* Generate strcpy code */ AddCodeLine ("ldy #$%02X", (unsigned char) (Offs - 1)); if (Offs == 0 || AllowOneIndex) { g_defcodelabel (L1); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,y", ED_GetLabelName (&Arg1.Expr, -Offs)); } else { AddCodeLine ("ldx #$FF"); g_defcodelabel (L1); AddCodeLine ("iny"); AddCodeLine ("inx"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta %s,x", ED_GetLabelName (&Arg1.Expr, 0)); } AddCodeLine ("bne %s", LocalLabelName (L1)); /* strcpy returns argument #1 */ *Expr = Arg1.Expr; } else if (ED_IsRVal (&Arg2.Expr) && ED_IsLocConst (&Arg2.Expr) && ED_IsRVal (&Arg1.Expr) && ED_IsLocStack (&Arg1.Expr) && StackPtr >= -255) { /* It is possible to just use one index register even if the stack * offset is not zero, by adjusting the offset to the constant * address accordingly. But we cannot do this if the data in * question is in the register space or at an absolute address less * than 256. Register space is zero page, which means that the * address calculation could overflow in the linker. */ int AllowOneIndex = !ED_IsLocRegister (&Arg2.Expr) && !(ED_IsLocAbs (&Arg2.Expr) && Arg2.Expr.IVal < 256); /* Calculate the real stack offset */ int Offs = ED_GetStackOffs (&Arg1.Expr, 0); /* Drop the generated code */ RemoveCode (&Arg1.Expr.Start); /* We need labels */ L1 = GetLocalLabel (); /* Generate strcpy code */ AddCodeLine ("ldy #$%02X", (unsigned char) (Offs - 1)); if (Offs == 0 || AllowOneIndex) { g_defcodelabel (L1); AddCodeLine ("iny"); AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg2.Expr, -Offs)); AddCodeLine ("sta (sp),y"); } else { AddCodeLine ("ldx #$FF"); g_defcodelabel (L1); AddCodeLine ("iny"); AddCodeLine ("inx"); AddCodeLine ("lda %s,x", ED_GetLabelName (&Arg2.Expr, 0)); AddCodeLine ("sta (sp),y"); } AddCodeLine ("bne %s", LocalLabelName (L1)); /* strcpy returns argument #1 */ *Expr = Arg1.Expr; } else { /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = GetFuncReturn (Expr->Type); } /* We expect the closing brace */ ConsumeRParen (); } /*****************************************************************************/ /* strlen */ /*****************************************************************************/ static void StdFunc_strlen (FuncDesc* F attribute ((unused)), ExprDesc* Expr) /* Handle the strlen function */ { static Type ArgType[] = { TYPE(T_PTR), TYPE(T_CHAR|T_QUAL_CONST), TYPE(T_END) }; ExprDesc Arg; int IsArray; int IsPtr; int IsByteIndex; long ECount; unsigned L; /* Setup the argument type string */ ArgType[1].C = GetDefaultChar () | T_QUAL_CONST; /* Evaluate the parameter */ hie1 (&Arg); /* Check if the argument is an array. If so, remember the element count. * Otherwise set the element count to undefined. */ IsArray = IsTypeArray (Arg.Type); if (IsArray) { ECount = GetElementCount (Arg.Type); if (ECount == FLEXIBLE) { /* Treat as unknown */ ECount = UNSPECIFIED; } IsPtr = 0; } else { ECount = UNSPECIFIED; IsPtr = IsTypePtr (Arg.Type); } /* Check if the elements of an array can be addressed by a byte sized * index. This is true if the size of the array is known and less than * 256. */ IsByteIndex = (ECount != UNSPECIFIED && ECount < 256); /* Do type conversion */ TypeConversion (&Arg, ArgType); /* If the expression is a literal, and if string literals are read * only, we can calculate the length of the string and remove it * from the literal pool. Otherwise we have to calculate the length * at runtime. */ if (ED_IsLocLiteral (&Arg) && IS_Get (&WritableStrings) == 0) { /* Constant string literal */ ED_MakeConstAbs (Expr, GetLiteralSize (Arg.LVal) - 1, type_size_t); /* We don't need the literal any longer */ ReleaseLiteral (Arg.LVal); /* We will inline strlen for arrays with constant addresses, if either the * inlining was forced on the command line, or the array is smaller than * 256, so the inlining is considered safe. */ } else if (ED_IsLocConst (&Arg) && IsArray && (IS_Get (&InlineStdFuncs) || IsByteIndex)) { /* Generate the strlen code */ L = GetLocalLabel (); AddCodeLine ("ldy #$FF"); g_defcodelabel (L); AddCodeLine ("iny"); AddCodeLine ("lda %s,y", ED_GetLabelName (&Arg, 0)); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("tax"); AddCodeLine ("tya"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = type_size_t; /* We will inline strlen for arrays on the stack, if the array is * completely within the reach of a byte sized index register. */ } else if (ED_IsLocStack (&Arg) && IsArray && IsByteIndex && (Arg.IVal - StackPtr) + ECount < 256) { /* Calculate the true stack offset */ int Offs = ED_GetStackOffs (&Arg, 0); /* Generate the strlen code */ L = GetLocalLabel (); AddCodeLine ("ldx #$FF"); AddCodeLine ("ldy #$%02X", (unsigned char) (Offs-1)); g_defcodelabel (L); AddCodeLine ("inx"); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("txa"); AddCodeLine ("ldx #$00"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = type_size_t; /* strlen for a string that is pointed to by a register variable will only * get inlined if requested on the command line, since we cannot know how * big the buffer actually is, so inlining is not always safe. */ } else if (ED_IsLocRegister (&Arg) && ED_IsLVal (&Arg) && IsPtr && IS_Get (&InlineStdFuncs)) { /* Generate the strlen code */ L = GetLocalLabel (); AddCodeLine ("ldy #$FF"); g_defcodelabel (L); AddCodeLine ("iny"); AddCodeLine ("lda (%s),y", ED_GetLabelName (&Arg, 0)); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("tax"); AddCodeLine ("tya"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = type_size_t; /* Last check: We will inline a generic strlen routine if inlining was * requested on the command line, and the code size factor is more than * 400 (code is 13 bytes vs. 3 for a jsr call). */ } else if (IS_Get (&CodeSizeFactor) > 400 && IS_Get (&InlineStdFuncs)) { /* Load the expression into the primary */ LoadExpr (CF_NONE, &Arg); /* Inline the function */ L = GetLocalLabel (); AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); AddCodeLine ("ldy #$FF"); g_defcodelabel (L); AddCodeLine ("iny"); AddCodeLine ("lda (ptr1),y"); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("tax"); AddCodeLine ("tya"); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = type_size_t; } else { /* Load the expression into the primary */ LoadExpr (CF_NONE, &Arg); /* Call the strlen function */ AddCodeLine ("jsr _%s", Func_strlen); /* The function result is an rvalue in the primary register */ ED_MakeRValExpr (Expr); Expr->Type = type_size_t; } /* We expect the closing brace */ ConsumeRParen (); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ int FindStdFunc (const char* Name) /* Determine if the given function is a known standard function that may be * called in a special way. If so, return the index, otherwise return -1. */ { /* Look into the table for known names */ struct StdFuncDesc* D = bsearch (Name, StdFuncs, FUNC_COUNT, sizeof (StdFuncs[0]), CmpFunc); /* Return the function index or -1 */ if (D == 0) { return -1; } else { return D - StdFuncs; } } void HandleStdFunc (int Index, FuncDesc* F, ExprDesc* lval) /* Generate code for a known standard function. */ { struct StdFuncDesc* D; /* Get a pointer to the table entry */ CHECK (Index >= 0 && Index < (int)FUNC_COUNT); D = StdFuncs + Index; /* Call the handler function */ D->Handler (F, lval); }
838
./cc65/src/cc65/declare.c
/*****************************************************************************/ /* */ /* declare.c */ /* */ /* Parse variable and function declarations */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "addrsize.h" #include "mmodel.h" #include "xmalloc.h" /* cc65 */ #include "anonname.h" #include "codegen.h" #include "datatype.h" #include "declare.h" #include "declattr.h" #include "error.h" #include "expr.h" #include "funcdesc.h" #include "function.h" #include "global.h" #include "litpool.h" #include "pragma.h" #include "scanner.h" #include "standard.h" #include "symtab.h" #include "typeconv.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ typedef struct StructInitData StructInitData; struct StructInitData { unsigned Size; /* Size of struct */ unsigned Offs; /* Current offset in struct */ unsigned BitVal; /* Summed up bit-field value */ unsigned ValBits; /* Valid bits in Val */ }; /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers); /* Parse a type specificier */ static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers); /* Parse initialization of variables. Return the number of data bytes. */ /*****************************************************************************/ /* Internal functions */ /*****************************************************************************/ static void DuplicateQualifier (const char* Name) /* Print an error message */ { Warning ("Duplicate qualifier: `%s'", Name); } static TypeCode OptionalQualifiers (TypeCode Allowed) /* Read type qualifiers if we have any. Allowed specifies the allowed * qualifiers. */ { /* We start without any qualifiers */ TypeCode Q = T_QUAL_NONE; /* Check for more qualifiers */ while (1) { switch (CurTok.Tok) { case TOK_CONST: if (Allowed & T_QUAL_CONST) { if (Q & T_QUAL_CONST) { DuplicateQualifier ("const"); } Q |= T_QUAL_CONST; } else { goto Done; } break; case TOK_VOLATILE: if (Allowed & T_QUAL_VOLATILE) { if (Q & T_QUAL_VOLATILE) { DuplicateQualifier ("volatile"); } Q |= T_QUAL_VOLATILE; } else { goto Done; } break; case TOK_RESTRICT: if (Allowed & T_QUAL_RESTRICT) { if (Q & T_QUAL_RESTRICT) { DuplicateQualifier ("restrict"); } Q |= T_QUAL_RESTRICT; } else { goto Done; } break; case TOK_NEAR: if (Allowed & T_QUAL_NEAR) { if (Q & T_QUAL_NEAR) { DuplicateQualifier ("near"); } Q |= T_QUAL_NEAR; } else { goto Done; } break; case TOK_FAR: if (Allowed & T_QUAL_FAR) { if (Q & T_QUAL_FAR) { DuplicateQualifier ("far"); } Q |= T_QUAL_FAR; } else { goto Done; } break; case TOK_FASTCALL: if (Allowed & T_QUAL_FASTCALL) { if (Q & T_QUAL_FASTCALL) { DuplicateQualifier ("fastcall"); } Q |= T_QUAL_FASTCALL; } else { goto Done; } break; case TOK_CDECL: if (Allowed & T_QUAL_CDECL) { if (Q & T_QUAL_CDECL) { DuplicateQualifier ("cdecl"); } Q |= T_QUAL_CDECL; } else { goto Done; } break; default: goto Done; } /* Skip the token */ NextToken (); } Done: /* We cannot have more than one address size far qualifier */ switch (Q & T_QUAL_ADDRSIZE) { case T_QUAL_NONE: case T_QUAL_NEAR: case T_QUAL_FAR: break; default: Error ("Cannot specify more than one address size qualifier"); Q &= ~T_QUAL_ADDRSIZE; } /* We cannot have more than one calling convention specifier */ switch (Q & T_QUAL_CCONV) { case T_QUAL_NONE: case T_QUAL_FASTCALL: case T_QUAL_CDECL: break; default: Error ("Cannot specify more than one calling convention qualifier"); Q &= ~T_QUAL_CCONV; } /* Return the qualifiers read */ return Q; } static void OptionalInt (void) /* Eat an optional "int" token */ { if (CurTok.Tok == TOK_INT) { /* Skip it */ NextToken (); } } static void OptionalSigned (void) /* Eat an optional "signed" token */ { if (CurTok.Tok == TOK_SIGNED) { /* Skip it */ NextToken (); } } static void InitDeclSpec (DeclSpec* D) /* Initialize the DeclSpec struct for use */ { D->StorageClass = 0; D->Type[0].C = T_END; D->Flags = 0; } static void InitDeclaration (Declaration* D) /* Initialize the Declaration struct for use */ { D->Ident[0] = '\0'; D->Type[0].C = T_END; D->Index = 0; D->Attributes = 0; } static void NeedTypeSpace (Declaration* D, unsigned Count) /* Check if there is enough space for Count type specifiers within D */ { if (D->Index + Count >= MAXTYPELEN) { /* We must call Fatal() here, since calling Error() will try to * continue, and the declaration type is not correctly terminated * in case we come here. */ Fatal ("Too many type specifiers"); } } static void AddTypeToDeclaration (Declaration* D, TypeCode T) /* Add a type specifier to the type of a declaration */ { NeedTypeSpace (D, 1); D->Type[D->Index++].C = T; } static void FixQualifiers (Type* DataType) /* Apply several fixes to qualifiers */ { Type* T; TypeCode Q; /* Using typedefs, it is possible to generate declarations that have * type qualifiers attached to an array, not the element type. Go and * fix these here. */ T = DataType; Q = T_QUAL_NONE; while (T->C != T_END) { if (IsTypeArray (T)) { /* Extract any type qualifiers */ Q |= GetQualifier (T); T->C = UnqualifiedType (T->C); } else { /* Add extracted type qualifiers here */ T->C |= Q; Q = T_QUAL_NONE; } ++T; } /* Q must be empty now */ CHECK (Q == T_QUAL_NONE); /* Do some fixes on pointers and functions. */ T = DataType; while (T->C != T_END) { if (IsTypePtr (T)) { /* Fastcall qualifier on the pointer? */ if (IsQualFastcall (T)) { /* Pointer to function which is not fastcall? */ if (IsTypeFunc (T+1) && !IsQualFastcall (T+1)) { /* Move the fastcall qualifier from the pointer to * the function. */ T[0].C &= ~T_QUAL_FASTCALL; T[1].C |= T_QUAL_FASTCALL; } else { Error ("Invalid `_fastcall__' qualifier for pointer"); } } /* Apply the default far and near qualifiers if none are given */ Q = (T[0].C & T_QUAL_ADDRSIZE); if (Q == T_QUAL_NONE) { /* No address size qualifiers specified */ if (IsTypeFunc (T+1)) { /* Pointer to function. Use the qualifier from the function * or the default if the function don't has one. */ Q = (T[1].C & T_QUAL_ADDRSIZE); if (Q == T_QUAL_NONE) { Q = CodeAddrSizeQualifier (); } } else { Q = DataAddrSizeQualifier (); } T[0].C |= Q; } else { /* We have address size qualifiers. If followed by a function, * apply these also to the function. */ if (IsTypeFunc (T+1)) { TypeCode FQ = (T[1].C & T_QUAL_ADDRSIZE); if (FQ == T_QUAL_NONE) { T[1].C |= Q; } else if (FQ != Q) { Error ("Address size qualifier mismatch"); T[1].C = (T[1].C & ~T_QUAL_ADDRSIZE) | Q; } } } } else if (IsTypeFunc (T)) { /* Apply the default far and near qualifiers if none are given */ if ((T[0].C & T_QUAL_ADDRSIZE) == 0) { T[0].C |= CodeAddrSizeQualifier (); } } ++T; } } static void ParseStorageClass (DeclSpec* D, unsigned DefStorage) /* Parse a storage class */ { /* Assume we're using an explicit storage class */ D->Flags &= ~DS_DEF_STORAGE; /* Check the storage class given */ switch (CurTok.Tok) { case TOK_EXTERN: D->StorageClass = SC_EXTERN | SC_STATIC; NextToken (); break; case TOK_STATIC: D->StorageClass = SC_STATIC; NextToken (); break; case TOK_REGISTER: D->StorageClass = SC_REGISTER | SC_STATIC; NextToken (); break; case TOK_AUTO: D->StorageClass = SC_AUTO; NextToken (); break; case TOK_TYPEDEF: D->StorageClass = SC_TYPEDEF; NextToken (); break; default: /* No storage class given, use default */ D->Flags |= DS_DEF_STORAGE; D->StorageClass = DefStorage; break; } } static void ParseEnumDecl (void) /* Process an enum declaration . */ { int EnumVal; ident Ident; /* Accept forward definitions */ if (CurTok.Tok != TOK_LCURLY) { return; } /* Skip the opening curly brace */ NextToken (); /* Read the enum tags */ EnumVal = 0; while (CurTok.Tok != TOK_RCURLY) { /* We expect an identifier */ if (CurTok.Tok != TOK_IDENT) { Error ("Identifier expected"); continue; } /* Remember the identifier and skip it */ strcpy (Ident, CurTok.Ident); NextToken (); /* Check for an assigned value */ if (CurTok.Tok == TOK_ASSIGN) { ExprDesc Expr; NextToken (); ConstAbsIntExpr (hie1, &Expr); EnumVal = Expr.IVal; } /* Add an entry to the symbol table */ AddConstSym (Ident, type_int, SC_ENUM, EnumVal++); /* Check for end of definition */ if (CurTok.Tok != TOK_COMMA) break; NextToken (); } ConsumeRCurly (); } static int ParseFieldWidth (Declaration* Decl) /* Parse an optional field width. Returns -1 if no field width is speficied, * otherwise the width of the field. */ { ExprDesc Expr; if (CurTok.Tok != TOK_COLON) { /* No bit-field declaration */ return -1; } /* Read the width */ NextToken (); ConstAbsIntExpr (hie1, &Expr); if (Expr.IVal < 0) { Error ("Negative width in bit-field"); return -1; } if (Expr.IVal > (int) INT_BITS) { Error ("Width of bit-field exceeds its type"); return -1; } if (Expr.IVal == 0 && Decl->Ident[0] != '\0') { Error ("Zero width for named bit-field"); return -1; } if (!IsTypeInt (Decl->Type)) { /* Only integer types may be used for bit-fields */ Error ("Bit-field has invalid type"); return -1; } /* Return the field width */ return (int) Expr.IVal; } static SymEntry* StructOrUnionForwardDecl (const char* Name, unsigned Type) /* Handle a struct or union forward decl */ { /* Try to find a struct/union with the given name. If there is none, * insert a forward declaration into the current lexical level. */ SymEntry* Entry = FindTagSym (Name); if (Entry == 0) { Entry = AddStructSym (Name, Type, 0, 0); } else if ((Entry->Flags & SC_TYPEMASK) != Type) { /* Already defined, but no struct */ Error ("Symbol `%s' is already different kind", Name); } return Entry; } static unsigned CopyAnonStructFields (const Declaration* Decl, int Offs) /* Copy fields from an anon union/struct into the current lexical level. The * function returns the size of the embedded struct/union. */ { /* Get the pointer to the symbol table entry of the anon struct */ SymEntry* Entry = GetSymEntry (Decl->Type); /* Get the size of the anon struct */ unsigned Size = Entry->V.S.Size; /* Get the symbol table containing the fields. If it is empty, there has * been an error before, so bail out. */ SymTable* Tab = Entry->V.S.SymTab; if (Tab == 0) { /* Incomplete definition - has been flagged before */ return Size; } /* Get a pointer to the list of symbols. Then walk the list adding copies * of the embedded struct to the current level. */ Entry = Tab->SymHead; while (Entry) { /* Enter a copy of this symbol adjusting the offset. We will just * reuse the type string here. */ AddLocalSym (Entry->Name, Entry->Type, SC_STRUCTFIELD, Offs + Entry->V.Offs); /* Currently, there can not be any attributes, but if there will be * some in the future, we want to know this. */ CHECK (Entry->Attr == 0); /* Next entry */ Entry = Entry->NextSym; } /* Return the size of the embedded struct */ return Size; } static SymEntry* ParseUnionDecl (const char* Name) /* Parse a union declaration. */ { unsigned UnionSize; unsigned FieldSize; int FieldWidth; /* Width in bits, -1 if not a bit-field */ SymTable* FieldTab; if (CurTok.Tok != TOK_LCURLY) { /* Just a forward declaration. */ return StructOrUnionForwardDecl (Name, SC_UNION); } /* Add a forward declaration for the struct in the current lexical level */ AddStructSym (Name, SC_UNION, 0, 0); /* Skip the curly brace */ NextToken (); /* Enter a new lexical level for the struct */ EnterStructLevel (); /* Parse union fields */ UnionSize = 0; while (CurTok.Tok != TOK_RCURLY) { /* Get the type of the entry */ DeclSpec Spec; InitDeclSpec (&Spec); ParseTypeSpec (&Spec, -1, T_QUAL_NONE); /* Read fields with this type */ while (1) { Declaration Decl; /* Get type and name of the struct field */ ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT); /* Check for a bit-field declaration */ FieldWidth = ParseFieldWidth (&Decl); /* Ignore zero sized bit fields in a union */ if (FieldWidth == 0) { goto NextMember; } /* Check for fields without a name */ if (Decl.Ident[0] == '\0') { /* In cc65 mode, we allow anonymous structs/unions within * a struct. */ if (IS_Get (&Standard) >= STD_CC65 && IsClassStruct (Decl.Type)) { /* This is an anonymous struct or union. Copy the fields * into the current level. */ CopyAnonStructFields (&Decl, 0); } else { /* A non bit-field without a name is legal but useless */ Warning ("Declaration does not declare anything"); } goto NextMember; } /* Handle sizes */ FieldSize = CheckedSizeOf (Decl.Type); if (FieldSize > UnionSize) { UnionSize = FieldSize; } /* Add a field entry to the table. */ if (FieldWidth > 0) { AddBitField (Decl.Ident, 0, 0, FieldWidth); } else { AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, 0); } NextMember: if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } ConsumeSemi (); } /* Skip the closing brace */ NextToken (); /* Remember the symbol table and leave the struct level */ FieldTab = GetSymTab (); LeaveStructLevel (); /* Make a real entry from the forward decl and return it */ return AddStructSym (Name, SC_UNION, UnionSize, FieldTab); } static SymEntry* ParseStructDecl (const char* Name) /* Parse a struct declaration. */ { unsigned StructSize; int FlexibleMember; int BitOffs; /* Bit offset for bit-fields */ int FieldWidth; /* Width in bits, -1 if not a bit-field */ SymTable* FieldTab; if (CurTok.Tok != TOK_LCURLY) { /* Just a forward declaration. */ return StructOrUnionForwardDecl (Name, SC_STRUCT); } /* Add a forward declaration for the struct in the current lexical level */ AddStructSym (Name, SC_STRUCT, 0, 0); /* Skip the curly brace */ NextToken (); /* Enter a new lexical level for the struct */ EnterStructLevel (); /* Parse struct fields */ FlexibleMember = 0; StructSize = 0; BitOffs = 0; while (CurTok.Tok != TOK_RCURLY) { /* Get the type of the entry */ DeclSpec Spec; InitDeclSpec (&Spec); ParseTypeSpec (&Spec, -1, T_QUAL_NONE); /* Read fields with this type */ while (1) { Declaration Decl; ident Ident; /* If we had a flexible array member before, no other fields can * follow. */ if (FlexibleMember) { Error ("Flexible array member must be last field"); FlexibleMember = 0; /* Avoid further errors */ } /* Get type and name of the struct field */ ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT); /* Check for a bit-field declaration */ FieldWidth = ParseFieldWidth (&Decl); /* If this is not a bit field, or the bit field is too large for * the remainder of the current member, or we have a bit field * with width zero, align the struct to the next member by adding * a member with an anonymous name. */ if (BitOffs > 0) { if (FieldWidth <= 0 || (BitOffs + FieldWidth) > (int) INT_BITS) { /* We need an anonymous name */ AnonName (Ident, "bit-field"); /* Add an anonymous bit-field that aligns to the next * storage unit. */ AddBitField (Ident, StructSize, BitOffs, INT_BITS - BitOffs); /* No bits left */ StructSize += SIZEOF_INT; BitOffs = 0; } } /* Apart from the above, a bit field with width 0 is not processed * further. */ if (FieldWidth == 0) { goto NextMember; } /* Check if this field is a flexible array member, and * calculate the size of the field. */ if (IsTypeArray (Decl.Type) && GetElementCount (Decl.Type) == UNSPECIFIED) { /* Array with unspecified size */ if (StructSize == 0) { Error ("Flexible array member cannot be first struct field"); } FlexibleMember = 1; /* Assume zero for size calculations */ SetElementCount (Decl.Type, FLEXIBLE); } /* Check for fields without names */ if (Decl.Ident[0] == '\0') { if (FieldWidth < 0) { /* In cc65 mode, we allow anonymous structs/unions within * a struct. */ if (IS_Get (&Standard) >= STD_CC65 && IsClassStruct (Decl.Type)) { /* This is an anonymous struct or union. Copy the * fields into the current level. */ StructSize += CopyAnonStructFields (&Decl, StructSize); } else { /* A non bit-field without a name is legal but useless */ Warning ("Declaration does not declare anything"); } goto NextMember; } else { /* A bit-field without a name will get an anonymous one */ AnonName (Decl.Ident, "bit-field"); } } /* Add a field entry to the table */ if (FieldWidth > 0) { /* Add full byte from the bit offset to the variable offset. * This simplifies handling he bit-field as a char type * in expressions. */ unsigned Offs = StructSize + (BitOffs / CHAR_BITS); AddBitField (Decl.Ident, Offs, BitOffs % CHAR_BITS, FieldWidth); BitOffs += FieldWidth; CHECK (BitOffs <= (int) INT_BITS); if (BitOffs == INT_BITS) { StructSize += SIZEOF_INT; BitOffs = 0; } } else { AddLocalSym (Decl.Ident, Decl.Type, SC_STRUCTFIELD, StructSize); if (!FlexibleMember) { StructSize += CheckedSizeOf (Decl.Type); } } NextMember: if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } ConsumeSemi (); } /* If we have bits from bit-fields left, add them to the size. */ if (BitOffs > 0) { StructSize += ((BitOffs + CHAR_BITS - 1) / CHAR_BITS); } /* Skip the closing brace */ NextToken (); /* Remember the symbol table and leave the struct level */ FieldTab = GetSymTab (); LeaveStructLevel (); /* Make a real entry from the forward decl and return it */ return AddStructSym (Name, SC_STRUCT, StructSize, FieldTab); } static void ParseTypeSpec (DeclSpec* D, long Default, TypeCode Qualifiers) /* Parse a type specificier */ { ident Ident; SymEntry* Entry; /* Assume we have an explicit type */ D->Flags &= ~DS_DEF_TYPE; /* Read type qualifiers if we have any */ Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE); /* Look at the data type */ switch (CurTok.Tok) { case TOK_VOID: NextToken (); D->Type[0].C = T_VOID; D->Type[1].C = T_END; break; case TOK_CHAR: NextToken (); D->Type[0].C = GetDefaultChar(); D->Type[1].C = T_END; break; case TOK_LONG: NextToken (); if (CurTok.Tok == TOK_UNSIGNED) { NextToken (); OptionalInt (); D->Type[0].C = T_ULONG; D->Type[1].C = T_END; } else { OptionalSigned (); OptionalInt (); D->Type[0].C = T_LONG; D->Type[1].C = T_END; } break; case TOK_SHORT: NextToken (); if (CurTok.Tok == TOK_UNSIGNED) { NextToken (); OptionalInt (); D->Type[0].C = T_USHORT; D->Type[1].C = T_END; } else { OptionalSigned (); OptionalInt (); D->Type[0].C = T_SHORT; D->Type[1].C = T_END; } break; case TOK_INT: NextToken (); D->Type[0].C = T_INT; D->Type[1].C = T_END; break; case TOK_SIGNED: NextToken (); switch (CurTok.Tok) { case TOK_CHAR: NextToken (); D->Type[0].C = T_SCHAR; D->Type[1].C = T_END; break; case TOK_SHORT: NextToken (); OptionalInt (); D->Type[0].C = T_SHORT; D->Type[1].C = T_END; break; case TOK_LONG: NextToken (); OptionalInt (); D->Type[0].C = T_LONG; D->Type[1].C = T_END; break; case TOK_INT: NextToken (); /* FALL THROUGH */ default: D->Type[0].C = T_INT; D->Type[1].C = T_END; break; } break; case TOK_UNSIGNED: NextToken (); switch (CurTok.Tok) { case TOK_CHAR: NextToken (); D->Type[0].C = T_UCHAR; D->Type[1].C = T_END; break; case TOK_SHORT: NextToken (); OptionalInt (); D->Type[0].C = T_USHORT; D->Type[1].C = T_END; break; case TOK_LONG: NextToken (); OptionalInt (); D->Type[0].C = T_ULONG; D->Type[1].C = T_END; break; case TOK_INT: NextToken (); /* FALL THROUGH */ default: D->Type[0].C = T_UINT; D->Type[1].C = T_END; break; } break; case TOK_FLOAT: NextToken (); D->Type[0].C = T_FLOAT; D->Type[1].C = T_END; break; case TOK_DOUBLE: NextToken (); D->Type[0].C = T_DOUBLE; D->Type[1].C = T_END; break; case TOK_UNION: NextToken (); /* */ if (CurTok.Tok == TOK_IDENT) { strcpy (Ident, CurTok.Ident); NextToken (); } else { AnonName (Ident, "union"); } /* Remember we have an extra type decl */ D->Flags |= DS_EXTRA_TYPE; /* Declare the union in the current scope */ Entry = ParseUnionDecl (Ident); /* Encode the union entry into the type */ D->Type[0].C = T_UNION; SetSymEntry (D->Type, Entry); D->Type[1].C = T_END; break; case TOK_STRUCT: NextToken (); /* */ if (CurTok.Tok == TOK_IDENT) { strcpy (Ident, CurTok.Ident); NextToken (); } else { AnonName (Ident, "struct"); } /* Remember we have an extra type decl */ D->Flags |= DS_EXTRA_TYPE; /* Declare the struct in the current scope */ Entry = ParseStructDecl (Ident); /* Encode the struct entry into the type */ D->Type[0].C = T_STRUCT; SetSymEntry (D->Type, Entry); D->Type[1].C = T_END; break; case TOK_ENUM: NextToken (); if (CurTok.Tok != TOK_LCURLY) { /* Named enum */ if (CurTok.Tok == TOK_IDENT) { /* Find an entry with this name */ Entry = FindTagSym (CurTok.Ident); if (Entry) { if (SymIsLocal (Entry) && (Entry->Flags & SC_ENUM) == 0) { Error ("Symbol `%s' is already different kind", Entry->Name); } } else { /* Insert entry into table ### */ } /* Skip the identifier */ NextToken (); } else { Error ("Identifier expected"); } } /* Remember we have an extra type decl */ D->Flags |= DS_EXTRA_TYPE; /* Parse the enum decl */ ParseEnumDecl (); D->Type[0].C = T_INT; D->Type[1].C = T_END; break; case TOK_IDENT: Entry = FindSym (CurTok.Ident); if (Entry && SymIsTypeDef (Entry)) { /* It's a typedef */ NextToken (); TypeCopy (D->Type, Entry->Type); break; } /* FALL THROUGH */ default: if (Default < 0) { Error ("Type expected"); D->Type[0].C = T_INT; D->Type[1].C = T_END; } else { D->Flags |= DS_DEF_TYPE; D->Type[0].C = (TypeCode) Default; D->Type[1].C = T_END; } break; } /* There may also be qualifiers *after* the initial type */ D->Type[0].C |= (Qualifiers | OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE)); } static Type* ParamTypeCvt (Type* T) /* If T is an array, convert it to a pointer else do nothing. Return the * resulting type. */ { if (IsTypeArray (T)) { T->C = T_PTR; } return T; } static void ParseOldStyleParamList (FuncDesc* F) /* Parse an old style (K&R) parameter list */ { /* Some fix point tokens that are used for error recovery */ static const token_t TokenList[] = { TOK_COMMA, TOK_RPAREN, TOK_SEMI }; /* Parse params */ while (CurTok.Tok != TOK_RPAREN) { /* List of identifiers expected */ if (CurTok.Tok == TOK_IDENT) { /* Create a symbol table entry with type int */ AddLocalSym (CurTok.Ident, type_int, SC_AUTO | SC_PARAM | SC_DEF | SC_DEFTYPE, 0); /* Count arguments */ ++F->ParamCount; /* Skip the identifier */ NextToken (); } else { /* Not a parameter name */ Error ("Identifier expected"); /* Try some smart error recovery */ SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0])); } /* Check for more parameters */ if (CurTok.Tok == TOK_COMMA) { NextToken (); } else { break; } } /* Skip right paren. We must explicitly check for one here, since some of * the breaks above bail out without checking. */ ConsumeRParen (); /* An optional list of type specifications follows */ while (CurTok.Tok != TOK_LCURLY) { DeclSpec Spec; /* Read the declaration specifier */ ParseDeclSpec (&Spec, SC_AUTO, T_INT); /* We accept only auto and register as storage class specifiers, but * we ignore all this, since we use auto anyway. */ if ((Spec.StorageClass & SC_AUTO) == 0 && (Spec.StorageClass & SC_REGISTER) == 0) { Error ("Illegal storage class"); } /* Parse a comma separated variable list */ while (1) { Declaration Decl; /* Read the parameter */ ParseDecl (&Spec, &Decl, DM_NEED_IDENT); if (Decl.Ident[0] != '\0') { /* We have a name given. Search for the symbol */ SymEntry* Sym = FindLocalSym (Decl.Ident); if (Sym) { /* Check if we already changed the type for this * parameter */ if (Sym->Flags & SC_DEFTYPE) { /* Found it, change the default type to the one given */ ChangeSymType (Sym, ParamTypeCvt (Decl.Type)); /* Reset the "default type" flag */ Sym->Flags &= ~SC_DEFTYPE; } else { /* Type has already been changed */ Error ("Redefinition for parameter `%s'", Sym->Name); } } else { Error ("Unknown identifier: `%s'", Decl.Ident); } } if (CurTok.Tok == TOK_COMMA) { NextToken (); } else { break; } } /* Variable list must be semicolon terminated */ ConsumeSemi (); } } static void ParseAnsiParamList (FuncDesc* F) /* Parse a new style (ANSI) parameter list */ { /* Parse params */ while (CurTok.Tok != TOK_RPAREN) { DeclSpec Spec; Declaration Decl; SymEntry* Sym; /* Allow an ellipsis as last parameter */ if (CurTok.Tok == TOK_ELLIPSIS) { NextToken (); F->Flags |= FD_VARIADIC; break; } /* Read the declaration specifier */ ParseDeclSpec (&Spec, SC_AUTO, T_INT); /* We accept only auto and register as storage class specifiers */ if ((Spec.StorageClass & SC_AUTO) == SC_AUTO) { Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF; } else if ((Spec.StorageClass & SC_REGISTER) == SC_REGISTER) { Spec.StorageClass = SC_REGISTER | SC_STATIC | SC_PARAM | SC_DEF; } else { Error ("Illegal storage class"); Spec.StorageClass = SC_AUTO | SC_PARAM | SC_DEF; } /* Allow parameters without a name, but remember if we had some to * eventually print an error message later. */ ParseDecl (&Spec, &Decl, DM_ACCEPT_IDENT); if (Decl.Ident[0] == '\0') { /* Unnamed symbol. Generate a name that is not user accessible, * then handle the symbol normal. */ AnonName (Decl.Ident, "param"); F->Flags |= FD_UNNAMED_PARAMS; /* Clear defined bit on nonames */ Decl.StorageClass &= ~SC_DEF; } /* Parse attributes for this parameter */ ParseAttribute (&Decl); /* Create a symbol table entry */ Sym = AddLocalSym (Decl.Ident, ParamTypeCvt (Decl.Type), Decl.StorageClass, 0); /* Add attributes if we have any */ SymUseAttr (Sym, &Decl); /* If the parameter is a struct or union, emit a warning */ if (IsClassStruct (Decl.Type)) { if (IS_Get (&WarnStructParam)) { Warning ("Passing struct by value for parameter `%s'", Decl.Ident); } } /* Count arguments */ ++F->ParamCount; /* Check for more parameters */ if (CurTok.Tok == TOK_COMMA) { NextToken (); } else { break; } } /* Skip right paren. We must explicitly check for one here, since some of * the breaks above bail out without checking. */ ConsumeRParen (); } static FuncDesc* ParseFuncDecl (void) /* Parse the argument list of a function. */ { unsigned Offs; SymEntry* Sym; /* Create a new function descriptor */ FuncDesc* F = NewFuncDesc (); /* Enter a new lexical level */ EnterFunctionLevel (); /* Check for several special parameter lists */ if (CurTok.Tok == TOK_RPAREN) { /* Parameter list is empty */ F->Flags |= (FD_EMPTY | FD_VARIADIC); } else if (CurTok.Tok == TOK_VOID && NextTok.Tok == TOK_RPAREN) { /* Parameter list declared as void */ NextToken (); F->Flags |= FD_VOID_PARAM; } else if (CurTok.Tok == TOK_IDENT && (NextTok.Tok == TOK_COMMA || NextTok.Tok == TOK_RPAREN)) { /* If the identifier is a typedef, we have a new style parameter list, * if it's some other identifier, it's an old style parameter list. */ Sym = FindSym (CurTok.Ident); if (Sym == 0 || !SymIsTypeDef (Sym)) { /* Old style (K&R) function. */ F->Flags |= FD_OLDSTYLE; } } /* Parse params */ if ((F->Flags & FD_OLDSTYLE) == 0) { /* New style function */ ParseAnsiParamList (F); } else { /* Old style function */ ParseOldStyleParamList (F); } /* Remember the last function parameter. We need it later for several * purposes, for example when passing stuff to fastcall functions. Since * more symbols are added to the table, it is easier if we remember it * now, since it is currently the last entry in the symbol table. */ F->LastParam = GetSymTab()->SymTail; /* Assign offsets. If the function has a variable parameter list, * there's one additional byte (the arg size). */ Offs = (F->Flags & FD_VARIADIC)? 1 : 0; Sym = F->LastParam; while (Sym) { unsigned Size = CheckedSizeOf (Sym->Type); if (SymIsRegVar (Sym)) { Sym->V.R.SaveOffs = Offs; } else { Sym->V.Offs = Offs; } Offs += Size; F->ParamSize += Size; Sym = Sym->PrevSym; } /* Leave the lexical level remembering the symbol tables */ RememberFunctionLevel (F); /* Return the function descriptor */ return F; } static void Declarator (const DeclSpec* Spec, Declaration* D, declmode_t Mode) /* Recursively process declarators. Build a type array in reverse order. */ { /* Read optional function or pointer qualifiers. These modify the * identifier or token to the right. For convenience, we allow the fastcall * qualifier also for pointers here. If it is a pointer-to-function, the * qualifier will later be transfered to the function itself. If it's a * pointer to something else, it will be flagged as an error. */ TypeCode Qualifiers = OptionalQualifiers (T_QUAL_ADDRSIZE | T_QUAL_FASTCALL); /* Pointer to something */ if (CurTok.Tok == TOK_STAR) { /* Skip the star */ NextToken (); /* Allow const, restrict and volatile qualifiers */ Qualifiers |= OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE | T_QUAL_RESTRICT); /* Parse the type, the pointer points to */ Declarator (Spec, D, Mode); /* Add the type */ AddTypeToDeclaration (D, T_PTR | Qualifiers); return; } if (CurTok.Tok == TOK_LPAREN) { NextToken (); Declarator (Spec, D, Mode); ConsumeRParen (); } else { /* Things depend on Mode now: * - Mode == DM_NEED_IDENT means: * we *must* have a type and a variable identifer. * - Mode == DM_NO_IDENT means: * we must have a type but no variable identifer * (if there is one, it's not read). * - Mode == DM_ACCEPT_IDENT means: * we *may* have an identifier. If there is an identifier, * it is read, but it is no error, if there is none. */ if (Mode == DM_NO_IDENT) { D->Ident[0] = '\0'; } else if (CurTok.Tok == TOK_IDENT) { strcpy (D->Ident, CurTok.Ident); NextToken (); } else { if (Mode == DM_NEED_IDENT) { Error ("Identifier expected"); } D->Ident[0] = '\0'; } } while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN) { if (CurTok.Tok == TOK_LPAREN) { /* Function declaration */ FuncDesc* F; /* Skip the opening paren */ NextToken (); /* Parse the function declaration */ F = ParseFuncDecl (); /* We cannot specify fastcall for variadic functions */ if ((F->Flags & FD_VARIADIC) && (Qualifiers & T_QUAL_FASTCALL)) { Error ("Variadic functions cannot be `__fastcall__'"); Qualifiers &= ~T_QUAL_FASTCALL; } /* Add the function type. Be sure to bounds check the type buffer */ NeedTypeSpace (D, 1); D->Type[D->Index].C = T_FUNC | Qualifiers; D->Type[D->Index].A.P = F; ++D->Index; /* Qualifiers now used */ Qualifiers = T_QUAL_NONE; } else { /* Array declaration. */ long Size = UNSPECIFIED; /* We cannot have any qualifiers for an array */ if (Qualifiers != T_QUAL_NONE) { Error ("Invalid qualifiers for array"); Qualifiers = T_QUAL_NONE; } /* Skip the left bracket */ NextToken (); /* Read the size if it is given */ if (CurTok.Tok != TOK_RBRACK) { ExprDesc Expr; ConstAbsIntExpr (hie1, &Expr); if (Expr.IVal <= 0) { if (D->Ident[0] != '\0') { Error ("Size of array `%s' is invalid", D->Ident); } else { Error ("Size of array is invalid"); } Expr.IVal = 1; } Size = Expr.IVal; } /* Skip the right bracket */ ConsumeRBrack (); /* Add the array type with the size to the type */ NeedTypeSpace (D, 1); D->Type[D->Index].C = T_ARRAY; D->Type[D->Index].A.L = Size; ++D->Index; } } /* If we have remaining qualifiers, flag them as invalid */ if (Qualifiers & T_QUAL_NEAR) { Error ("Invalid `__near__' qualifier"); } if (Qualifiers & T_QUAL_FAR) { Error ("Invalid `__far__' qualifier"); } if (Qualifiers & T_QUAL_FASTCALL) { Error ("Invalid `__fastcall__' qualifier"); } if (Qualifiers & T_QUAL_CDECL) { Error ("Invalid `__cdecl__' qualifier"); } } /*****************************************************************************/ /* code */ /*****************************************************************************/ Type* ParseType (Type* T) /* Parse a complete type specification */ { DeclSpec Spec; Declaration Decl; /* Get a type without a default */ InitDeclSpec (&Spec); ParseTypeSpec (&Spec, -1, T_QUAL_NONE); /* Parse additional declarators */ ParseDecl (&Spec, &Decl, DM_NO_IDENT); /* Copy the type to the target buffer */ TypeCopy (T, Decl.Type); /* Return a pointer to the target buffer */ return T; } void ParseDecl (const DeclSpec* Spec, Declaration* D, declmode_t Mode) /* Parse a variable, type or function declaration */ { /* Initialize the Declaration struct */ InitDeclaration (D); /* Get additional declarators and the identifier */ Declarator (Spec, D, Mode); /* Add the base type. */ NeedTypeSpace (D, TypeLen (Spec->Type) + 1); /* Bounds check */ TypeCopy (D->Type + D->Index, Spec->Type); /* Use the storage class from the declspec */ D->StorageClass = Spec->StorageClass; /* Do several fixes on qualifiers */ FixQualifiers (D->Type); /* If we have a function, add a special storage class */ if (IsTypeFunc (D->Type)) { D->StorageClass |= SC_FUNC; } /* Parse attributes for this declaration */ ParseAttribute (D); /* Check several things for function or function pointer types */ if (IsTypeFunc (D->Type) || IsTypeFuncPtr (D->Type)) { /* A function. Check the return type */ Type* RetType = GetFuncReturn (D->Type); /* Functions may not return functions or arrays */ if (IsTypeFunc (RetType)) { Error ("Functions are not allowed to return functions"); } else if (IsTypeArray (RetType)) { Error ("Functions are not allowed to return arrays"); } /* The return type must not be qualified */ if (GetQualifier (RetType) != T_QUAL_NONE && RetType[1].C == T_END) { if (GetType (RetType) == T_TYPE_VOID) { /* A qualified void type is always an error */ Error ("function definition has qualified void return type"); } else { /* For others, qualifiers are ignored */ Warning ("type qualifiers ignored on function return type"); RetType[0].C = UnqualifiedType (RetType[0].C); } } /* Warn about an implicit int return in the function */ if ((Spec->Flags & DS_DEF_TYPE) != 0 && RetType[0].C == T_INT && RetType[1].C == T_END) { /* Function has an implicit int return. Output a warning if we don't * have the C89 standard enabled explicitly. */ if (IS_Get (&Standard) >= STD_C99) { Warning ("Implicit `int' return type is an obsolete feature"); } GetFuncDesc (D->Type)->Flags |= FD_OLDSTYLE_INTRET; } } /* For anthing that is not a function or typedef, check for an implicit * int declaration. */ if ((D->StorageClass & SC_FUNC) != SC_FUNC && (D->StorageClass & SC_TYPEMASK) != SC_TYPEDEF) { /* If the standard was not set explicitly to C89, print a warning * for variables with implicit int type. */ if ((Spec->Flags & DS_DEF_TYPE) != 0 && IS_Get (&Standard) >= STD_C99) { Warning ("Implicit `int' is an obsolete feature"); } } /* Check the size of the generated type */ if (!IsTypeFunc (D->Type) && !IsTypeVoid (D->Type)) { unsigned Size = SizeOf (D->Type); if (Size >= 0x10000) { if (D->Ident[0] != '\0') { Error ("Size of `%s' is invalid (0x%06X)", D->Ident, Size); } else { Error ("Invalid size in declaration (0x%06X)", Size); } } } } void ParseDeclSpec (DeclSpec* D, unsigned DefStorage, long DefType) /* Parse a declaration specification */ { TypeCode Qualifiers; /* Initialize the DeclSpec struct */ InitDeclSpec (D); /* There may be qualifiers *before* the storage class specifier */ Qualifiers = OptionalQualifiers (T_QUAL_CONST | T_QUAL_VOLATILE); /* Now get the storage class specifier for this declaration */ ParseStorageClass (D, DefStorage); /* Parse the type specifiers passing any initial type qualifiers */ ParseTypeSpec (D, DefType, Qualifiers); } void CheckEmptyDecl (const DeclSpec* D) /* Called after an empty type declaration (that is, a type declaration without * a variable). Checks if the declaration does really make sense and issues a * warning if not. */ { if ((D->Flags & DS_EXTRA_TYPE) == 0) { Warning ("Useless declaration"); } } static void SkipInitializer (unsigned BracesExpected) /* Skip the remainder of an initializer in case of errors. Try to be somewhat * smart so we don't have too many following errors. */ { while (CurTok.Tok != TOK_CEOF && CurTok.Tok != TOK_SEMI && BracesExpected > 0) { switch (CurTok.Tok) { case TOK_RCURLY: --BracesExpected; break; case TOK_LCURLY: ++BracesExpected; break; default: break; } NextToken (); } } static unsigned OpeningCurlyBraces (unsigned BracesNeeded) /* Accept any number of opening curly braces around an initialization, skip * them and return the number. If the number of curly braces is less than * BracesNeeded, issue a warning. */ { unsigned BraceCount = 0; while (CurTok.Tok == TOK_LCURLY) { ++BraceCount; NextToken (); } if (BraceCount < BracesNeeded) { Error ("`{' expected"); } return BraceCount; } static void ClosingCurlyBraces (unsigned BracesExpected) /* Accept and skip the given number of closing curly braces together with * an optional comma. Output an error messages, if the input does not contain * the expected number of braces. */ { while (BracesExpected) { if (CurTok.Tok == TOK_RCURLY) { NextToken (); } else if (CurTok.Tok == TOK_COMMA && NextTok.Tok == TOK_RCURLY) { NextToken (); NextToken (); } else { Error ("`}' expected"); return; } --BracesExpected; } } static void DefineData (ExprDesc* Expr) /* Output a data definition for the given expression */ { switch (ED_GetLoc (Expr)) { case E_LOC_ABS: /* Absolute: numeric address or const */ g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->IVal, 0); break; case E_LOC_GLOBAL: /* Global variable */ g_defdata (CF_EXTERNAL, Expr->Name, Expr->IVal); break; case E_LOC_STATIC: case E_LOC_LITERAL: /* Static variable or literal in the literal pool */ g_defdata (CF_STATIC, Expr->Name, Expr->IVal); break; case E_LOC_REGISTER: /* Register variable. Taking the address is usually not * allowed. */ if (IS_Get (&AllowRegVarAddr) == 0) { Error ("Cannot take the address of a register variable"); } g_defdata (CF_REGVAR, Expr->Name, Expr->IVal); break; case E_LOC_STACK: case E_LOC_PRIMARY: case E_LOC_EXPR: Error ("Non constant initializer"); break; default: Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr)); } } static void OutputBitFieldData (StructInitData* SI) /* Output bit field data */ { /* Ignore if we have no data */ if (SI->ValBits > 0) { /* Output the data */ g_defdata (CF_INT | CF_UNSIGNED | CF_CONST, SI->BitVal, 0); /* Clear the data from SI and account for the size */ SI->BitVal = 0; SI->ValBits = 0; SI->Offs += SIZEOF_INT; } } static void ParseScalarInitInternal (Type* T, ExprDesc* ED) /* Parse initializaton for scalar data types. This function will not output the * data but return it in ED. */ { /* Optional opening brace */ unsigned BraceCount = OpeningCurlyBraces (0); /* We warn if an initializer for a scalar contains braces, because this is * quite unusual and often a sign for some problem in the input. */ if (BraceCount > 0) { Warning ("Braces around scalar initializer"); } /* Get the expression and convert it to the target type */ ConstExpr (hie1, ED); TypeConversion (ED, T); /* Close eventually opening braces */ ClosingCurlyBraces (BraceCount); } static unsigned ParseScalarInit (Type* T) /* Parse initializaton for scalar data types. Return the number of data bytes. */ { ExprDesc ED; /* Parse initialization */ ParseScalarInitInternal (T, &ED); /* Output the data */ DefineData (&ED); /* Done */ return SizeOf (T); } static unsigned ParsePointerInit (Type* T) /* Parse initializaton for pointer data types. Return the number of data bytes. */ { /* Optional opening brace */ unsigned BraceCount = OpeningCurlyBraces (0); /* Expression */ ExprDesc ED; ConstExpr (hie1, &ED); TypeConversion (&ED, T); /* Output the data */ DefineData (&ED); /* Close eventually opening braces */ ClosingCurlyBraces (BraceCount); /* Done */ return SIZEOF_PTR; } static unsigned ParseArrayInit (Type* T, int AllowFlexibleMembers) /* Parse initializaton for arrays. Return the number of data bytes. */ { int Count; /* Get the array data */ Type* ElementType = GetElementType (T); unsigned ElementSize = CheckedSizeOf (ElementType); long ElementCount = GetElementCount (T); /* Special handling for a character array initialized by a literal */ if (IsTypeChar (ElementType) && (CurTok.Tok == TOK_SCONST || CurTok.Tok == TOK_WCSCONST || (CurTok.Tok == TOK_LCURLY && (NextTok.Tok == TOK_SCONST || NextTok.Tok == TOK_WCSCONST)))) { /* Char array initialized by string constant */ int NeedParen; /* If we initializer is enclosed in brackets, remember this fact and * skip the opening bracket. */ NeedParen = (CurTok.Tok == TOK_LCURLY); if (NeedParen) { NextToken (); } /* Translate into target charset */ TranslateLiteral (CurTok.SVal); /* If the array is one too small for the string literal, omit the * trailing zero. */ Count = GetLiteralSize (CurTok.SVal); if (ElementCount != UNSPECIFIED && ElementCount != FLEXIBLE && Count == ElementCount + 1) { /* Omit the trailing zero */ --Count; } /* Output the data */ g_defbytes (GetLiteralStr (CurTok.SVal), Count); /* Skip the string */ NextToken (); /* If the initializer was enclosed in curly braces, we need a closing * one. */ if (NeedParen) { ConsumeRCurly (); } } else { /* Curly brace */ ConsumeLCurly (); /* Initialize the array members */ Count = 0; while (CurTok.Tok != TOK_RCURLY) { /* Flexible array members may not be initialized within * an array (because the size of each element may differ * otherwise). */ ParseInitInternal (ElementType, 0); ++Count; if (CurTok.Tok != TOK_COMMA) break; NextToken (); } /* Closing curly braces */ ConsumeRCurly (); } if (ElementCount == UNSPECIFIED) { /* Number of elements determined by initializer */ SetElementCount (T, Count); ElementCount = Count; } else if (ElementCount == FLEXIBLE && AllowFlexibleMembers) { /* In non ANSI mode, allow initialization of flexible array * members. */ ElementCount = Count; } else if (Count < ElementCount) { g_zerobytes ((ElementCount - Count) * ElementSize); } else if (Count > ElementCount) { Error ("Too many initializers"); } return ElementCount * ElementSize; } static unsigned ParseStructInit (Type* T, int AllowFlexibleMembers) /* Parse initialization of a struct or union. Return the number of data bytes. */ { SymEntry* Entry; SymTable* Tab; StructInitData SI; /* Consume the opening curly brace */ ConsumeLCurly (); /* Get a pointer to the struct entry from the type */ Entry = GetSymEntry (T); /* Get the size of the struct from the symbol table entry */ SI.Size = Entry->V.S.Size; /* Check if this struct definition has a field table. If it doesn't, it * is an incomplete definition. */ Tab = Entry->V.S.SymTab; if (Tab == 0) { Error ("Cannot initialize variables with incomplete type"); /* Try error recovery */ SkipInitializer (1); /* Nothing initialized */ return 0; } /* Get a pointer to the list of symbols */ Entry = Tab->SymHead; /* Initialize fields */ SI.Offs = 0; SI.BitVal = 0; SI.ValBits = 0; while (CurTok.Tok != TOK_RCURLY) { /* */ if (Entry == 0) { Error ("Too many initializers"); SkipInitializer (1); return SI.Offs; } /* Parse initialization of one field. Bit-fields need a special * handling. */ if (SymIsBitField (Entry)) { ExprDesc ED; unsigned Val; unsigned Shift; /* Calculate the bitmask from the bit-field data */ unsigned Mask = (1U << Entry->V.B.BitWidth) - 1U; /* Safety ... */ CHECK (Entry->V.B.Offs * CHAR_BITS + Entry->V.B.BitOffs == SI.Offs * CHAR_BITS + SI.ValBits); /* This may be an anonymous bit-field, in which case it doesn't * have an initializer. */ if (IsAnonName (Entry->Name)) { /* Account for the data and output it if we have a full word */ SI.ValBits += Entry->V.B.BitWidth; CHECK (SI.ValBits <= INT_BITS); if (SI.ValBits == INT_BITS) { OutputBitFieldData (&SI); } goto NextMember; } else { /* Read the data, check for a constant integer, do a range * check. */ ParseScalarInitInternal (type_uint, &ED); if (!ED_IsConstAbsInt (&ED)) { Error ("Constant initializer expected"); ED_MakeConstAbsInt (&ED, 1); } if (ED.IVal > (long) Mask) { Warning ("Truncating value in bit-field initializer"); ED.IVal &= (long) Mask; } Val = (unsigned) ED.IVal; } /* Add the value to the currently stored bit-field value */ Shift = (Entry->V.B.Offs - SI.Offs) * CHAR_BITS + Entry->V.B.BitOffs; SI.BitVal |= (Val << Shift); /* Account for the data and output it if we have a full word */ SI.ValBits += Entry->V.B.BitWidth; CHECK (SI.ValBits <= INT_BITS); if (SI.ValBits == INT_BITS) { OutputBitFieldData (&SI); } } else { /* Standard member. We should never have stuff from a * bit-field left */ CHECK (SI.ValBits == 0); /* Flexible array members may only be initialized if they are * the last field (or part of the last struct field). */ SI.Offs += ParseInitInternal (Entry->Type, AllowFlexibleMembers && Entry->NextSym == 0); } /* More initializers? */ if (CurTok.Tok != TOK_COMMA) { break; } /* Skip the comma */ NextToken (); NextMember: /* Next member. For unions, only the first one can be initialized */ if (IsTypeUnion (T)) { /* Union */ Entry = 0; } else { /* Struct */ Entry = Entry->NextSym; } } /* Consume the closing curly brace */ ConsumeRCurly (); /* If we have data from a bit-field left, output it now */ OutputBitFieldData (&SI); /* If there are struct fields left, reserve additional storage */ if (SI.Offs < SI.Size) { g_zerobytes (SI.Size - SI.Offs); SI.Offs = SI.Size; } /* Return the actual number of bytes initialized. This number may be * larger than sizeof (Struct) if flexible array members are present and * were initialized (possible in non ANSI mode). */ return SI.Offs; } static unsigned ParseVoidInit (void) /* Parse an initialization of a void variable (special cc65 extension). * Return the number of bytes initialized. */ { ExprDesc Expr; unsigned Size; /* Opening brace */ ConsumeLCurly (); /* Allow an arbitrary list of values */ Size = 0; do { ConstExpr (hie1, &Expr); switch (UnqualifiedType (Expr.Type[0].C)) { case T_SCHAR: case T_UCHAR: if (ED_IsConstAbsInt (&Expr)) { /* Make it byte sized */ Expr.IVal &= 0xFF; } DefineData (&Expr); Size += SIZEOF_CHAR; break; case T_SHORT: case T_USHORT: case T_INT: case T_UINT: case T_PTR: case T_ARRAY: if (ED_IsConstAbsInt (&Expr)) { /* Make it word sized */ Expr.IVal &= 0xFFFF; } DefineData (&Expr); Size += SIZEOF_INT; break; case T_LONG: case T_ULONG: if (ED_IsConstAbsInt (&Expr)) { /* Make it dword sized */ Expr.IVal &= 0xFFFFFFFF; } DefineData (&Expr); Size += SIZEOF_LONG; break; default: Error ("Illegal type in initialization"); break; } if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } while (CurTok.Tok != TOK_RCURLY); /* Closing brace */ ConsumeRCurly (); /* Return the number of bytes initialized */ return Size; } static unsigned ParseInitInternal (Type* T, int AllowFlexibleMembers) /* Parse initialization of variables. Return the number of data bytes. */ { switch (UnqualifiedType (T->C)) { case T_SCHAR: case T_UCHAR: case T_SHORT: case T_USHORT: case T_INT: case T_UINT: case T_LONG: case T_ULONG: case T_FLOAT: case T_DOUBLE: return ParseScalarInit (T); case T_PTR: return ParsePointerInit (T); case T_ARRAY: return ParseArrayInit (T, AllowFlexibleMembers); case T_STRUCT: case T_UNION: return ParseStructInit (T, AllowFlexibleMembers); case T_VOID: if (IS_Get (&Standard) == STD_CC65) { /* Special cc65 extension in non ANSI mode */ return ParseVoidInit (); } /* FALLTHROUGH */ default: Error ("Illegal type"); return SIZEOF_CHAR; } } unsigned ParseInit (Type* T) /* Parse initialization of variables. Return the number of data bytes. */ { /* Parse the initialization. Flexible array members can only be initialized * in cc65 mode. */ unsigned Size = ParseInitInternal (T, IS_Get (&Standard) == STD_CC65); /* The initialization may not generate code on global level, because code * outside function scope will never get executed. */ if (HaveGlobalCode ()) { Error ("Non constant initializers"); RemoveGlobalCode (); } /* Return the size needed for the initialization */ return Size; }
839
./cc65/src/cc65/litpool.c
/*****************************************************************************/ /* */ /* litpool.c */ /* */ /* Literal string handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "attrib.h" #include "check.h" #include "coll.h" #include "tgttrans.h" #include "xmalloc.h" /* cc65 */ #include "asmlabel.h" #include "codegen.h" #include "error.h" #include "global.h" #include "litpool.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Definition of a literal */ struct Literal { unsigned Label; /* Asm label for this literal */ int RefCount; /* Reference count */ int Output; /* True if output has been generated */ StrBuf Data; /* Literal data */ }; /* Definition of the literal pool */ struct LiteralPool { struct SymEntry* Func; /* Function that owns the pool */ Collection WritableLiterals; /* Writable literals in the pool */ Collection ReadOnlyLiterals; /* Readonly literals in the pool */ }; /* The global and current literal pool */ static LiteralPool* GlobalPool = 0; static LiteralPool* LP = 0; /* Stack that contains the nested literal pools. Since TOS is in LiteralPool * and functions aren't nested in C, the maximum depth is 1. I'm using a * collection anyway, so the code is prepared for nested functions or * whatever. */ static Collection LPStack = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* struct Literal */ /*****************************************************************************/ static Literal* NewLiteral (const void* Buf, unsigned Len) /* Create a new literal and return it */ { /* Allocate memory */ Literal* L = xmalloc (sizeof (*L)); /* Initialize the fields */ L->Label = GetLocalLabel (); L->RefCount = 0; L->Output = 0; SB_Init (&L->Data); SB_AppendBuf (&L->Data, Buf, Len); /* Return the new literal */ return L; } static void FreeLiteral (Literal* L) /* Free a literal */ { /* Free the literal data */ SB_Done (&L->Data); /* Free the structure itself */ xfree (L); } static void OutputLiteral (Literal* L) /* Output one literal to the currently active data segment */ { /* Translate the literal into the target charset */ TranslateLiteral (L); /* Define the label for the literal */ g_defdatalabel (L->Label); /* Output the literal data */ g_defbytes (SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)); /* Mark the literal as output */ L->Output = 1; } Literal* UseLiteral (Literal* L) /* Increase the reference counter for the literal and return it */ { /* Increase the reference count */ ++L->RefCount; /* If --local-strings was given, immediately output the literal */ if (IS_Get (&LocalStrings)) { /* Switch to the proper data segment */ if (IS_Get (&WritableStrings)) { g_usedata (); } else { g_userodata (); } /* Output the literal */ OutputLiteral (L); } /* Return the literal */ return L; } void ReleaseLiteral (Literal* L) /* Decrement the reference counter for the literal */ { --L->RefCount; CHECK (L->RefCount >= 0); } void TranslateLiteral (Literal* L) /* Translate a literal into the target charset. */ { TgtTranslateBuf (SB_GetBuf (&L->Data), SB_GetLen (&L->Data)); } unsigned GetLiteralLabel (const Literal* L) /* Return the asm label for a literal */ { return L->Label; } const char* GetLiteralStr (const Literal* L) /* Return the data for a literal as pointer to char */ { return SB_GetConstBuf (&L->Data); } const StrBuf* GetLiteralStrBuf (const Literal* L) /* Return the data for a literal as pointer to the string buffer */ { return &L->Data; } unsigned GetLiteralSize (const Literal* L) /* Get the size of a literal string */ { return SB_GetLen (&L->Data); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static LiteralPool* NewLiteralPool (struct SymEntry* Func) /* Create a new literal pool and return it */ { /* Allocate memory */ LiteralPool* LP = xmalloc (sizeof (*LP)); /* Initialize the fields */ LP->Func = Func; InitCollection (&LP->WritableLiterals); InitCollection (&LP->ReadOnlyLiterals); /* Return the new pool */ return LP; } static void FreeLiteralPool (LiteralPool* LP) /* Free a LiteralPool structure */ { /* Free the collections contained within the struct */ DoneCollection (&LP->WritableLiterals); DoneCollection (&LP->ReadOnlyLiterals); /* Free the struct itself */ xfree (LP); } static int Compare (void* Data attribute ((unused)), const void* Left, const void* Right) /* Compare function used when sorting the literal pool */ { /* Larger strings are considered "smaller" */ return (int) GetLiteralSize (Right) - (int) GetLiteralSize (Left); } void InitLiteralPool (void) /* Initialize the literal pool */ { /* Create the global literal pool */ GlobalPool = LP = NewLiteralPool (0); } void PushLiteralPool (struct SymEntry* Func) /* Push the current literal pool onto the stack and create a new one */ { /* We must have a literal pool to push! */ PRECONDITION (LP != 0); /* Push the old pool */ CollAppend (&LPStack, LP); /* Create a new one */ LP = NewLiteralPool (Func); } LiteralPool* PopLiteralPool (void) /* Pop the last literal pool from TOS and activate it. Return the old * literal pool. */ { /* Remember the current literal pool */ LiteralPool* Old = LP; /* Pop one from stack */ LP = CollPop (&LPStack); /* Return the old one */ return Old; } static void MoveLiterals (Collection* Source, Collection* Target) /* Move referenced literals from Source to Target, delete unreferenced ones */ { unsigned I; /* Move referenced literals, remove unreferenced ones */ for (I = 0; I < CollCount (Source); ++I) { /* Get the literal */ Literal* L = CollAt (Source, I); /* If it is referenced and not output, add it to the Target pool, * otherwise free it */ if (L->RefCount && !L->Output) { CollAppend (Target, L); } else { FreeLiteral (L); } } } void MoveLiteralPool (LiteralPool* LocalPool) /* Move all referenced literals in LocalPool to the global literal pool. This * function will free LocalPool after moving the used string literals. */ { /* Move the literals */ MoveLiterals (&LocalPool->WritableLiterals, &GlobalPool->WritableLiterals); MoveLiterals (&LocalPool->ReadOnlyLiterals, &GlobalPool->ReadOnlyLiterals); /* Free the local literal pool */ FreeLiteralPool (LocalPool); } static void OutputWritableLiterals (Collection* Literals) /* Output the given writable literals */ { unsigned I; /* If nothing there, exit... */ if (CollCount (Literals) == 0) { return; } /* Switch to the correct segment */ g_usedata (); /* Emit all literals that have a reference */ for (I = 0; I < CollCount (Literals); ++I) { /* Get a pointer to the literal */ Literal* L = CollAtUnchecked (Literals, I); /* Output this one, if it has references and wasn't already output */ if (L->RefCount > 0 && !L->Output) { OutputLiteral (L); } } } static void OutputReadOnlyLiterals (Collection* Literals) /* Output the given readonly literals merging (even partial) duplicates */ { unsigned I; /* If nothing there, exit... */ if (CollCount (Literals) == 0) { return; } /* Switch to the correct segment */ g_userodata (); /* Sort the literal pool by literal size. Larger strings go first */ CollSort (Literals, Compare, 0); /* Emit all literals that have a reference */ for (I = 0; I < CollCount (Literals); ++I) { unsigned J; Literal* C; /* Get the next literal */ Literal* L = CollAt (Literals, I); /* Ignore it, if it doesn't have references or was already output */ if (L->RefCount == 0 || L->Output) { continue; } /* Translate the literal into the target charset */ TranslateLiteral (L); /* Check if this literal is part of another one. Since the literals * are sorted by size (larger ones first), it can only be part of a * literal with a smaller index. * Beware: Only check literals that have actually been referenced. */ C = 0; for (J = 0; J < I; ++J) { const void* D; /* Get a pointer to the compare literal */ Literal* L2 = CollAt (Literals, J); /* Ignore literals that have no reference */ if (L2->RefCount == 0) { continue; } /* Get a pointer to the data */ D = SB_GetConstBuf (&L2->Data) + SB_GetLen (&L2->Data) - SB_GetLen (&L->Data); /* Compare the data */ if (memcmp (D, SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)) == 0) { /* Remember the literal and terminate the loop */ C = L2; break; } } /* Check if we found a match */ if (C != 0) { /* This literal is part of a longer literal, merge them */ g_aliasdatalabel (L->Label, C->Label, GetLiteralSize (C) - GetLiteralSize (L)); } else { /* Define the label for the literal */ g_defdatalabel (L->Label); /* Output the literal data */ g_defbytes (SB_GetConstBuf (&L->Data), SB_GetLen (&L->Data)); } /* Mark the literal */ L->Output = 1; } } void OutputLiteralPool (void) /* Output the global literal pool */ { /* Output both sorts of literals */ OutputWritableLiterals (&GlobalPool->WritableLiterals); OutputReadOnlyLiterals (&GlobalPool->ReadOnlyLiterals); } Literal* AddLiteral (const char* S) /* Add a literal string to the literal pool. Return the literal. */ { return AddLiteralBuf (S, strlen (S) + 1); } Literal* AddLiteralBuf (const void* Buf, unsigned Len) /* Add a buffer containing a literal string to the literal pool. Return the * literal. */ { /* Create a new literal */ Literal* L = NewLiteral (Buf, Len); /* Add the literal to the correct pool */ if (IS_Get (&WritableStrings)) { CollAppend (&LP->WritableLiterals, L); } else { CollAppend (&LP->ReadOnlyLiterals, L); } /* Return the new literal */ return L; } Literal* AddLiteralStr (const StrBuf* S) /* Add a literal string to the literal pool. Return the literal. */ { return AddLiteralBuf (SB_GetConstBuf (S), SB_GetLen (S)); }
840
./cc65/src/cc65/main.c
/*****************************************************************************/ /* */ /* main.c */ /* */ /* cc65 main program */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> /* common */ #include "abend.h" #include "chartype.h" #include "cmdline.h" #include "cpu.h" #include "debugflag.h" #include "fname.h" #include "mmodel.h" #include "print.h" #include "segnames.h" #include "strbuf.h" #include "target.h" #include "tgttrans.h" #include "version.h" #include "xmalloc.h" /* cc65 */ #include "asmcode.h" #include "compile.h" #include "codeopt.h" #include "error.h" #include "global.h" #include "incpath.h" #include "input.h" #include "macrotab.h" #include "output.h" #include "scanner.h" #include "segments.h" #include "standard.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Usage (void) /* Print usage information to stderr */ { printf ("Usage: %s [options] file\n" "Short options:\n" " -Cl\t\t\t\tMake local variables static\n" " -Dsym[=defn]\t\t\tDefine a symbol\n" " -E\t\t\t\tStop after the preprocessing stage\n" " -I dir\t\t\tSet an include directory search path\n" " -O\t\t\t\tOptimize code\n" " -Oi\t\t\t\tOptimize code, inline more code\n" " -Or\t\t\t\tEnable register variables\n" " -Os\t\t\t\tInline some known functions\n" " -T\t\t\t\tInclude source as comment\n" " -V\t\t\t\tPrint the compiler version number\n" " -W warning[,...]\t\tSuppress warnings\n" " -d\t\t\t\tDebug mode\n" " -g\t\t\t\tAdd debug info to object file\n" " -h\t\t\t\tHelp (this text)\n" " -j\t\t\t\tDefault characters are signed\n" " -mm model\t\t\tSet the memory model\n" " -o name\t\t\tName the output file\n" " -r\t\t\t\tEnable register variables\n" " -t sys\t\t\tSet the target system\n" " -v\t\t\t\tIncrease verbosity\n" "\n" "Long options:\n" " --add-source\t\t\tInclude source as comment\n" " --bss-name seg\t\tSet the name of the BSS segment\n" " --check-stack\t\t\tGenerate stack overflow checks\n" " --code-name seg\t\tSet the name of the CODE segment\n" " --codesize x\t\t\tAccept larger code by factor x\n" " --cpu type\t\t\tSet cpu type (6502, 65c02)\n" " --create-dep name\t\tCreate a make dependency file\n" " --create-full-dep name\tCreate a full make dependency file\n" " --data-name seg\t\tSet the name of the DATA segment\n" " --debug\t\t\tDebug mode\n" " --debug-info\t\t\tAdd debug info to object file\n" " --debug-opt name\t\tDebug optimization steps\n" " --dep-target target\t\tUse this dependency target\n" " --disable-opt name\t\tDisable an optimization step\n" " --enable-opt name\t\tEnable an optimization step\n" " --help\t\t\tHelp (this text)\n" " --include-dir dir\t\tSet an include directory search path\n" " --list-opt-steps\t\tList all optimizer steps and exit\n" " --list-warnings\t\tList available warning types for -W\n" " --local-strings\t\tEmit string literals immediately\n" " --memory-model model\t\tSet the memory model\n" " --register-space b\t\tSet space available for register variables\n" " --register-vars\t\tEnable register variables\n" " --rodata-name seg\t\tSet the name of the RODATA segment\n" " --signed-chars\t\tDefault characters are signed\n" " --standard std\t\tLanguage standard (c89, c99, cc65)\n" " --static-locals\t\tMake local variables static\n" " --target sys\t\t\tSet the target system\n" " --verbose\t\t\tIncrease verbosity\n" " --version\t\t\tPrint the compiler version number\n" " --writable-strings\t\tMake string literals writable\n", ProgName); } static void cbmsys (const char* sys) /* Define a CBM system */ { DefineNumericMacro ("__CBM__", 1); DefineNumericMacro (sys, 1); } static void SetSys (const char* Sys) /* Define a target system */ { switch (Target = FindTarget (Sys)) { case TGT_NONE: break; case TGT_MODULE: AbEnd ("Cannot use `module' as a target for the compiler"); break; case TGT_ATARI: DefineNumericMacro ("__ATARI__", 1); break; case TGT_ATARIXL: DefineNumericMacro ("__ATARI__", 1); DefineNumericMacro ("__ATARIXL__", 1); break; case TGT_C16: cbmsys ("__C16__"); break; case TGT_C64: cbmsys ("__C64__"); break; case TGT_VIC20: cbmsys ("__VIC20__"); break; case TGT_C128: cbmsys ("__C128__"); break; case TGT_PLUS4: cbmsys ("__PLUS4__"); break; case TGT_CBM510: cbmsys ("__CBM510__"); break; case TGT_CBM610: cbmsys ("__CBM610__"); break; case TGT_PET: cbmsys ("__PET__"); break; case TGT_BBC: DefineNumericMacro ("__BBC__", 1); break; case TGT_APPLE2: DefineNumericMacro ("__APPLE2__", 1); break; case TGT_APPLE2ENH: DefineNumericMacro ("__APPLE2__", 1); DefineNumericMacro ("__APPLE2ENH__", 1); break; case TGT_GEOS_CBM: /* Do not handle as a CBM system */ DefineNumericMacro ("__GEOS__", 1); DefineNumericMacro ("__GEOS_CBM__", 1); break; case TGT_GEOS_APPLE: DefineNumericMacro ("__GEOS__", 1); DefineNumericMacro ("__GEOS_APPLE__", 1); break; case TGT_LUNIX: DefineNumericMacro ("__LUNIX__", 1); break; case TGT_ATMOS: DefineNumericMacro ("__ATMOS__", 1); break; case TGT_NES: DefineNumericMacro ("__NES__", 1); break; case TGT_SUPERVISION: DefineNumericMacro ("__SUPERVISION__", 1); break; case TGT_LYNX: DefineNumericMacro ("__LYNX__", 1); break; case TGT_SIM6502: DefineNumericMacro ("__SIM6502__", 1); break; case TGT_SIM65C02: DefineNumericMacro ("__SIM65C02__", 1); break; default: AbEnd ("Unknown target system type %d", Target); } /* Initialize the translation tables for the target system */ TgtTranslateInit (); } static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name) /* Handle an option that remembers a file name for later */ { /* Cannot have the option twice */ if (SB_NotEmpty (Name)) { AbEnd ("Cannot use option `%s' twice", Opt); } /* Remember the file name for later */ SB_CopyStr (Name, Arg); SB_Terminate (Name); } static void DefineSym (const char* Def) /* Define a symbol on the command line */ { const char* P = Def; /* The symbol must start with a character or underline */ if (Def [0] != '_' && !IsAlpha (Def [0])) { InvDef (Def); } /* Check the symbol name */ while (IsAlNum (*P) || *P == '_') { ++P; } /* Do we have a value given? */ if (*P != '=') { if (*P != '\0') { InvDef (Def); } /* No value given. Define the macro with the value 1 */ DefineNumericMacro (Def, 1); } else { /* We have a value, P points to the '=' character. Since the argument * is const, create a copy and replace the '=' in the copy by a zero * terminator. */ char* Q; unsigned Len = strlen (Def)+1; char* S = (char*) xmalloc (Len); memcpy (S, Def, Len); Q = S + (P - Def); *Q++ = '\0'; /* Define this as a macro */ DefineTextMacro (S, Q); /* Release the allocated memory */ xfree (S); } } static void CheckSegName (const char* Seg) /* Abort if the given name is not a valid segment name */ { /* Print an error and abort if the name is not ok */ if (!ValidSegName (Seg)) { AbEnd ("Segment name `%s' is invalid", Seg); } } static void OptAddSource (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add source lines as comments in generated assembler file */ { AddSource = 1; } static void OptBssName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --bss-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ SetSegName (SEG_BSS, Arg); } static void OptCheckStack (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the --check-stack option */ { IS_Set (&CheckStack, 1); } static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --code-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ SetSegName (SEG_CODE, Arg); } static void OptCodeSize (const char* Opt, const char* Arg) /* Handle the --codesize option */ { unsigned Factor; char BoundsCheck; /* Numeric argument expected */ if (sscanf (Arg, "%u%c", &Factor, &BoundsCheck) != 1 || Factor < 10 || Factor > 1000) { AbEnd ("Argument for %s is invalid", Opt); } IS_Set (&CodeSizeFactor, Factor); } static void OptCreateDep (const char* Opt, const char* Arg) /* Handle the --create-dep option */ { FileNameOption (Opt, Arg, &DepName); } static void OptCreateFullDep (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --create-full-dep option */ { FileNameOption (Opt, Arg, &FullDepName); } static void OptCPU (const char* Opt, const char* Arg) /* Handle the --cpu option */ { /* Find the CPU from the given name */ CPU = FindCPU (Arg); if (CPU != CPU_6502 && CPU != CPU_6502X && CPU != CPU_65SC02 && CPU != CPU_65C02 && CPU != CPU_65816 && CPU != CPU_HUC6280) { AbEnd ("Invalid argument for %s: `%s'", Opt, Arg); } } static void OptDataName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --data-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ SetSegName (SEG_DATA, Arg); } static void OptDebug (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Compiler debug mode */ { ++Debug; } static void OptDebugInfo (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Add debug info to the object file */ { DebugInfo = 1; } static void OptDebugOpt (const char* Opt attribute ((unused)), const char* Arg) /* Debug optimization steps */ { char Buf [128]; char* Line; /* Open the file */ FILE* F = fopen (Arg, "r"); if (F == 0) { AbEnd ("Cannot open `%s': %s", Arg, strerror (errno)); } /* Read line by line, ignore empty lines and switch optimization * steps on/off. */ while (fgets (Buf, sizeof (Buf), F) != 0) { /* Remove trailing control chars. This will also remove the * trailing newline. */ unsigned Len = strlen (Buf); while (Len > 0 && IsControl (Buf[Len-1])) { --Len; } Buf[Len] = '\0'; /* Get a pointer to the buffer and remove leading white space */ Line = Buf; while (IsBlank (*Line)) { ++Line; } /* Check the first character and enable/disable the step or * ignore the line */ switch (*Line) { case '\0': case '#': case ';': /* Empty or comment line */ continue; case '-': DisableOpt (Line+1); break; case '+': ++Line; /* FALLTHROUGH */ default: EnableOpt (Line); break; } } /* Close the file, no error check here since we were just reading and * this is only a debug function. */ (void) fclose (F); } static void OptDebugOptOutput (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Output optimization steps */ { DebugOptOutput = 1; } static void OptDepTarget (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --dep-target option */ { FileNameOption (Opt, Arg, &DepTarget); } static void OptDisableOpt (const char* Opt attribute ((unused)), const char* Arg) /* Disable an optimization step */ { DisableOpt (Arg); } static void OptEnableOpt (const char* Opt attribute ((unused)), const char* Arg) /* Enable an optimization step */ { EnableOpt (Arg); } static void OptHelp (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print usage information and exit */ { Usage (); exit (EXIT_SUCCESS); } static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg) /* Add an include search path */ { AddSearchPath (SysIncSearchPath, Arg); AddSearchPath (UsrIncSearchPath, Arg); } static void OptListOptSteps (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* List all optimizer steps */ { /* List the optimizer steps */ ListOptSteps (stdout); /* Terminate */ exit (EXIT_SUCCESS); } static void OptListWarnings (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* List all warning types */ { /* List the warnings */ ListWarnings (stdout); /* Terminate */ exit (EXIT_SUCCESS); } static void OptLocalStrings (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Emit string literals immediately */ { IS_Set (&LocalStrings, 1); } static void OptMemoryModel (const char* Opt, const char* Arg) /* Set the memory model */ { mmodel_t M; /* Check the current memory model */ if (MemoryModel != MMODEL_UNKNOWN) { AbEnd ("Cannot use option `%s' twice", Opt); } /* Translate the memory model name and check it */ M = FindMemoryModel (Arg); if (M == MMODEL_UNKNOWN) { AbEnd ("Unknown memory model: %s", Arg); } else if (M == MMODEL_HUGE) { AbEnd ("Unsupported memory model: %s", Arg); } /* Set the memory model */ SetMemoryModel (M); } static void OptRegisterSpace (const char* Opt, const char* Arg) /* Handle the --register-space option */ { /* Numeric argument expected */ if (sscanf (Arg, "%u", &RegisterSpace) != 1 || RegisterSpace > 256) { AbEnd ("Argument for option %s is invalid", Opt); } } static void OptRegisterVars (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Handle the --register-vars option */ { IS_Set (&EnableRegVars, 1); } static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg) /* Handle the --rodata-name option */ { /* Check for a valid name */ CheckSegName (Arg); /* Set the name */ SetSegName (SEG_RODATA, Arg); } static void OptSignedChars (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Make default characters signed */ { IS_Set (&SignedChars, 1); } static void OptStandard (const char* Opt, const char* Arg) /* Handle the --standard option */ { /* Find the standard from the given name */ standard_t Std = FindStandard (Arg); if (Std == STD_UNKNOWN) { AbEnd ("Invalid argument for %s: `%s'", Opt, Arg); } else if (IS_Get (&Standard) != STD_UNKNOWN) { AbEnd ("Option %s given more than once", Opt); } else { IS_Set (&Standard, Std); } } static void OptStaticLocals (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Place local variables in static storage */ { IS_Set (&StaticLocals, 1); } static void OptTarget (const char* Opt attribute ((unused)), const char* Arg) /* Set the target system */ { SetSys (Arg); } static void OptVerbose (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Increase verbosity */ { ++Verbosity; } static void OptVersion (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Print the compiler version */ { fprintf (stderr, "cc65 V%s\n", GetVersionAsString ()); exit (EXIT_SUCCESS); } static void OptWarning (const char* Opt attribute ((unused)), const char* Arg) /* Handle the -W option */ { StrBuf W = AUTO_STRBUF_INITIALIZER; /* Arg is a list of suboptions, separated by commas */ while (Arg) { const char* Pos; int Enabled = 1; IntStack* S; /* The suboption may be prefixed with '-' or '+' */ if (*Arg == '-') { Enabled = 0; ++Arg; } else if (*Arg == '+') { /* This is the default */ ++Arg; } /* Get the next suboption */ Pos = strchr (Arg, ','); if (Pos) { SB_CopyBuf (&W, Arg, Pos - Arg); Arg = Pos + 1; } else { SB_CopyStr (&W, Arg); Arg = 0; } SB_Terminate (&W); /* Search for the warning */ S = FindWarning (SB_GetConstBuf (&W)); if (S == 0) { InvArg (Opt, SB_GetConstBuf (&W)); } IS_Set (S, Enabled); } /* Free allocated memory */ SB_Done (&W); } static void OptWritableStrings (const char* Opt attribute ((unused)), const char* Arg attribute ((unused))) /* Make string literals writable */ { IS_Set (&WritableStrings, 1); } int main (int argc, char* argv[]) { /* Program long options */ static const LongOpt OptTab[] = { { "--add-source", 0, OptAddSource }, { "--bss-name", 1, OptBssName }, { "--check-stack", 0, OptCheckStack }, { "--code-name", 1, OptCodeName }, { "--codesize", 1, OptCodeSize }, { "--cpu", 1, OptCPU }, { "--create-dep", 1, OptCreateDep }, { "--create-full-dep", 1, OptCreateFullDep }, { "--data-name", 1, OptDataName }, { "--debug", 0, OptDebug }, { "--debug-info", 0, OptDebugInfo }, { "--debug-opt", 1, OptDebugOpt }, { "--debug-opt-output", 0, OptDebugOptOutput }, { "--dep-target", 1, OptDepTarget }, { "--disable-opt", 1, OptDisableOpt }, { "--enable-opt", 1, OptEnableOpt }, { "--help", 0, OptHelp }, { "--include-dir", 1, OptIncludeDir }, { "--list-opt-steps", 0, OptListOptSteps }, { "--list-warnings", 0, OptListWarnings }, { "--local-strings", 0, OptLocalStrings }, { "--memory-model", 1, OptMemoryModel }, { "--register-space", 1, OptRegisterSpace }, { "--register-vars", 0, OptRegisterVars }, { "--rodata-name", 1, OptRodataName }, { "--signed-chars", 0, OptSignedChars }, { "--standard", 1, OptStandard }, { "--static-locals", 0, OptStaticLocals }, { "--target", 1, OptTarget }, { "--verbose", 0, OptVerbose }, { "--version", 0, OptVersion }, { "--writable-strings", 0, OptWritableStrings }, }; unsigned I; /* Initialize the input file name */ const char* InputFile = 0; /* Initialize the cmdline module */ InitCmdLine (&argc, &argv, "cc65"); /* Initialize the default segment names */ InitSegNames (); /* Initialize the include search paths */ InitIncludePaths (); /* Parse the command line */ I = 1; while (I < ArgCount) { const char* P; /* Get the argument */ const char* Arg = ArgVec[I]; /* Check for an option */ if (Arg[0] == '-') { switch (Arg[1]) { case '-': LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0])); break; case 'd': OptDebug (Arg, 0); break; case 'h': case '?': OptHelp (Arg, 0); break; case 'g': OptDebugInfo (Arg, 0); break; case 'j': OptSignedChars (Arg, 0); break; case 'o': SetOutputName (GetArg (&I, 2)); break; case 'r': OptRegisterVars (Arg, 0); break; case 't': OptTarget (Arg, GetArg (&I, 2)); break; case 'u': OptCreateDep (Arg, 0); break; case 'v': OptVerbose (Arg, 0); break; case 'C': P = Arg + 2; while (*P) { switch (*P++) { case 'l': OptStaticLocals (Arg, 0); break; default: UnknownOption (Arg); break; } } break; case 'D': DefineSym (GetArg (&I, 2)); break; case 'E': PreprocessOnly = 1; break; case 'I': OptIncludeDir (Arg, GetArg (&I, 2)); break; case 'O': IS_Set (&Optimize, 1); P = Arg + 2; while (*P) { switch (*P++) { case 'i': IS_Set (&CodeSizeFactor, 200); break; case 'r': IS_Set (&EnableRegVars, 1); break; case 's': IS_Set (&InlineStdFuncs, 1); break; } } break; case 'T': OptAddSource (Arg, 0); break; case 'V': OptVersion (Arg, 0); break; case 'W': OptWarning (Arg, GetArg (&I, 2)); break; default: UnknownOption (Arg); break; } } else { if (InputFile) { fprintf (stderr, "additional file specs ignored\n"); } else { InputFile = Arg; } } /* Next argument */ ++I; } /* Did we have a file spec on the command line? */ if (InputFile == 0) { AbEnd ("No input files"); } /* Add the default include search paths. */ FinishIncludePaths (); /* Create the output file name if it was not explicitly given */ MakeDefaultOutputName (InputFile); /* If no CPU given, use the default CPU for the target */ if (CPU == CPU_UNKNOWN) { if (Target != TGT_UNKNOWN) { CPU = GetTargetProperties (Target)->DefaultCPU; } else { CPU = CPU_6502; } } /* If no memory model was given, use the default */ if (MemoryModel == MMODEL_UNKNOWN) { SetMemoryModel (MMODEL_NEAR); } /* If no language standard was given, use the default one */ if (IS_Get (&Standard) == STD_UNKNOWN) { IS_Set (&Standard, STD_DEFAULT); } /* Go! */ Compile (InputFile); /* Create the output file if we didn't had any errors */ if (PreprocessOnly == 0 && (ErrorCount == 0 || Debug)) { /* Emit literals, externals, do cleanup and optimizations */ FinishCompile (); /* Open the file */ OpenOutputFile (); /* Write the output to the file */ WriteAsmOutput (); Print (stdout, 1, "Wrote output to `%s'\n", OutputFilename); /* Close the file, check for errors */ CloseOutputFile (); /* Create dependencies if requested */ CreateDependencies (); } /* Return an apropriate exit code */ return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS; }
841
./cc65/src/cc65/codeopt.c
/*****************************************************************************/ /* */ /* codeopt.c */ /* */ /* Optimizer subroutines */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> #include <stdarg.h> /* common */ #include "abend.h" #include "chartype.h" #include "cpu.h" #include "debugflag.h" #include "print.h" #include "strbuf.h" #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "asmlabel.h" #include "codeent.h" #include "codeinfo.h" #include "codeopt.h" #include "coptadd.h" #include "coptc02.h" #include "coptcmp.h" #include "coptind.h" #include "coptneg.h" #include "coptptrload.h" #include "coptptrstore.h" #include "coptpush.h" #include "coptshift.h" #include "coptsize.h" #include "coptstop.h" #include "coptstore.h" #include "coptsub.h" #include "copttest.h" #include "error.h" #include "global.h" #include "output.h" /*****************************************************************************/ /* Optimize loads */ /*****************************************************************************/ static unsigned OptLoad1 (CodeSeg* S) /* Search for a call to ldaxysp where X is not used later and replace it by * a load of just the A register. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* E; /* Get next entry */ E = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (E, "ldaxysp") && RegValIsKnown (E->RI->In.RegY) && !RegXUsed (S, I+1)) { CodeEntry* X; /* Reload the Y register */ const char* Arg = MakeHexArg (E->RI->In.RegY - 1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); CS_InsertEntry (S, X, I+1); /* Load from stack */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, E->LI); CS_InsertEntry (S, X, I+2); /* Now remove the call to the subroutine */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } static unsigned OptLoad2 (CodeSeg* S) /* Replace calls to ldaxysp by inline code */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxysp")) { CodeEntry* X; /* Followed by sta abs/stx abs? */ if (CS_GetEntries (S, L+1, I+1, 2) && L[1]->OPC == OP65_STA && L[2]->OPC == OP65_STX && (L[1]->Arg == 0 || L[2]->Arg == 0 || strcmp (L[1]->Arg, L[2]->Arg) != 0) && !CS_RangeHasLabel (S, I+1, 2) && !RegXUsed (S, I+3)) { /* A/X are stored into memory somewhere and X is not used * later */ /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI); CS_InsertEntry (S, X, I+3); /* sta abs */ X = NewCodeEntry (OP65_STA, L[2]->AM, L[2]->Arg, 0, L[2]->LI); CS_InsertEntry (S, X, I+4); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+5); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI); CS_InsertEntry (S, X, I+6); /* sta abs */ X = NewCodeEntry (OP65_STA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+7); /* Now remove the call to the subroutine and the sta/stx */ CS_DelEntries (S, I, 3); } else { /* Standard replacement */ /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI); CS_InsertEntry (S, X, I+1); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+3); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI); CS_InsertEntry (S, X, I+4); /* Now remove the call to the subroutine */ CS_DelEntry (S, I); } /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } static unsigned OptLoad3 (CodeSeg* S) /* Remove repeated loads from one and the same memory location */ { unsigned Changes = 0; CodeEntry* Load = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Forget a preceeding load if we have a label */ if (Load && CE_HasLabel (E)) { Load = 0; } /* Check if this insn is a load */ if (E->Info & OF_LOAD) { CodeEntry* N; /* If we had a preceeding load that is identical, remove this one. * If it is not identical, or we didn't have one, remember it. */ if (Load != 0 && E->OPC == Load->OPC && E->AM == Load->AM && ((E->Arg == 0 && Load->Arg == 0) || strcmp (E->Arg, Load->Arg) == 0) && (N = CS_GetNextEntry (S, I)) != 0 && (N->Info & OF_CBRA) == 0) { /* Now remove the call to the subroutine */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; /* Next insn */ continue; } else { Load = E; } } else if ((E->Info & OF_CMP) == 0 && (E->Info & OF_CBRA) == 0) { /* Forget the first load on occurance of any insn we don't like */ Load = 0; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Decouple operations */ /*****************************************************************************/ static unsigned OptDecouple (CodeSeg* S) /* Decouple operations, that is, do the following replacements: * * dex -> ldx #imm * inx -> ldx #imm * dey -> ldy #imm * iny -> ldy #imm * tax -> ldx #imm * txa -> lda #imm * tay -> ldy #imm * tya -> lda #imm * lda zp -> lda #imm * ldx zp -> ldx #imm * ldy zp -> ldy #imm * * Provided that the register values are known of course. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { const char* Arg; /* Get next entry and it's input register values */ CodeEntry* E = CS_GetEntry (S, I); const RegContents* In = &E->RI->In; /* Assume we have no replacement */ CodeEntry* X = 0; /* Check the instruction */ switch (E->OPC) { case OP65_DEA: if (RegValIsKnown (In->RegA)) { Arg = MakeHexArg ((In->RegA - 1) & 0xFF); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); } break; case OP65_DEX: if (RegValIsKnown (In->RegX)) { Arg = MakeHexArg ((In->RegX - 1) & 0xFF); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); } break; case OP65_DEY: if (RegValIsKnown (In->RegY)) { Arg = MakeHexArg ((In->RegY - 1) & 0xFF); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); } break; case OP65_INA: if (RegValIsKnown (In->RegA)) { Arg = MakeHexArg ((In->RegA + 1) & 0xFF); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); } break; case OP65_INX: if (RegValIsKnown (In->RegX)) { Arg = MakeHexArg ((In->RegX + 1) & 0xFF); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); } break; case OP65_INY: if (RegValIsKnown (In->RegY)) { Arg = MakeHexArg ((In->RegY + 1) & 0xFF); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); } break; case OP65_LDA: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Arg = MakeHexArg (In->Tmp1); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_LO: Arg = MakeHexArg (In->Ptr1Lo); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_HI: Arg = MakeHexArg (In->Ptr1Hi); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_LO: Arg = MakeHexArg (In->SRegLo); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_HI: Arg = MakeHexArg (In->SRegHi); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); break; } } break; case OP65_LDX: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Arg = MakeHexArg (In->Tmp1); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_LO: Arg = MakeHexArg (In->Ptr1Lo); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_HI: Arg = MakeHexArg (In->Ptr1Hi); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_LO: Arg = MakeHexArg (In->SRegLo); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_HI: Arg = MakeHexArg (In->SRegHi); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); break; } } break; case OP65_LDY: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use, In)) { case REG_TMP1: Arg = MakeHexArg (In->Tmp1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_LO: Arg = MakeHexArg (In->Ptr1Lo); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); break; case REG_PTR1_HI: Arg = MakeHexArg (In->Ptr1Hi); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_LO: Arg = MakeHexArg (In->SRegLo); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); break; case REG_SREG_HI: Arg = MakeHexArg (In->SRegHi); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); break; } } break; case OP65_TAX: if (E->RI->In.RegA >= 0) { Arg = MakeHexArg (In->RegA); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI); } break; case OP65_TAY: if (E->RI->In.RegA >= 0) { Arg = MakeHexArg (In->RegA); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); } break; case OP65_TXA: if (E->RI->In.RegX >= 0) { Arg = MakeHexArg (In->RegX); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); } break; case OP65_TYA: if (E->RI->In.RegY >= 0) { Arg = MakeHexArg (In->RegY); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI); } break; default: /* Avoid gcc warnings */ break; } /* Insert the replacement if we have one */ if (X) { CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimize stack pointer ops */ /*****************************************************************************/ static unsigned IsDecSP (const CodeEntry* E) /* Check if this is an insn that decrements the stack pointer. If so, return * the decrement. If not, return zero. * The function expects E to be a subroutine call. */ { if (strncmp (E->Arg, "decsp", 5) == 0) { if (E->Arg[5] >= '1' && E->Arg[5] <= '8') { return (E->Arg[5] - '0'); } } else if (strcmp (E->Arg, "subysp") == 0 && RegValIsKnown (E->RI->In.RegY)) { return E->RI->In.RegY; } /* If we come here, it's not a decsp op */ return 0; } static unsigned OptStackPtrOps (CodeSeg* S) /* Merge adjacent calls to decsp into one. NOTE: This function won't merge all * known cases! */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { unsigned Dec1; unsigned Dec2; const CodeEntry* N; /* Get the next entry */ const CodeEntry* E = CS_GetEntry (S, I); /* Check for decspn or subysp */ if (E->OPC == OP65_JSR && (Dec1 = IsDecSP (E)) > 0 && (N = CS_GetNextEntry (S, I)) != 0 && (Dec2 = IsDecSP (N)) > 0 && (Dec1 += Dec2) <= 255 && !CE_HasLabel (N)) { CodeEntry* X; char Buf[20]; /* We can combine the two */ if (Dec1 <= 8) { /* Insert a call to decsp */ xsprintf (Buf, sizeof (Buf), "decsp%u", Dec1); X = NewCodeEntry (OP65_JSR, AM65_ABS, Buf, 0, N->LI); CS_InsertEntry (S, X, I+2); } else { /* Insert a call to subysp */ const char* Arg = MakeHexArg (Dec1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, N->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_JSR, AM65_ABS, "subysp", 0, N->LI); CS_InsertEntry (S, X, I+3); } /* Delete the old code */ CS_DelEntries (S, I, 2); /* Regenerate register info */ CS_GenRegInfo (S); /* Remember we had changes */ ++Changes; } else { /* Next entry */ ++I; } } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* struct OptFunc */ /*****************************************************************************/ typedef struct OptFunc OptFunc; struct OptFunc { unsigned (*Func) (CodeSeg*); /* Optimizer function */ const char* Name; /* Name of the function/group */ unsigned CodeSizeFactor; /* Code size factor for this opt func */ unsigned long TotalRuns; /* Total number of runs */ unsigned long LastRuns; /* Last number of runs */ unsigned long TotalChanges; /* Total number of changes */ unsigned long LastChanges; /* Last number of changes */ char Disabled; /* True if function disabled */ }; /*****************************************************************************/ /* Code */ /*****************************************************************************/ /* A list of all the function descriptions */ static OptFunc DOpt65C02BitOps = { Opt65C02BitOps, "Opt65C02BitOps", 66, 0, 0, 0, 0, 0 }; static OptFunc DOpt65C02Ind = { Opt65C02Ind, "Opt65C02Ind", 100, 0, 0, 0, 0, 0 }; static OptFunc DOpt65C02Stores = { Opt65C02Stores, "Opt65C02Stores", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd1 = { OptAdd1, "OptAdd1", 125, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd2 = { OptAdd2, "OptAdd2", 200, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd3 = { OptAdd3, "OptAdd3", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd4 = { OptAdd4, "OptAdd4", 90, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd5 = { OptAdd5, "OptAdd5", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptAdd6 = { OptAdd6, "OptAdd6", 40, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegA1 = { OptBNegA1, "OptBNegA1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegA2 = { OptBNegA2, "OptBNegA2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegAX1 = { OptBNegAX1, "OptBNegAX1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegAX2 = { OptBNegAX2, "OptBNegAX2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegAX3 = { OptBNegAX3, "OptBNegAX3", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBNegAX4 = { OptBNegAX4, "OptBNegAX4", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBoolTrans = { OptBoolTrans, "OptBoolTrans", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptBranchDist = { OptBranchDist, "OptBranchDist", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp1 = { OptCmp1, "OptCmp1", 42, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp2 = { OptCmp2, "OptCmp2", 85, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp3 = { OptCmp3, "OptCmp3", 75, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp4 = { OptCmp4, "OptCmp4", 75, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp5 = { OptCmp5, "OptCmp5", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp6 = { OptCmp6, "OptCmp6", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp7 = { OptCmp7, "OptCmp7", 85, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp8 = { OptCmp8, "OptCmp8", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptCmp9 = { OptCmp9, "OptCmp9", 85, 0, 0, 0, 0, 0 }; static OptFunc DOptComplAX1 = { OptComplAX1, "OptComplAX1", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptCondBranches1= { OptCondBranches1,"OptCondBranches1", 80, 0, 0, 0, 0, 0 }; static OptFunc DOptCondBranches2= { OptCondBranches2,"OptCondBranches2", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptDeadCode = { OptDeadCode, "OptDeadCode", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptDeadJumps = { OptDeadJumps, "OptDeadJumps", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptDecouple = { OptDecouple, "OptDecouple", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptDupLoads = { OptDupLoads, "OptDupLoads", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptIndLoads1 = { OptIndLoads1, "OptIndLoads1", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptIndLoads2 = { OptIndLoads2, "OptIndLoads2", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptJumpCascades = { OptJumpCascades, "OptJumpCascades", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptJumpTarget1 = { OptJumpTarget1, "OptJumpTarget1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptJumpTarget2 = { OptJumpTarget2, "OptJumpTarget2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptJumpTarget3 = { OptJumpTarget3, "OptJumpTarget3", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptLoad1 = { OptLoad1, "OptLoad1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptLoad2 = { OptLoad2, "OptLoad2", 200, 0, 0, 0, 0, 0 }; static OptFunc DOptLoad3 = { OptLoad3, "OptLoad3", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptNegAX1 = { OptNegAX1, "OptNegAX1", 165, 0, 0, 0, 0, 0 }; static OptFunc DOptNegAX2 = { OptNegAX2, "OptNegAX2", 200, 0, 0, 0, 0, 0 }; static OptFunc DOptRTS = { OptRTS, "OptRTS", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptRTSJumps1 = { OptRTSJumps1, "OptRTSJumps1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptRTSJumps2 = { OptRTSJumps2, "OptRTSJumps2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPrecalc = { OptPrecalc, "OptPrecalc", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad1 = { OptPtrLoad1, "OptPtrLoad1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad2 = { OptPtrLoad2, "OptPtrLoad2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad3 = { OptPtrLoad3, "OptPtrLoad3", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad4 = { OptPtrLoad4, "OptPtrLoad4", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad5 = { OptPtrLoad5, "OptPtrLoad5", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad6 = { OptPtrLoad6, "OptPtrLoad6", 60, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad7 = { OptPtrLoad7, "OptPtrLoad7", 140, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad11 = { OptPtrLoad11, "OptPtrLoad11", 92, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad12 = { OptPtrLoad12, "OptPtrLoad12", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad13 = { OptPtrLoad13, "OptPtrLoad13", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad14 = { OptPtrLoad14, "OptPtrLoad14", 108, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad15 = { OptPtrLoad15, "OptPtrLoad15", 86, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad16 = { OptPtrLoad16, "OptPtrLoad16", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrLoad17 = { OptPtrLoad17, "OptPtrLoad17", 190, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrStore1 = { OptPtrStore1, "OptPtrStore1", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrStore2 = { OptPtrStore2, "OptPtrStore2", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptPtrStore3 = { OptPtrStore3, "OptPtrStore3", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptPush1 = { OptPush1, "OptPush1", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptPush2 = { OptPush2, "OptPush2", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptPushPop = { OptPushPop, "OptPushPop", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptShift1 = { OptShift1, "OptShift1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptShift2 = { OptShift2, "OptShift2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptShift3 = { OptShift3, "OptShift3", 17, 0, 0, 0, 0, 0 }; static OptFunc DOptShift4 = { OptShift4, "OptShift4", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptShift5 = { OptShift5, "OptShift5", 110, 0, 0, 0, 0, 0 }; static OptFunc DOptShift6 = { OptShift6, "OptShift6", 200, 0, 0, 0, 0, 0 }; static OptFunc DOptSize1 = { OptSize1, "OptSize1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptSize2 = { OptSize2, "OptSize2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptStackOps = { OptStackOps, "OptStackOps", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptStackPtrOps = { OptStackPtrOps, "OptStackPtrOps", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptStore1 = { OptStore1, "OptStore1", 70, 0, 0, 0, 0, 0 }; static OptFunc DOptStore2 = { OptStore2, "OptStore2", 115, 0, 0, 0, 0, 0 }; static OptFunc DOptStore3 = { OptStore3, "OptStore3", 120, 0, 0, 0, 0, 0 }; static OptFunc DOptStore4 = { OptStore4, "OptStore4", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptStore5 = { OptStore5, "OptStore5", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptStoreLoad = { OptStoreLoad, "OptStoreLoad", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptSub1 = { OptSub1, "OptSub1", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptSub2 = { OptSub2, "OptSub2", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptSub3 = { OptSub3, "OptSub3", 100, 0, 0, 0, 0, 0 }; static OptFunc DOptTest1 = { OptTest1, "OptTest1", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptTest2 = { OptTest2, "OptTest2", 50, 0, 0, 0, 0, 0 }; static OptFunc DOptTransfers1 = { OptTransfers1, "OptTransfers1", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptTransfers2 = { OptTransfers2, "OptTransfers2", 60, 0, 0, 0, 0, 0 }; static OptFunc DOptTransfers3 = { OptTransfers3, "OptTransfers3", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptTransfers4 = { OptTransfers4, "OptTransfers4", 65, 0, 0, 0, 0, 0 }; static OptFunc DOptUnusedLoads = { OptUnusedLoads, "OptUnusedLoads", 0, 0, 0, 0, 0, 0 }; static OptFunc DOptUnusedStores = { OptUnusedStores, "OptUnusedStores", 0, 0, 0, 0, 0, 0 }; /* Table containing all the steps in alphabetical order */ static OptFunc* OptFuncs[] = { &DOpt65C02BitOps, &DOpt65C02Ind, &DOpt65C02Stores, &DOptAdd1, &DOptAdd2, &DOptAdd3, &DOptAdd4, &DOptAdd5, &DOptAdd6, &DOptBNegA1, &DOptBNegA2, &DOptBNegAX1, &DOptBNegAX2, &DOptBNegAX3, &DOptBNegAX4, &DOptBoolTrans, &DOptBranchDist, &DOptCmp1, &DOptCmp2, &DOptCmp3, &DOptCmp4, &DOptCmp5, &DOptCmp6, &DOptCmp7, &DOptCmp8, &DOptCmp9, &DOptComplAX1, &DOptCondBranches1, &DOptCondBranches2, &DOptDeadCode, &DOptDeadJumps, &DOptDecouple, &DOptDupLoads, &DOptIndLoads1, &DOptIndLoads2, &DOptJumpCascades, &DOptJumpTarget1, &DOptJumpTarget2, &DOptJumpTarget3, &DOptLoad1, &DOptLoad2, &DOptLoad3, &DOptNegAX1, &DOptNegAX2, &DOptPrecalc, &DOptPtrLoad1, &DOptPtrLoad11, &DOptPtrLoad12, &DOptPtrLoad13, &DOptPtrLoad14, &DOptPtrLoad15, &DOptPtrLoad16, &DOptPtrLoad17, &DOptPtrLoad2, &DOptPtrLoad3, &DOptPtrLoad4, &DOptPtrLoad5, &DOptPtrLoad6, &DOptPtrLoad7, &DOptPtrStore1, &DOptPtrStore2, &DOptPtrStore3, &DOptPush1, &DOptPush2, &DOptPushPop, &DOptRTS, &DOptRTSJumps1, &DOptRTSJumps2, &DOptShift1, &DOptShift2, &DOptShift3, &DOptShift4, &DOptShift5, &DOptShift6, &DOptSize1, &DOptSize2, &DOptStackOps, &DOptStackPtrOps, &DOptStore1, &DOptStore2, &DOptStore3, &DOptStore4, &DOptStore5, &DOptStoreLoad, &DOptSub1, &DOptSub2, &DOptSub3, &DOptTest1, &DOptTest2, &DOptTransfers1, &DOptTransfers2, &DOptTransfers3, &DOptTransfers4, &DOptUnusedLoads, &DOptUnusedStores, }; #define OPTFUNC_COUNT (sizeof(OptFuncs) / sizeof(OptFuncs[0])) static int CmpOptStep (const void* Key, const void* Func) /* Compare function for bsearch */ { return strcmp (Key, (*(const OptFunc**)Func)->Name); } static OptFunc* FindOptFunc (const char* Name) /* Find an optimizer step by name in the table and return a pointer. Return * NULL if no such step is found. */ { /* Search for the function in the list */ OptFunc** O = bsearch (Name, OptFuncs, OPTFUNC_COUNT, sizeof (OptFuncs[0]), CmpOptStep); return O? *O : 0; } static OptFunc* GetOptFunc (const char* Name) /* Find an optimizer step by name in the table and return a pointer. Print an * error and call AbEnd if not found. */ { /* Search for the function in the list */ OptFunc* F = FindOptFunc (Name); if (F == 0) { /* Not found */ AbEnd ("Optimization step `%s' not found", Name); } return F; } void DisableOpt (const char* Name) /* Disable the optimization with the given name */ { if (strcmp (Name, "any") == 0) { unsigned I; for (I = 0; I < OPTFUNC_COUNT; ++I) { OptFuncs[I]->Disabled = 1; } } else { GetOptFunc(Name)->Disabled = 1; } } void EnableOpt (const char* Name) /* Enable the optimization with the given name */ { if (strcmp (Name, "any") == 0) { unsigned I; for (I = 0; I < OPTFUNC_COUNT; ++I) { OptFuncs[I]->Disabled = 0; } } else { GetOptFunc(Name)->Disabled = 0; } } void ListOptSteps (FILE* F) /* List all optimization steps */ { unsigned I; for (I = 0; I < OPTFUNC_COUNT; ++I) { fprintf (F, "%s\n", OptFuncs[I]->Name); } } static void ReadOptStats (const char* Name) /* Read the optimizer statistics file */ { char Buf [256]; unsigned Lines; /* Try to open the file */ FILE* F = fopen (Name, "r"); if (F == 0) { /* Ignore the error */ return; } /* Read and parse the lines */ Lines = 0; while (fgets (Buf, sizeof (Buf), F) != 0) { char* B; unsigned Len; OptFunc* Func; /* Fields */ char Name[32]; unsigned long TotalRuns; unsigned long TotalChanges; /* Count lines */ ++Lines; /* Remove trailing white space including the line terminator */ B = Buf; Len = strlen (B); while (Len > 0 && IsSpace (B[Len-1])) { --Len; } B[Len] = '\0'; /* Remove leading whitespace */ while (IsSpace (*B)) { ++B; } /* Check for empty and comment lines */ if (*B == '\0' || *B == ';' || *B == '#') { continue; } /* Parse the line */ if (sscanf (B, "%31s %lu %*u %lu %*u", Name, &TotalRuns, &TotalChanges) != 3) { /* Syntax error */ continue; } /* Search for the optimizer step. */ Func = FindOptFunc (Name); if (Func == 0) { /* Not found */ continue; } /* Found the step, set the fields */ Func->TotalRuns = TotalRuns; Func->TotalChanges = TotalChanges; } /* Close the file, ignore errors here. */ fclose (F); } static void WriteOptStats (const char* Name) /* Write the optimizer statistics file */ { unsigned I; /* Try to open the file */ FILE* F = fopen (Name, "w"); if (F == 0) { /* Ignore the error */ return; } /* Write a header */ fprintf (F, "; Optimizer Total Last Total Last\n" "; Step Runs Runs Chg Chg\n"); /* Write the data */ for (I = 0; I < OPTFUNC_COUNT; ++I) { const OptFunc* O = OptFuncs[I]; fprintf (F, "%-20s %10lu %10lu %10lu %10lu\n", O->Name, O->TotalRuns, O->LastRuns, O->TotalChanges, O->LastChanges); } /* Close the file, ignore errors here. */ fclose (F); } static void OpenDebugFile (const CodeSeg* S) /* Open the debug file for the given segment if the flag is on */ { if (DebugOptOutput) { StrBuf Name = AUTO_STRBUF_INITIALIZER; if (S->Func) { SB_CopyStr (&Name, S->Func->Name); } else { SB_CopyStr (&Name, "global"); } SB_AppendStr (&Name, ".opt"); SB_Terminate (&Name); OpenDebugOutputFile (SB_GetConstBuf (&Name)); SB_Done (&Name); } } static void WriteDebugOutput (CodeSeg* S, const char* Step) /* Write a separator line into the debug file if the flag is on */ { if (DebugOptOutput) { /* Output a separator */ WriteOutput ("=========================================================================\n"); /* Output a header line */ if (Step == 0) { /* Initial output */ WriteOutput ("Initial code for function `%s':\n", S->Func? S->Func->Name : "<global>"); } else { WriteOutput ("Code after applying `%s':\n", Step); } /* Output the code segment */ CS_Output (S); } } static unsigned RunOptFunc (CodeSeg* S, OptFunc* F, unsigned Max) /* Run one optimizer function Max times or until there are no more changes */ { unsigned Changes, C; /* Don't run the function if it is disabled or if it is prohibited by the * code size factor */ if (F->Disabled || F->CodeSizeFactor > S->CodeSizeFactor) { return 0; } /* Run this until there are no more changes */ Changes = 0; do { /* Run the function */ C = F->Func (S); Changes += C; /* Do statistics */ ++F->TotalRuns; ++F->LastRuns; F->TotalChanges += C; F->LastChanges += C; /* If we had changes, output stuff and regenerate register info */ if (C) { if (Debug) { printf ("Applied %s: %u changes\n", F->Name, C); } WriteDebugOutput (S, F->Name); CS_GenRegInfo (S); } } while (--Max && C > 0); /* Return the number of changes */ return Changes; } static unsigned RunOptGroup1 (CodeSeg* S) /* Run the first group of optimization steps. These steps translate known * patterns emitted by the code generator into more optimal patterns. Order * of the steps is important, because some of the steps done earlier cover * the same patterns as later steps as subpatterns. */ { unsigned Changes = 0; Changes += RunOptFunc (S, &DOptStackPtrOps, 5); Changes += RunOptFunc (S, &DOptPtrStore1, 1); Changes += RunOptFunc (S, &DOptPtrStore2, 1); Changes += RunOptFunc (S, &DOptPtrStore3, 1); Changes += RunOptFunc (S, &DOptAdd3, 1); /* Before OptPtrLoad5! */ Changes += RunOptFunc (S, &DOptPtrLoad1, 1); Changes += RunOptFunc (S, &DOptPtrLoad2, 1); Changes += RunOptFunc (S, &DOptPtrLoad3, 1); Changes += RunOptFunc (S, &DOptPtrLoad4, 1); Changes += RunOptFunc (S, &DOptPtrLoad5, 1); Changes += RunOptFunc (S, &DOptPtrLoad6, 1); Changes += RunOptFunc (S, &DOptPtrLoad7, 1); Changes += RunOptFunc (S, &DOptPtrLoad11, 1); Changes += RunOptFunc (S, &DOptPtrLoad12, 1); Changes += RunOptFunc (S, &DOptPtrLoad13, 1); Changes += RunOptFunc (S, &DOptPtrLoad14, 1); Changes += RunOptFunc (S, &DOptPtrLoad15, 1); Changes += RunOptFunc (S, &DOptPtrLoad16, 1); Changes += RunOptFunc (S, &DOptPtrLoad17, 1); Changes += RunOptFunc (S, &DOptBNegAX1, 1); Changes += RunOptFunc (S, &DOptBNegAX2, 1); Changes += RunOptFunc (S, &DOptBNegAX3, 1); Changes += RunOptFunc (S, &DOptBNegAX4, 1); Changes += RunOptFunc (S, &DOptAdd1, 1); Changes += RunOptFunc (S, &DOptAdd2, 1); Changes += RunOptFunc (S, &DOptAdd4, 1); Changes += RunOptFunc (S, &DOptAdd5, 1); Changes += RunOptFunc (S, &DOptAdd6, 1); Changes += RunOptFunc (S, &DOptSub1, 1); Changes += RunOptFunc (S, &DOptSub3, 1); Changes += RunOptFunc (S, &DOptStore4, 1); Changes += RunOptFunc (S, &DOptStore5, 1); Changes += RunOptFunc (S, &DOptShift1, 1); Changes += RunOptFunc (S, &DOptShift2, 1); Changes += RunOptFunc (S, &DOptShift5, 1); Changes += RunOptFunc (S, &DOptShift6, 1); Changes += RunOptFunc (S, &DOptStore1, 1); Changes += RunOptFunc (S, &DOptStore2, 5); Changes += RunOptFunc (S, &DOptStore3, 5); /* Return the number of changes */ return Changes; } static unsigned RunOptGroup2 (CodeSeg* S) /* Run one group of optimization steps. This step involves just decoupling * instructions by replacing them by instructions that do not depend on * previous instructions. This makes it easier to find instructions that * aren't used. */ { unsigned Changes = 0; Changes += RunOptFunc (S, &DOptDecouple, 1); /* Return the number of changes */ return Changes; } static unsigned RunOptGroup3 (CodeSeg* S) /* Run one group of optimization steps. These steps depend on each other, * that means that one step may allow another step to do additional work, * so we will repeat the steps as long as we see any changes. */ { unsigned Changes, C; Changes = 0; do { C = 0; C += RunOptFunc (S, &DOptBNegA1, 1); C += RunOptFunc (S, &DOptBNegA2, 1); C += RunOptFunc (S, &DOptNegAX1, 1); C += RunOptFunc (S, &DOptNegAX2, 1); C += RunOptFunc (S, &DOptStackOps, 3); C += RunOptFunc (S, &DOptShift1, 1); C += RunOptFunc (S, &DOptShift4, 1); C += RunOptFunc (S, &DOptComplAX1, 1); C += RunOptFunc (S, &DOptSub1, 1); C += RunOptFunc (S, &DOptSub2, 1); C += RunOptFunc (S, &DOptSub3, 1); C += RunOptFunc (S, &DOptAdd5, 1); C += RunOptFunc (S, &DOptAdd6, 1); C += RunOptFunc (S, &DOptJumpCascades, 1); C += RunOptFunc (S, &DOptDeadJumps, 1); C += RunOptFunc (S, &DOptRTS, 1); C += RunOptFunc (S, &DOptDeadCode, 1); C += RunOptFunc (S, &DOptBoolTrans, 1); C += RunOptFunc (S, &DOptJumpTarget1, 1); C += RunOptFunc (S, &DOptJumpTarget2, 1); C += RunOptFunc (S, &DOptCondBranches1, 1); C += RunOptFunc (S, &DOptCondBranches2, 1); C += RunOptFunc (S, &DOptRTSJumps1, 1); C += RunOptFunc (S, &DOptCmp1, 1); C += RunOptFunc (S, &DOptCmp2, 1); C += RunOptFunc (S, &DOptCmp8, 1); /* Must run before OptCmp3 */ C += RunOptFunc (S, &DOptCmp3, 1); C += RunOptFunc (S, &DOptCmp4, 1); C += RunOptFunc (S, &DOptCmp5, 1); C += RunOptFunc (S, &DOptCmp6, 1); C += RunOptFunc (S, &DOptCmp7, 1); C += RunOptFunc (S, &DOptCmp9, 1); C += RunOptFunc (S, &DOptTest1, 1); C += RunOptFunc (S, &DOptLoad1, 1); C += RunOptFunc (S, &DOptJumpTarget3, 1); /* After OptCondBranches2 */ C += RunOptFunc (S, &DOptUnusedLoads, 1); C += RunOptFunc (S, &DOptUnusedStores, 1); C += RunOptFunc (S, &DOptDupLoads, 1); C += RunOptFunc (S, &DOptStoreLoad, 1); C += RunOptFunc (S, &DOptTransfers1, 1); C += RunOptFunc (S, &DOptTransfers3, 1); C += RunOptFunc (S, &DOptTransfers4, 1); C += RunOptFunc (S, &DOptStore1, 1); C += RunOptFunc (S, &DOptStore5, 1); C += RunOptFunc (S, &DOptPushPop, 1); C += RunOptFunc (S, &DOptPrecalc, 1); Changes += C; } while (C); /* Return the number of changes */ return Changes; } static unsigned RunOptGroup4 (CodeSeg* S) /* Run another round of pattern replacements. These are done late, since there * may be better replacements before. */ { unsigned Changes = 0; /* Repeat some of the steps here */ Changes += RunOptFunc (S, &DOptShift3, 1); Changes += RunOptFunc (S, &DOptPush1, 1); Changes += RunOptFunc (S, &DOptPush2, 1); Changes += RunOptFunc (S, &DOptUnusedLoads, 1); Changes += RunOptFunc (S, &DOptTest2, 1); Changes += RunOptFunc (S, &DOptTransfers2, 1); Changes += RunOptFunc (S, &DOptLoad2, 1); Changes += RunOptFunc (S, &DOptLoad3, 1); Changes += RunOptFunc (S, &DOptDupLoads, 1); /* Return the number of changes */ return Changes; } static unsigned RunOptGroup5 (CodeSeg* S) /* 65C02 specific optimizations. */ { unsigned Changes = 0; if (CPUIsets[CPU] & CPU_ISET_65SC02) { Changes += RunOptFunc (S, &DOpt65C02BitOps, 1); Changes += RunOptFunc (S, &DOpt65C02Ind, 1); Changes += RunOptFunc (S, &DOpt65C02Stores, 1); if (Changes) { /* The 65C02 replacement codes do often make the use of a register * value unnecessary, so if we have changes, run another load * removal pass. */ Changes += RunOptFunc (S, &DOptUnusedLoads, 1); } } /* Return the number of changes */ return Changes; } static unsigned RunOptGroup6 (CodeSeg* S) /* This one is quite special. It tries to replace "lda (sp),y" by "lda (sp,x)". * The latter is ony cycle slower, but if we're able to remove the necessary * load of the Y register, because X is zero anyway, we gain 1 cycle and * shorten the code by one (transfer) or two bytes (load). So what we do is * to replace the insns, remove unused loads, and then change back all insns * where Y is still zero (meaning that the load has not been removed). */ { unsigned Changes = 0; /* This group will only run for a standard 6502, because the 65C02 has a * better addressing mode that covers this case. */ if ((CPUIsets[CPU] & CPU_ISET_65SC02) == 0) { Changes += RunOptFunc (S, &DOptIndLoads1, 1); Changes += RunOptFunc (S, &DOptUnusedLoads, 1); Changes += RunOptFunc (S, &DOptIndLoads2, 1); } /* Return the number of changes */ return Changes; } static unsigned RunOptGroup7 (CodeSeg* S) /* The last group of optimization steps. Adjust branches, do size optimizations. */ { unsigned Changes = 0; unsigned C; /* Optimize for size, that is replace operations by shorter ones, even * if this does hinder further optimizations (no problem since we're * done soon). */ C = RunOptFunc (S, &DOptSize1, 1); if (C) { Changes += C; /* Run some optimization passes again, since the size optimizations * may have opened new oportunities. */ Changes += RunOptFunc (S, &DOptUnusedLoads, 1); Changes += RunOptFunc (S, &DOptUnusedStores, 1); Changes += RunOptFunc (S, &DOptJumpTarget1, 5); Changes += RunOptFunc (S, &DOptStore5, 1); } C = RunOptFunc (S, &DOptSize2, 1); if (C) { Changes += C; /* Run some optimization passes again, since the size optimizations * may have opened new oportunities. */ Changes += RunOptFunc (S, &DOptUnusedLoads, 1); Changes += RunOptFunc (S, &DOptJumpTarget1, 5); Changes += RunOptFunc (S, &DOptStore5, 1); Changes += RunOptFunc (S, &DOptTransfers1, 1); Changes += RunOptFunc (S, &DOptTransfers3, 1); } /* Adjust branch distances */ Changes += RunOptFunc (S, &DOptBranchDist, 3); /* Replace conditional branches to RTS. If we had changes, we must run dead * code elimination again, since the change may have introduced dead code. */ C = RunOptFunc (S, &DOptRTSJumps2, 1); Changes += C; if (C) { Changes += RunOptFunc (S, &DOptDeadCode, 1); } /* Return the number of changes */ return Changes; } void RunOpt (CodeSeg* S) /* Run the optimizer */ { const char* StatFileName; /* If we shouldn't run the optimizer, bail out */ if (!S->Optimize) { return; } /* Check if we are requested to write optimizer statistics */ StatFileName = getenv ("CC65_OPTSTATS"); if (StatFileName) { ReadOptStats (StatFileName); } /* Print the name of the function we are working on */ if (S->Func) { Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name); } else { Print (stdout, 1, "Running optimizer for global code segment\n"); } /* If requested, open an output file */ OpenDebugFile (S); WriteDebugOutput (S, 0); /* Generate register info for all instructions */ CS_GenRegInfo (S); /* Run groups of optimizations */ RunOptGroup1 (S); RunOptGroup2 (S); RunOptGroup3 (S); RunOptGroup4 (S); RunOptGroup5 (S); RunOptGroup6 (S); RunOptGroup7 (S); /* Free register info */ CS_FreeRegInfo (S); /* Close output file if necessary */ if (DebugOptOutput) { CloseOutputFile (); } /* Write statistics */ if (StatFileName) { WriteOptStats (StatFileName); } }
842
./cc65/src/cc65/coptsize.c
/*****************************************************************************/ /* */ /* coptsize.c */ /* */ /* Size optimizations */ /* */ /* */ /* */ /* (C) 2002-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> /* common */ #include "cpu.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptsize.h" #include "reginfo.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Flags for CallDesc */ #define F_NONE 0x0000U /* No extra flags */ #define F_SLOWER 0x0001U /* Function call is slower */ typedef struct CallDesc CallDesc; struct CallDesc { const char* LongFunc; /* Long function name */ RegContents Regs; /* Register contents */ unsigned Flags; /* Flags from above */ const char* ShortFunc; /* Short function name */ }; /* Note: The table is sorted. If there is more than one entry with the same * name, entries are sorted best match first, so when searching linear for * a match, the first one can be used because it is also the best one (or * at least none of the following ones are better). * Note^2: Ptr1 and Tmp1 aren't evaluated, because runtime routines don't * expect parameters here. */ static const CallDesc CallTable [] = { /* Name A register X register Y register flags replacement */ { "addeqysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "addeq0sp" },{ "laddeq", { /* A X Y SRegLo */ 1, 0, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "laddeq1" },{ "laddeq", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "laddeqa" },{ "laddeqysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "laddeq0sp" },{ "ldaxidx", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 1, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "ldaxi" },{ "ldaxysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 1, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "ldax0sp" },{ "ldeaxidx", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 3, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "ldeaxi" },{ "ldeaxysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 3, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "ldeax0sp" },{ "leaaxsp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "leaa0sp" },{ "lsubeq", { /* A X Y SRegLo */ 1, 0, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "lsubeq1" },{ "lsubeq", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "lsubeqa" },{ "lsubeqysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "lsubeq0sp" },{ "pusha", { /* A X Y SRegLo */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "pushc0" },{ "pusha", { /* A X Y SRegLo */ 1, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "pushc1" },{ "pusha", { /* A X Y SRegLo */ 2, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "pushc2" },{ "pushax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "push0" },{ "pushax", { /* A X Y SRegLo */ 1, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push1" },{ "pushax", { /* A X Y SRegLo */ 2, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push2" },{ "pushax", { /* A X Y SRegLo */ 3, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push3" },{ "pushax", { /* A X Y SRegLo */ 4, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push4" },{ "pushax", { /* A X Y SRegLo */ 5, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push5" },{ "pushax", { /* A X Y SRegLo */ 6, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push6" },{ "pushax", { /* A X Y SRegLo */ 7, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "push7" },{ "pushax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "pusha0" },{ "pushax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0xFF, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_SLOWER, "pushaFF" },{ "pushaysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "pusha0sp" },{ "pusheax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "pushl0" },{ "pusheax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "push0ax" },{ "pushwidx", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 1, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "pushw" },{ "pushwysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 3, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "pushw0sp" },{ "staxysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "stax0sp" },{ "steaxysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "steax0sp" },{ "subeqysp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "subeq0sp" },{ "tosaddax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosadda0" },{ "tosaddeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosadd0ax" },{ "tosandax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosanda0" },{ "tosandeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosand0ax" },{ "tosdivax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosdiva0" },{ "tosdiveax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosdiv0ax" },{ "toseqax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "toseq00" },{ "toseqax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "toseqa0" },{ "tosgeax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosge00" },{ "tosgeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosgea0" },{ "tosgtax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosgt00" },{ "tosgtax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosgta0" },{ "tosicmp", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosicmp0" },{ "tosleax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosle00" },{ "tosleax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "toslea0" },{ "tosltax", { /* A X Y SRegLo */ 0, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "toslt00" },{ "tosltax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "toslta0" },{ "tosmodax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosmoda0" },{ "tosmodeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosmod0ax" },{ "tosmulax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosmula0" },{ "tosmuleax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosmul0ax" },{ "tosneax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosnea0" },{ "tosorax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosora0" },{ "tosoreax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosor0ax" },{ "tosrsubax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosrsuba0" },{ "tosrsubeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosrsub0ax" },{ "tossubax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tossuba0" },{ "tossubeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tossub0ax" },{ "tosudivax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosudiva0" },{ "tosudiveax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosudiv0ax" },{ "tosugeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosugea0" },{ "tosugtax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosugta0" },{ "tosuleax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosulea0" },{ "tosultax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosulta0" },{ "tosumodax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosumoda0" },{ "tosumodeax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosumod0ax" },{ "tosumulax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosumula0" },{ "tosumuleax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosumul0ax" },{ "tosxorax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosxora0" },{ "tosxoreax", { /* A X Y SRegLo */ UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL, 0, /* SRegHi Ptr1Lo Ptr1Hi Tmp1 */ 0, UNKNOWN_REGVAL, UNKNOWN_REGVAL, UNKNOWN_REGVAL }, F_NONE, "tosxor0ax" }, }; #define CALL_COUNT (sizeof(CallTable) / sizeof(CallTable[0])) /*****************************************************************************/ /* Helpers */ /*****************************************************************************/ static const CallDesc* FindCall (const char* Name) /* Find the function with the given name. Return a pointer to the table entry * or NULL if the function was not found. */ { /* Do a binary search */ int First = 0; int Last = CALL_COUNT - 1; int Found = 0; while (First <= Last) { /* Set current to mid of range */ int Current = (Last + First) / 2; /* Do a compare */ int Result = strcmp (CallTable[Current].LongFunc, Name); if (Result < 0) { First = Current + 1; } else { Last = Current - 1; if (Result == 0) { /* Found. Repeat the procedure until the first of all entries * with the same name is found. */ Found = 1; } } } /* Return the first entry if found, or NULL otherwise */ return Found? &CallTable[First] : 0; } static int RegMatch (short Expected, short Actual) /* Check for a register match. If Expected has a value, it must be identical * to Actual. */ { return RegValIsUnknown (Expected) || (Expected == Actual); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptSize1 (CodeSeg* S) /* Do size optimization by calling special subroutines that preload registers. * This routine does not work standalone, it needs a following register load * removal pass. */ { CodeEntry* E; unsigned Changes = 0; unsigned I; /* Are we optimizing for size */ int OptForSize = (S->CodeSizeFactor < 100); /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { const CallDesc* D; /* Get next entry */ E = CS_GetEntry (S, I); /* Check if it's a subroutine call */ if (E->OPC == OP65_JSR && (D = FindCall (E->Arg)) != 0) { /* Get input register info for this insn */ const RegContents* In = &E->RI->In; /* FindCall finds the first entry that matches our function name. * The names are listed in "best match" order, so search for the * first one, that fulfills our conditions. */ while (1) { /* Check the registers and allow slower code only if * optimizing for size. */ if ((OptForSize || (D->Flags & F_SLOWER) == 0) && RegMatch (D->Regs.RegA, In->RegA) && RegMatch (D->Regs.RegX, In->RegX) && RegMatch (D->Regs.RegY, In->RegY) && RegMatch (D->Regs.SRegLo, In->SRegLo) && RegMatch (D->Regs.SRegHi, In->SRegHi)) { /* Ok, match for all conditions */ CodeEntry* X; X = NewCodeEntry (E->OPC, E->AM, D->ShortFunc, 0, E->LI); CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); /* Remember that we had changes */ ++Changes; /* Done */ break; } /* Next table entry, bail out if next entry not valid */ if (++D >= CallTable + CALL_COUNT || strcmp (D->LongFunc, E->Arg) != 0) { /* End of table or entries reached */ break; } } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptSize2 (CodeSeg* S) /* Do size optimization by using shorter code sequences, even if this * introduces relations between instructions. This step must be one of the * last steps, because it makes further work much more difficult. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Get the input registers */ const RegContents* In = &E->RI->In; /* Assume we have no replacement */ CodeEntry* X = 0; /* Check the instruction */ switch (E->OPC) { case OP65_LDA: if (CE_IsConstImm (E)) { short Val = (short) E->Num; if (Val == In->RegX) { X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, E->LI); } else if (Val == In->RegY) { X = NewCodeEntry (OP65_TYA, AM65_IMP, 0, 0, E->LI); } else if (RegValIsKnown (In->RegA) && (CPUIsets[CPU] & CPU_ISET_65SC02) != 0) { if (Val == ((In->RegA - 1) & 0xFF)) { X = NewCodeEntry (OP65_DEA, AM65_IMP, 0, 0, E->LI); } else if (Val == ((In->RegA + 1) & 0xFF)) { X = NewCodeEntry (OP65_INA, AM65_IMP, 0, 0, E->LI); } } } break; case OP65_LDX: if (CE_IsConstImm (E)) { short Val = (short) E->Num; if (RegValIsKnown (In->RegX) && Val == ((In->RegX - 1) & 0xFF)) { X = NewCodeEntry (OP65_DEX, AM65_IMP, 0, 0, E->LI); } else if (RegValIsKnown (In->RegX) && Val == ((In->RegX + 1) & 0xFF)) { X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI); } else if (Val == In->RegA) { X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, E->LI); } } break; case OP65_LDY: if (CE_IsConstImm (E)) { short Val = (short) E->Num; if (RegValIsKnown (In->RegY) && Val == ((In->RegY - 1) & 0xFF)) { X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, E->LI); } else if (RegValIsKnown (In->RegY) && Val == ((In->RegY + 1) & 0xFF)) { X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, E->LI); } else if (Val == In->RegA) { X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, E->LI); } } break; default: /* Avoid gcc warnings */ break; } /* Insert the replacement if we have one */ if (X) { CS_InsertEntry (S, X, I+1); CS_DelEntry (S, I); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
843
./cc65/src/cc65/coptpush.c
/*****************************************************************************/ /* */ /* coptpush.c */ /* */ /* Optimize push sequences */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptpush.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptPush1 (CodeSeg* S) /* Given a sequence * * jsr ldaxysp * jsr pushax * * If a/x are not used later, and Y is known, replace that by * * ldy #xx+2 * jsr pushwysp * * saving 3 bytes and several cycles. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxysp") && RegValIsKnown (L[0]->RI->In.RegY) && L[0]->RI->In.RegY < 0xFE && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax") && !RegAXUsed (S, I+2)) { /* Insert new code behind the pushax */ const char* Arg; CodeEntry* X; /* ldy #xx+1 */ Arg = MakeHexArg (L[0]->RI->In.RegY+2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+2); /* jsr pushwysp */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwysp", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPush2 (CodeSeg* S) /* A sequence * * jsr ldaxidx * jsr pushax * * may get replaced by * * jsr pushwidx * */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "ldaxidx") && (L[1] = CS_GetNextEntry (S, I)) != 0 && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "pushax")) { /* Insert new code behind the pushax */ CodeEntry* X; /* jsr pushwidx */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "pushwidx", 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
844
./cc65/src/cc65/global.c
/*****************************************************************************/ /* */ /* global.c */ /* */ /* Global variables for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "global.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ unsigned char AddSource = 0; /* Add source lines as comments */ unsigned char DebugInfo = 0; /* Add debug info to the obj */ unsigned char PreprocessOnly = 0; /* Just preprocess the input */ unsigned char DebugOptOutput = 0; /* Output debug stuff */ unsigned RegisterSpace = 6; /* Space available for register vars */ /* Stackable options */ IntStack WritableStrings = INTSTACK(0); /* Literal strings are r/w */ IntStack LocalStrings = INTSTACK(0); /* Emit string literals immediately */ IntStack InlineStdFuncs = INTSTACK(0); /* Inline some known functions */ IntStack EnableRegVars = INTSTACK(0); /* Enable register variables */ IntStack AllowRegVarAddr = INTSTACK(0); /* Allow taking addresses of register vars */ IntStack RegVarsToCallStack = INTSTACK(0); /* Save reg variables on call stack */ IntStack StaticLocals = INTSTACK(0); /* Make local variables static */ IntStack SignedChars = INTSTACK(0); /* Make characters signed by default */ IntStack CheckStack = INTSTACK(0); /* Generate stack overflow checks */ IntStack Optimize = INTSTACK(0); /* Optimize flag */ IntStack CodeSizeFactor = INTSTACK(100);/* Size factor for generated code */ IntStack DataAlignment = INTSTACK(1); /* Alignment for data */ /* File names */ StrBuf DepName = STATIC_STRBUF_INITIALIZER; /* Name of dependencies file */ StrBuf FullDepName = STATIC_STRBUF_INITIALIZER; /* Name of full dependencies file */ StrBuf DepTarget = STATIC_STRBUF_INITIALIZER; /* Name of dependency target */
845
./cc65/src/cc65/codeent.c
/*****************************************************************************/ /* */ /* codeent.c */ /* */ /* Code segment entry */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> /* common */ #include "chartype.h" #include "check.h" #include "debugflag.h" #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "error.h" #include "global.h" #include "codelab.h" #include "opcodes.h" #include "output.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Empty argument */ static char EmptyArg[] = ""; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void FreeArg (char* Arg) /* Free a code entry argument */ { if (Arg != EmptyArg) { xfree (Arg); } } static char* GetArgCopy (const char* Arg) /* Create an argument copy for assignment */ { if (Arg && Arg[0] != '\0') { /* Create a copy */ return xstrdup (Arg); } else { /* Use the empty argument string */ return EmptyArg; } } static int NumArg (const char* Arg, unsigned long* Num) /* If the given argument is numerical, convert it and return true. Otherwise * set Num to zero and return false. */ { char* End; unsigned long Val; /* Determine the base */ int Base = 10; if (*Arg == '$') { ++Arg; Base = 16; } else if (*Arg == '%') { ++Arg; Base = 2; } /* Convert the value. strtol is not exactly what we want here, but it's * cheap and may be replaced by something fancier later. */ Val = strtoul (Arg, &End, Base); /* Check if the conversion was successful */ if (*End != '\0') { /* Could not convert */ *Num = 0; return 0; } else { /* Conversion ok */ *Num = Val; return 1; } } static void SetUseChgInfo (CodeEntry* E, const OPCDesc* D) /* Set the Use and Chg in E */ { const ZPInfo* Info; /* If this is a subroutine call, or a jump to an external function, * lookup the information about this function and use it. The jump itself * does not change any registers, so we don't need to use the data from D. */ if ((E->Info & (OF_UBRA | OF_CALL)) != 0 && E->JumpTo == 0) { /* A subroutine call or jump to external symbol (function exit) */ GetFuncInfo (E->Arg, &E->Use, &E->Chg); } else { /* Some other instruction. Use the values from the opcode description * plus addressing mode info. */ E->Use = D->Use | GetAMUseInfo (E->AM); E->Chg = D->Chg; /* Check for special zero page registers used */ switch (E->AM) { case AM65_ACC: if (E->OPC == OP65_ASL || E->OPC == OP65_DEC || E->OPC == OP65_INC || E->OPC == OP65_LSR || E->OPC == OP65_ROL || E->OPC == OP65_ROR) { /* A is changed by these insns */ E->Chg |= REG_A; } break; case AM65_ZP: case AM65_ABS: /* Be conservative: */ case AM65_ZPX: case AM65_ABSX: case AM65_ABSY: Info = GetZPInfo (E->Arg); if (Info && Info->ByteUse != REG_NONE) { if (E->OPC == OP65_ASL || E->OPC == OP65_DEC || E->OPC == OP65_INC || E->OPC == OP65_LSR || E->OPC == OP65_ROL || E->OPC == OP65_ROR || E->OPC == OP65_TRB || E->OPC == OP65_TSB) { /* The zp loc is both, input and output */ E->Chg |= Info->ByteUse; E->Use |= Info->ByteUse; } else if ((E->Info & OF_STORE) != 0) { /* Just output */ E->Chg |= Info->ByteUse; } else { /* Input only */ E->Use |= Info->ByteUse; } } break; case AM65_ZPX_IND: case AM65_ZP_INDY: case AM65_ZP_IND: Info = GetZPInfo (E->Arg); if (Info && Info->ByteUse != REG_NONE) { /* These addressing modes will never change the zp loc */ E->Use |= Info->WordUse; } break; default: /* Keep gcc silent */ break; } } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* MakeHexArg (unsigned Num) /* Convert Num into a string in the form $XY, suitable for passing it as an * argument to NewCodeEntry, and return a pointer to the string. * BEWARE: The function returns a pointer to a static buffer, so the value is * gone if you call it twice (and apart from that it's not thread and signal * safe). */ { static char Buf[16]; xsprintf (Buf, sizeof (Buf), "$%02X", (unsigned char) Num); return Buf; } CodeEntry* NewCodeEntry (opc_t OPC, am_t AM, const char* Arg, CodeLabel* JumpTo, LineInfo* LI) /* Create a new code entry, initialize and return it */ { /* Get the opcode description */ const OPCDesc* D = GetOPCDesc (OPC); /* Allocate memory */ CodeEntry* E = xmalloc (sizeof (CodeEntry)); /* Initialize the fields */ E->OPC = D->OPC; E->AM = AM; E->Size = GetInsnSize (E->OPC, E->AM); E->Arg = GetArgCopy (Arg); E->Flags = NumArg (E->Arg, &E->Num)? CEF_NUMARG : 0; /* Needs E->Arg */ E->Info = D->Info; E->JumpTo = JumpTo; E->LI = UseLineInfo (LI); E->RI = 0; SetUseChgInfo (E, D); InitCollection (&E->Labels); /* If we have a label given, add this entry to the label */ if (JumpTo) { CollAppend (&JumpTo->JumpFrom, E); } /* Return the initialized struct */ return E; } void FreeCodeEntry (CodeEntry* E) /* Free the given code entry */ { /* Free the string argument if we have one */ FreeArg (E->Arg); /* Cleanup the collection */ DoneCollection (&E->Labels); /* Release the line info */ ReleaseLineInfo (E->LI); /* Delete the register info */ CE_FreeRegInfo (E); /* Free the entry */ xfree (E); } void CE_ReplaceOPC (CodeEntry* E, opc_t OPC) /* Replace the opcode of the instruction. This will also replace related info, * Size, Use and Chg, but it will NOT update any arguments or labels. */ { /* Get the opcode descriptor */ const OPCDesc* D = GetOPCDesc (OPC); /* Replace the opcode */ E->OPC = OPC; E->Info = D->Info; E->Size = GetInsnSize (E->OPC, E->AM); SetUseChgInfo (E, D); } int CodeEntriesAreEqual (const CodeEntry* E1, const CodeEntry* E2) /* Check if both code entries are equal */ { return (E1->OPC == E2->OPC && E1->AM == E2->AM && strcmp (E1->Arg, E2->Arg) == 0); } void CE_AttachLabel (CodeEntry* E, CodeLabel* L) /* Attach the label to the entry */ { /* Add it to the entries label list */ CollAppend (&E->Labels, L); /* Tell the label about it's owner */ L->Owner = E; } void CE_ClearJumpTo (CodeEntry* E) /* Clear the JumpTo entry and the argument (which contained the name of the * label). Note: The function will not clear the backpointer from the label, * so use it with care. */ { /* Clear the JumpTo entry */ E->JumpTo = 0; /* Clear the argument and assign the empty one */ FreeArg (E->Arg); E->Arg = EmptyArg; } void CE_MoveLabel (CodeLabel* L, CodeEntry* E) /* Move the code label L from it's former owner to the code entry E. */ { /* Delete the label from the owner */ CollDeleteItem (&L->Owner->Labels, L); /* Set the new owner */ CollAppend (&E->Labels, L); L->Owner = E; } void CE_SetArg (CodeEntry* E, const char* Arg) /* Replace the argument by the new one. */ { /* Free the old argument */ FreeArg (E->Arg); /* Assign the new one */ E->Arg = GetArgCopy (Arg); } void CE_SetNumArg (CodeEntry* E, long Num) /* Set a new numeric argument for the given code entry that must already * have a numeric argument. */ { char Buf[16]; /* Check that the entry has a numerical argument */ CHECK (E->Flags & CEF_NUMARG); /* Make the new argument string */ if (E->Size == 2) { Num &= 0xFF; xsprintf (Buf, sizeof (Buf), "$%02X", (unsigned) Num); } else if (E->Size == 3) { Num &= 0xFFFF; xsprintf (Buf, sizeof (Buf), "$%04X", (unsigned) Num); } else { Internal ("Invalid instruction size in CE_SetNumArg"); } /* Replace the argument by the new one */ CE_SetArg (E, Buf); /* Use the new numerical value */ E->Num = Num; } int CE_IsConstImm (const CodeEntry* E) /* Return true if the argument of E is a constant immediate value */ { return (E->AM == AM65_IMM && CE_HasNumArg (E)); } int CE_IsKnownImm (const CodeEntry* E, unsigned long Num) /* Return true if the argument of E is a constant immediate value that is * equal to Num. */ { return (E->AM == AM65_IMM && CE_HasNumArg (E) && E->Num == Num); } int CE_UseLoadFlags (CodeEntry* E) /* Return true if the instruction uses any flags that are set by a load of * a register (N and Z). */ { /* Follow unconditional branches, but beware of endless loops. After this, * E will point to the first entry that is not a branch. */ if (E->Info & OF_UBRA) { Collection C = AUTO_COLLECTION_INITIALIZER; /* Follow the chain */ while (E->Info & OF_UBRA) { /* Remember the entry so we can detect loops */ CollAppend (&C, E); /* Check the target */ if (E->JumpTo == 0 || CollIndex (&C, E->JumpTo->Owner) >= 0) { /* Unconditional jump to external symbol, or endless loop. */ DoneCollection (&C); return 0; /* Flags not used */ } /* Follow the chain */ E = E->JumpTo->Owner; } /* Delete the collection */ DoneCollection (&C); } /* A branch will use the flags */ if (E->Info & OF_FBRA) { return 1; } /* Call of a boolean transformer routine will also use the flags */ if (E->OPC == OP65_JSR) { /* Get the condition that is evaluated and check it */ switch (FindBoolCmpCond (E->Arg)) { case CMP_EQ: case CMP_NE: case CMP_GT: case CMP_GE: case CMP_LT: case CMP_LE: case CMP_UGT: case CMP_ULE: /* Will use the N or Z flags */ return 1; case CMP_UGE: /* Uses only carry */ case CMP_ULT: /* Dito */ default: /* No bool transformer subroutine */ return 0; } } /* Anything else */ return 0; } void CE_FreeRegInfo (CodeEntry* E) /* Free an existing register info struct */ { if (E->RI) { FreeRegInfo (E->RI); E->RI = 0; } } void CE_GenRegInfo (CodeEntry* E, RegContents* InputRegs) /* Generate register info for this instruction. If an old info exists, it is * overwritten. */ { /* Pointers to the register contents */ RegContents* In; RegContents* Out; /* Function register usage */ unsigned short Use, Chg; /* If we don't have a register info struct, allocate one. */ if (E->RI == 0) { E->RI = NewRegInfo (InputRegs); } else { if (InputRegs) { E->RI->In = *InputRegs; } else { RC_Invalidate (&E->RI->In); } E->RI->Out2 = E->RI->Out = E->RI->In; } /* Get pointers to the register contents */ In = &E->RI->In; Out = &E->RI->Out; /* Handle the different instructions */ switch (E->OPC) { case OP65_ADC: /* We don't know the value of the carry, so the result is * always unknown. */ Out->RegA = UNKNOWN_REGVAL; break; case OP65_AND: if (RegValIsKnown (In->RegA)) { if (CE_IsConstImm (E)) { Out->RegA = In->RegA & (short) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegA = In->RegA & In->Tmp1; break; case REG_PTR1_LO: Out->RegA = In->RegA & In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegA = In->RegA & In->Ptr1Hi; break; case REG_SREG_LO: Out->RegA = In->RegA & In->SRegLo; break; case REG_SREG_HI: Out->RegA = In->RegA & In->SRegHi; break; default: Out->RegA = UNKNOWN_REGVAL; break; } } else { Out->RegA = UNKNOWN_REGVAL; } } else if (CE_IsKnownImm (E, 0)) { /* A and $00 does always give zero */ Out->RegA = 0; } break; case OP65_ASL: if (E->AM == AM65_ACC && RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA << 1) & 0xFF; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = (In->Tmp1 << 1) & 0xFF; break; case REG_PTR1_LO: Out->Ptr1Lo = (In->Ptr1Lo << 1) & 0xFF; break; case REG_PTR1_HI: Out->Ptr1Hi = (In->Ptr1Hi << 1) & 0xFF; break; case REG_SREG_LO: Out->SRegLo = (In->SRegLo << 1) & 0xFF; break; case REG_SREG_HI: Out->SRegHi = (In->SRegHi << 1) & 0xFF; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_BCC: break; case OP65_BCS: break; case OP65_BEQ: break; case OP65_BIT: break; case OP65_BMI: break; case OP65_BNE: break; case OP65_BPL: break; case OP65_BRA: break; case OP65_BRK: break; case OP65_BVC: break; case OP65_BVS: break; case OP65_CLC: break; case OP65_CLD: break; case OP65_CLI: break; case OP65_CLV: break; case OP65_CMP: break; case OP65_CPX: break; case OP65_CPY: break; case OP65_DEA: if (RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA - 1) & 0xFF; } break; case OP65_DEC: if (E->AM == AM65_ACC && RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA - 1) & 0xFF; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = (In->Tmp1 - 1) & 0xFF; break; case REG_PTR1_LO: Out->Ptr1Lo = (In->Ptr1Lo - 1) & 0xFF; break; case REG_PTR1_HI: Out->Ptr1Hi = (In->Ptr1Hi - 1) & 0xFF; break; case REG_SREG_LO: Out->SRegLo = (In->SRegLo - 1) & 0xFF; break; case REG_SREG_HI: Out->SRegHi = (In->SRegHi - 1) & 0xFF; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_DEX: if (RegValIsKnown (In->RegX)) { Out->RegX = (In->RegX - 1) & 0xFF; } break; case OP65_DEY: if (RegValIsKnown (In->RegY)) { Out->RegY = (In->RegY - 1) & 0xFF; } break; case OP65_EOR: if (RegValIsKnown (In->RegA)) { if (CE_IsConstImm (E)) { Out->RegA = In->RegA ^ (short) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegA = In->RegA ^ In->Tmp1; break; case REG_PTR1_LO: Out->RegA = In->RegA ^ In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegA = In->RegA ^ In->Ptr1Hi; break; case REG_SREG_LO: Out->RegA = In->RegA ^ In->SRegLo; break; case REG_SREG_HI: Out->RegA = In->RegA ^ In->SRegHi; break; default: Out->RegA = UNKNOWN_REGVAL; break; } } else { Out->RegA = UNKNOWN_REGVAL; } } break; case OP65_INA: if (RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA + 1) & 0xFF; } break; case OP65_INC: if (E->AM == AM65_ACC && RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA + 1) & 0xFF; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = (In->Tmp1 + 1) & 0xFF; break; case REG_PTR1_LO: Out->Ptr1Lo = (In->Ptr1Lo + 1) & 0xFF; break; case REG_PTR1_HI: Out->Ptr1Hi = (In->Ptr1Hi + 1) & 0xFF; break; case REG_SREG_LO: Out->SRegLo = (In->SRegLo + 1) & 0xFF; break; case REG_SREG_HI: Out->SRegHi = (In->SRegHi + 1) & 0xFF; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_INX: if (RegValIsKnown (In->RegX)) { Out->RegX = (In->RegX + 1) & 0xFF; } break; case OP65_INY: if (RegValIsKnown (In->RegY)) { Out->RegY = (In->RegY + 1) & 0xFF; } break; case OP65_JCC: break; case OP65_JCS: break; case OP65_JEQ: break; case OP65_JMI: break; case OP65_JMP: break; case OP65_JNE: break; case OP65_JPL: break; case OP65_JSR: /* Get the code info for the function */ GetFuncInfo (E->Arg, &Use, &Chg); if (Chg & REG_A) { Out->RegA = UNKNOWN_REGVAL; } if (Chg & REG_X) { Out->RegX = UNKNOWN_REGVAL; } if (Chg & REG_Y) { Out->RegY = UNKNOWN_REGVAL; } if (Chg & REG_TMP1) { Out->Tmp1 = UNKNOWN_REGVAL; } if (Chg & REG_PTR1_LO) { Out->Ptr1Lo = UNKNOWN_REGVAL; } if (Chg & REG_PTR1_HI) { Out->Ptr1Hi = UNKNOWN_REGVAL; } if (Chg & REG_SREG_LO) { Out->SRegLo = UNKNOWN_REGVAL; } if (Chg & REG_SREG_HI) { Out->SRegHi = UNKNOWN_REGVAL; } /* ## FIXME: Quick hack for some known functions: */ if (strcmp (E->Arg, "complax") == 0) { if (RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA ^ 0xFF); } if (RegValIsKnown (In->RegX)) { Out->RegX = (In->RegX ^ 0xFF); } } else if (strcmp (E->Arg, "tosandax") == 0) { if (In->RegA == 0) { Out->RegA = 0; } if (In->RegX == 0) { Out->RegX = 0; } } else if (strcmp (E->Arg, "tosaslax") == 0) { if (RegValIsKnown (In->RegA) && (In->RegA & 0x0F) >= 8) { printf ("Hey!\n"); Out->RegA = 0; } } else if (strcmp (E->Arg, "tosorax") == 0) { if (In->RegA == 0xFF) { Out->RegA = 0xFF; } if (In->RegX == 0xFF) { Out->RegX = 0xFF; } } else if (strcmp (E->Arg, "tosshlax") == 0) { if ((In->RegA & 0x0F) >= 8) { Out->RegA = 0; } } else if (FindBoolCmpCond (E->Arg) != CMP_INV || FindTosCmpCond (E->Arg) != CMP_INV) { /* Result is boolean value, so X is zero on output */ Out->RegX = 0; } break; case OP65_JVC: break; case OP65_JVS: break; case OP65_LDA: if (CE_IsConstImm (E)) { Out->RegA = (unsigned char) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegA = In->Tmp1; break; case REG_PTR1_LO: Out->RegA = In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegA = In->Ptr1Hi; break; case REG_SREG_LO: Out->RegA = In->SRegLo; break; case REG_SREG_HI: Out->RegA = In->SRegHi; break; default: Out->RegA = UNKNOWN_REGVAL; break; } } else { /* A is now unknown */ Out->RegA = UNKNOWN_REGVAL; } break; case OP65_LDX: if (CE_IsConstImm (E)) { Out->RegX = (unsigned char) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegX = In->Tmp1; break; case REG_PTR1_LO: Out->RegX = In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegX = In->Ptr1Hi; break; case REG_SREG_LO: Out->RegX = In->SRegLo; break; case REG_SREG_HI: Out->RegX = In->SRegHi; break; default: Out->RegX = UNKNOWN_REGVAL; break; } } else { /* X is now unknown */ Out->RegX = UNKNOWN_REGVAL; } break; case OP65_LDY: if (CE_IsConstImm (E)) { Out->RegY = (unsigned char) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegY = In->Tmp1; break; case REG_PTR1_LO: Out->RegY = In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegY = In->Ptr1Hi; break; case REG_SREG_LO: Out->RegY = In->SRegLo; break; case REG_SREG_HI: Out->RegY = In->SRegHi; break; default: Out->RegY = UNKNOWN_REGVAL; break; } } else { /* Y is now unknown */ Out->RegY = UNKNOWN_REGVAL; } break; case OP65_LSR: if (E->AM == AM65_ACC && RegValIsKnown (In->RegA)) { Out->RegA = (In->RegA >> 1) & 0xFF; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = (In->Tmp1 >> 1) & 0xFF; break; case REG_PTR1_LO: Out->Ptr1Lo = (In->Ptr1Lo >> 1) & 0xFF; break; case REG_PTR1_HI: Out->Ptr1Hi = (In->Ptr1Hi >> 1) & 0xFF; break; case REG_SREG_LO: Out->SRegLo = (In->SRegLo >> 1) & 0xFF; break; case REG_SREG_HI: Out->SRegHi = (In->SRegHi >> 1) & 0xFF; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_NOP: break; case OP65_ORA: if (RegValIsKnown (In->RegA)) { if (CE_IsConstImm (E)) { Out->RegA = In->RegA | (short) E->Num; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Use & REG_ZP, In)) { case REG_TMP1: Out->RegA = In->RegA | In->Tmp1; break; case REG_PTR1_LO: Out->RegA = In->RegA | In->Ptr1Lo; break; case REG_PTR1_HI: Out->RegA = In->RegA | In->Ptr1Hi; break; case REG_SREG_LO: Out->RegA = In->RegA | In->SRegLo; break; case REG_SREG_HI: Out->RegA = In->RegA | In->SRegHi; break; default: Out->RegA = UNKNOWN_REGVAL; break; } } else { /* A is now unknown */ Out->RegA = UNKNOWN_REGVAL; } } else if (CE_IsKnownImm (E, 0xFF)) { /* ORA with 0xFF does always give 0xFF */ Out->RegA = 0xFF; } break; case OP65_PHA: break; case OP65_PHP: break; case OP65_PHX: break; case OP65_PHY: break; case OP65_PLA: Out->RegA = UNKNOWN_REGVAL; break; case OP65_PLP: break; case OP65_PLX: Out->RegX = UNKNOWN_REGVAL; break; case OP65_PLY: Out->RegY = UNKNOWN_REGVAL; break; case OP65_ROL: /* We don't know the value of the carry bit */ if (E->AM == AM65_ACC) { Out->RegA = UNKNOWN_REGVAL; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = UNKNOWN_REGVAL; break; case REG_PTR1_LO: Out->Ptr1Lo = UNKNOWN_REGVAL; break; case REG_PTR1_HI: Out->Ptr1Hi = UNKNOWN_REGVAL; break; case REG_SREG_LO: Out->SRegLo = UNKNOWN_REGVAL; break; case REG_SREG_HI: Out->SRegHi = UNKNOWN_REGVAL; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_ROR: /* We don't know the value of the carry bit */ if (E->AM == AM65_ACC) { Out->RegA = UNKNOWN_REGVAL; } else if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = UNKNOWN_REGVAL; break; case REG_PTR1_LO: Out->Ptr1Lo = UNKNOWN_REGVAL; break; case REG_PTR1_HI: Out->Ptr1Hi = UNKNOWN_REGVAL; break; case REG_SREG_LO: Out->SRegLo = UNKNOWN_REGVAL; break; case REG_SREG_HI: Out->SRegHi = UNKNOWN_REGVAL; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_RTI: break; case OP65_RTS: break; case OP65_SBC: /* We don't know the value of the carry bit */ Out->RegA = UNKNOWN_REGVAL; break; case OP65_SEC: break; case OP65_SED: break; case OP65_SEI: break; case OP65_STA: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, 0)) { case REG_TMP1: Out->Tmp1 = In->RegA; break; case REG_PTR1_LO: Out->Ptr1Lo = In->RegA; break; case REG_PTR1_HI: Out->Ptr1Hi = In->RegA; break; case REG_SREG_LO: Out->SRegLo = In->RegA; break; case REG_SREG_HI: Out->SRegHi = In->RegA; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_STX: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, 0)) { case REG_TMP1: Out->Tmp1 = In->RegX; break; case REG_PTR1_LO: Out->Ptr1Lo = In->RegX; break; case REG_PTR1_HI: Out->Ptr1Hi = In->RegX; break; case REG_SREG_LO: Out->SRegLo = In->RegX; break; case REG_SREG_HI: Out->SRegHi = In->RegX; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_STY: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, 0)) { case REG_TMP1: Out->Tmp1 = In->RegY; break; case REG_PTR1_LO: Out->Ptr1Lo = In->RegY; break; case REG_PTR1_HI: Out->Ptr1Hi = In->RegY; break; case REG_SREG_LO: Out->SRegLo = In->RegY; break; case REG_SREG_HI: Out->SRegHi = In->RegY; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_STZ: if (E->AM == AM65_ZP) { switch (GetKnownReg (E->Chg & REG_ZP, 0)) { case REG_TMP1: Out->Tmp1 = 0; break; case REG_PTR1_LO: Out->Ptr1Lo = 0; break; case REG_PTR1_HI: Out->Ptr1Hi = 0; break; case REG_SREG_LO: Out->SRegLo = 0; break; case REG_SREG_HI: Out->SRegHi = 0; break; } } else if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } break; case OP65_TAX: Out->RegX = In->RegA; break; case OP65_TAY: Out->RegY = In->RegA; break; case OP65_TRB: if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } else if (E->AM == AM65_ZP) { if (RegValIsKnown (In->RegA)) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 &= ~In->RegA; break; case REG_PTR1_LO: Out->Ptr1Lo &= ~In->RegA; break; case REG_PTR1_HI: Out->Ptr1Hi &= ~In->RegA; break; case REG_SREG_LO: Out->SRegLo &= ~In->RegA; break; case REG_SREG_HI: Out->SRegHi &= ~In->RegA; break; } } else { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = UNKNOWN_REGVAL; break; case REG_PTR1_LO: Out->Ptr1Lo = UNKNOWN_REGVAL; break; case REG_PTR1_HI: Out->Ptr1Hi = UNKNOWN_REGVAL; break; case REG_SREG_LO: Out->SRegLo = UNKNOWN_REGVAL; break; case REG_SREG_HI: Out->SRegHi = UNKNOWN_REGVAL; break; } } } break; case OP65_TSB: if (E->AM == AM65_ZPX) { /* Invalidates all ZP registers */ RC_InvalidateZP (Out); } else if (E->AM == AM65_ZP) { if (RegValIsKnown (In->RegA)) { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 |= In->RegA; break; case REG_PTR1_LO: Out->Ptr1Lo |= In->RegA; break; case REG_PTR1_HI: Out->Ptr1Hi |= In->RegA; break; case REG_SREG_LO: Out->SRegLo |= In->RegA; break; case REG_SREG_HI: Out->SRegHi |= In->RegA; break; } } else { switch (GetKnownReg (E->Chg & REG_ZP, In)) { case REG_TMP1: Out->Tmp1 = UNKNOWN_REGVAL; break; case REG_PTR1_LO: Out->Ptr1Lo = UNKNOWN_REGVAL; break; case REG_PTR1_HI: Out->Ptr1Hi = UNKNOWN_REGVAL; break; case REG_SREG_LO: Out->SRegLo = UNKNOWN_REGVAL; break; case REG_SREG_HI: Out->SRegHi = UNKNOWN_REGVAL; break; } } } break; case OP65_TSX: Out->RegX = UNKNOWN_REGVAL; break; case OP65_TXA: Out->RegA = In->RegX; break; case OP65_TXS: break; case OP65_TYA: Out->RegA = In->RegY; break; default: break; } } static char* RegInfoDesc (unsigned U, char* Buf) /* Return a string containing register info */ { Buf[0] = '\0'; strcat (Buf, U & REG_SREG_HI? "H" : "_"); strcat (Buf, U & REG_SREG_LO? "L" : "_"); strcat (Buf, U & REG_A? "A" : "_"); strcat (Buf, U & REG_X? "X" : "_"); strcat (Buf, U & REG_Y? "Y" : "_"); strcat (Buf, U & REG_TMP1? "T1" : "__"); strcat (Buf, U & REG_PTR1? "1" : "_"); strcat (Buf, U & REG_PTR2? "2" : "_"); strcat (Buf, U & REG_SAVE? "V" : "_"); strcat (Buf, U & REG_SP? "S" : "_"); return Buf; } static char* RegContentDesc (const RegContents* RC, char* Buf) /* Return a string containing register contents */ { char* B = Buf; if (RegValIsUnknown (RC->RegA)) { strcpy (B, "A:XX "); } else { sprintf (B, "A:%02X ", RC->RegA); } B += 5; if (RegValIsUnknown (RC->RegX)) { strcpy (B, "X:XX "); } else { sprintf (B, "X:%02X ", RC->RegX); } B += 5; if (RegValIsUnknown (RC->RegY)) { strcpy (B, "Y:XX"); } else { sprintf (B, "Y:%02X", RC->RegY); } B += 4; return Buf; } void CE_Output (const CodeEntry* E) /* Output the code entry to the output file */ { const OPCDesc* D; unsigned Chars; int Space; const char* Target; /* If we have a label, print that */ unsigned LabelCount = CollCount (&E->Labels); unsigned I; for (I = 0; I < LabelCount; ++I) { CL_Output (CollConstAt (&E->Labels, I)); } /* Get the opcode description */ D = GetOPCDesc (E->OPC); /* Print the mnemonic */ Chars = WriteOutput ("\t%s", D->Mnemo); /* Space to leave before the operand */ Space = 9 - Chars; /* Print the operand */ switch (E->AM) { case AM65_IMP: /* implicit */ break; case AM65_ACC: /* accumulator */ Chars += WriteOutput ("%*sa", Space, ""); break; case AM65_IMM: /* immidiate */ Chars += WriteOutput ("%*s#%s", Space, "", E->Arg); break; case AM65_ZP: case AM65_ABS: /* zeropage and absolute */ Chars += WriteOutput ("%*s%s", Space, "", E->Arg); break; case AM65_ZPX: case AM65_ABSX: /* zeropage,X and absolute,X */ Chars += WriteOutput ("%*s%s,x", Space, "", E->Arg); break; case AM65_ABSY: /* absolute,Y */ Chars += WriteOutput ("%*s%s,y", Space, "", E->Arg); break; case AM65_ZPX_IND: /* (zeropage,x) */ Chars += WriteOutput ("%*s(%s,x)", Space, "", E->Arg); break; case AM65_ZP_INDY: /* (zeropage),y */ Chars += WriteOutput ("%*s(%s),y", Space, "", E->Arg); break; case AM65_ZP_IND: /* (zeropage) */ Chars += WriteOutput ("%*s(%s)", Space, "", E->Arg); break; case AM65_BRA: /* branch */ Target = E->JumpTo? E->JumpTo->Name : E->Arg; Chars += WriteOutput ("%*s%s", Space, "", Target); break; default: Internal ("Invalid addressing mode"); } /* Print usage info if requested by the debugging flag */ if (Debug) { char Use [128]; char Chg [128]; WriteOutput ("%*s; USE: %-12s CHG: %-12s SIZE: %u", (int)(30-Chars), "", RegInfoDesc (E->Use, Use), RegInfoDesc (E->Chg, Chg), E->Size); if (E->RI) { char RegIn[32]; char RegOut[32]; WriteOutput (" In %s Out %s", RegContentDesc (&E->RI->In, RegIn), RegContentDesc (&E->RI->Out, RegOut)); } } /* Terminate the line */ WriteOutput ("\n"); }
846
./cc65/src/cc65/scanner.c
/*****************************************************************************/ /* */ /* scanner.c */ /* */ /* Source file line info structure */ /* */ /* */ /* */ /* (C) 1998-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <math.h> /* common */ #include "chartype.h" #include "fp.h" #include "tgttrans.h" /* cc65 */ #include "datatype.h" #include "error.h" #include "function.h" #include "global.h" #include "hexval.h" #include "ident.h" #include "input.h" #include "litpool.h" #include "preproc.h" #include "scanner.h" #include "standard.h" #include "symtab.h" /*****************************************************************************/ /* data */ /*****************************************************************************/ Token CurTok; /* The current token */ Token NextTok; /* The next token */ /* Token types */ enum { TT_C89 = 0x01 << STD_C89, /* Token valid in C89 */ TT_C99 = 0x01 << STD_C99, /* Token valid in C99 */ TT_CC65 = 0x01 << STD_CC65 /* Token valid in cc65 */ }; /* Token table */ static const struct Keyword { char* Key; /* Keyword name */ unsigned char Tok; /* The token */ unsigned char Std; /* Token supported in which standards? */ } Keywords [] = { { "_Pragma", TOK_PRAGMA, TT_C89 | TT_C99 | TT_CC65 }, /* !! */ { "__AX__", TOK_AX, TT_C89 | TT_C99 | TT_CC65 }, { "__A__", TOK_A, TT_C89 | TT_C99 | TT_CC65 }, { "__EAX__", TOK_EAX, TT_C89 | TT_C99 | TT_CC65 }, { "__X__", TOK_X, TT_C89 | TT_C99 | TT_CC65 }, { "__Y__", TOK_Y, TT_C89 | TT_C99 | TT_CC65 }, { "__asm__", TOK_ASM, TT_C89 | TT_C99 | TT_CC65 }, { "__attribute__", TOK_ATTRIBUTE, TT_C89 | TT_C99 | TT_CC65 }, { "__cdecl__", TOK_CDECL, TT_C89 | TT_C99 | TT_CC65 }, { "__far__", TOK_FAR, TT_C89 | TT_C99 | TT_CC65 }, { "__fastcall__", TOK_FASTCALL, TT_C89 | TT_C99 | TT_CC65 }, { "__inline__", TOK_INLINE, TT_C89 | TT_C99 | TT_CC65 }, { "__near__", TOK_NEAR, TT_C89 | TT_C99 | TT_CC65 }, { "asm", TOK_ASM, TT_CC65 }, { "auto", TOK_AUTO, TT_C89 | TT_C99 | TT_CC65 }, { "break", TOK_BREAK, TT_C89 | TT_C99 | TT_CC65 }, { "case", TOK_CASE, TT_C89 | TT_C99 | TT_CC65 }, { "cdecl", TOK_CDECL, TT_CC65 }, { "char", TOK_CHAR, TT_C89 | TT_C99 | TT_CC65 }, { "const", TOK_CONST, TT_C89 | TT_C99 | TT_CC65 }, { "continue", TOK_CONTINUE, TT_C89 | TT_C99 | TT_CC65 }, { "default", TOK_DEFAULT, TT_C89 | TT_C99 | TT_CC65 }, { "do", TOK_DO, TT_C89 | TT_C99 | TT_CC65 }, { "double", TOK_DOUBLE, TT_C89 | TT_C99 | TT_CC65 }, { "else", TOK_ELSE, TT_C89 | TT_C99 | TT_CC65 }, { "enum", TOK_ENUM, TT_C89 | TT_C99 | TT_CC65 }, { "extern", TOK_EXTERN, TT_C89 | TT_C99 | TT_CC65 }, { "far", TOK_FAR, TT_CC65 }, { "fastcall", TOK_FASTCALL, TT_CC65 }, { "float", TOK_FLOAT, TT_C89 | TT_C99 | TT_CC65 }, { "for", TOK_FOR, TT_C89 | TT_C99 | TT_CC65 }, { "goto", TOK_GOTO, TT_C89 | TT_C99 | TT_CC65 }, { "if", TOK_IF, TT_C89 | TT_C99 | TT_CC65 }, { "inline", TOK_INLINE, TT_C99 | TT_CC65 }, { "int", TOK_INT, TT_C89 | TT_C99 | TT_CC65 }, { "long", TOK_LONG, TT_C89 | TT_C99 | TT_CC65 }, { "near", TOK_NEAR, TT_CC65 }, { "register", TOK_REGISTER, TT_C89 | TT_C99 | TT_CC65 }, { "restrict", TOK_RESTRICT, TT_C99 | TT_CC65 }, { "return", TOK_RETURN, TT_C89 | TT_C99 | TT_CC65 }, { "short", TOK_SHORT, TT_C89 | TT_C99 | TT_CC65 }, { "signed", TOK_SIGNED, TT_C89 | TT_C99 | TT_CC65 }, { "sizeof", TOK_SIZEOF, TT_C89 | TT_C99 | TT_CC65 }, { "static", TOK_STATIC, TT_C89 | TT_C99 | TT_CC65 }, { "struct", TOK_STRUCT, TT_C89 | TT_C99 | TT_CC65 }, { "switch", TOK_SWITCH, TT_C89 | TT_C99 | TT_CC65 }, { "typedef", TOK_TYPEDEF, TT_C89 | TT_C99 | TT_CC65 }, { "union", TOK_UNION, TT_C89 | TT_C99 | TT_CC65 }, { "unsigned", TOK_UNSIGNED, TT_C89 | TT_C99 | TT_CC65 }, { "void", TOK_VOID, TT_C89 | TT_C99 | TT_CC65 }, { "volatile", TOK_VOLATILE, TT_C89 | TT_C99 | TT_CC65 }, { "while", TOK_WHILE, TT_C89 | TT_C99 | TT_CC65 }, }; #define KEY_COUNT (sizeof (Keywords) / sizeof (Keywords [0])) /* Stuff for determining the type of an integer constant */ #define IT_INT 0x01 #define IT_UINT 0x02 #define IT_LONG 0x04 #define IT_ULONG 0x08 /*****************************************************************************/ /* code */ /*****************************************************************************/ static int CmpKey (const void* Key, const void* Elem) /* Compare function for bsearch */ { return strcmp ((const char*) Key, ((const struct Keyword*) Elem)->Key); } static token_t FindKey (const char* Key) /* Find a keyword and return the token. Return IDENT if the token is not a * keyword. */ { struct Keyword* K; K = bsearch (Key, Keywords, KEY_COUNT, sizeof (Keywords [0]), CmpKey); if (K && (K->Std & (0x01 << IS_Get (&Standard))) != 0) { return K->Tok; } else { return TOK_IDENT; } } static int SkipWhite (void) /* Skip white space in the input stream, reading and preprocessing new lines * if necessary. Return 0 if end of file is reached, return 1 otherwise. */ { while (1) { while (CurC == '\0') { if (NextLine () == 0) { return 0; } Preprocess (); } if (IsSpace (CurC)) { NextChar (); } else { return 1; } } } int TokIsFuncSpec (const Token* T) /* Return true if the token is a function specifier */ { return (T->Tok == TOK_INLINE) || (T->Tok == TOK_FASTCALL) || (T->Tok == TOK_CDECL) || (T->Tok == TOK_NEAR) || (T->Tok == TOK_FAR); } void SymName (char* S) /* Read a symbol from the input stream. The first character must have been * checked before calling this function. The buffer is expected to be at * least of size MAX_IDENTLEN+1. */ { unsigned Len = 0; do { if (Len < MAX_IDENTLEN) { ++Len; *S++ = CurC; } NextChar (); } while (IsIdent (CurC) || IsDigit (CurC)); *S = '\0'; } int IsSym (char* S) /* If a symbol follows, read it and return 1, otherwise return 0 */ { if (IsIdent (CurC)) { SymName (S); return 1; } else { return 0; } } static void UnknownChar (char C) /* Error message for unknown character */ { Error ("Invalid input character with code %02X", C & 0xFF); NextChar (); /* Skip */ } static void SetTok (int tok) /* Set NextTok.Tok and bump line ptr */ { NextTok.Tok = tok; NextChar (); } static int ParseChar (void) /* Parse a character. Converts escape chars into character codes. */ { int C; int HadError; /* Check for escape chars */ if (CurC == '\\') { NextChar (); switch (CurC) { case '?': C = '\?'; break; case 'a': C = '\a'; break; case 'b': C = '\b'; break; case 'f': C = '\f'; break; case 'r': C = '\r'; break; case 'n': C = '\n'; break; case 't': C = '\t'; break; case 'v': C = '\v'; break; case '\"': C = '\"'; break; case '\'': C = '\''; break; case '\\': C = '\\'; break; case 'x': case 'X': /* Hex character constant */ if (!IsXDigit (NextC)) { Error ("\\x used with no following hex digits"); C = ' '; } else { HadError = 0; C = 0; while (IsXDigit (NextC)) { if ((C << 4) >= 256) { if (!HadError) { Error ("Hex character constant out of range"); HadError = 1; } } else { C = (C << 4) | HexVal (NextC); } NextChar (); } } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': /* Octal constant */ HadError = 0; C = HexVal (CurC); while (IsODigit (NextC)) { if ((C << 3) >= 256) { if (!HadError) { Error ("Octal character constant out of range"); HadError = 1; } } else { C = (C << 3) | HexVal (NextC); } NextChar (); } break; default: Error ("Illegal character constant"); C = ' '; /* Try to do error recovery, otherwise the compiler will spit * out thousands of errors in this place and abort. */ if (CurC != '\'' && CurC != '\0') { while (NextC != '\'' && NextC != '\"' && NextC != '\0') { NextChar (); } } break; } } else { C = CurC; } /* Skip the character read */ NextChar (); /* Do correct sign extension */ return SignExtendChar (C); } static void CharConst (void) /* Parse a character constant. */ { int C; /* Skip the quote */ NextChar (); /* Get character */ C = ParseChar (); /* Check for closing quote */ if (CurC != '\'') { Error ("`\'' expected"); } else { /* Skip the quote */ NextChar (); } /* Setup values and attributes */ NextTok.Tok = TOK_CCONST; /* Translate into target charset */ NextTok.IVal = SignExtendChar (TgtTranslateChar (C)); /* Character constants have type int */ NextTok.Type = type_int; } static void StringConst (void) /* Parse a quoted string */ { /* String buffer */ StrBuf S = AUTO_STRBUF_INITIALIZER; /* Assume next token is a string constant */ NextTok.Tok = TOK_SCONST; /* Concatenate strings. If at least one of the concenated strings is a wide * character literal, the whole string is a wide char literal, otherwise * it's a normal string literal. */ while (1) { /* Check if this is a normal or a wide char string */ if (CurC == 'L' && NextC == '\"') { /* Wide character literal */ NextTok.Tok = TOK_WCSCONST; NextChar (); NextChar (); } else if (CurC == '\"') { /* Skip the quote char */ NextChar (); } else { /* No string */ break; } /* Read until end of string */ while (CurC != '\"') { if (CurC == '\0') { Error ("Unexpected newline"); break; } SB_AppendChar (&S, ParseChar ()); } /* Skip closing quote char if there was one */ NextChar (); /* Skip white space, read new input */ SkipWhite (); } /* Terminate the string */ SB_AppendChar (&S, '\0'); /* Add the whole string to the literal pool */ NextTok.SVal = AddLiteralStr (&S); /* Free the buffer */ SB_Done (&S); } static void NumericConst (void) /* Parse a numeric constant */ { unsigned Base; /* Temporary number base */ unsigned Prefix; /* Base according to prefix */ StrBuf S = STATIC_STRBUF_INITIALIZER; int IsFloat; char C; unsigned DigitVal; unsigned long IVal; /* Value */ /* Check for a leading hex or octal prefix and determine the possible * integer types. */ if (CurC == '0') { /* Gobble 0 and examine next char */ NextChar (); if (toupper (CurC) == 'X') { Base = Prefix = 16; NextChar (); /* gobble "x" */ } else { Base = 10; /* Assume 10 for now - see below */ Prefix = 8; /* Actual prefix says octal */ } } else { Base = Prefix = 10; } /* Because floating point numbers don't have octal prefixes (a number * with a leading zero is decimal), we first have to read the number * before converting it, so we can determine if it's a float or an * integer. */ while (IsXDigit (CurC) && HexVal (CurC) < Base) { SB_AppendChar (&S, CurC); NextChar (); } SB_Terminate (&S); /* The following character tells us if we have an integer or floating * point constant. Note: Hexadecimal floating point constants aren't * supported in C89. */ IsFloat = (CurC == '.' || (Base == 10 && toupper (CurC) == 'E') || (Base == 16 && toupper (CurC) == 'P' && IS_Get (&Standard) >= STD_C99)); /* If we don't have a floating point type, an octal prefix results in an * octal base. */ if (!IsFloat && Prefix == 8) { Base = 8; } /* Since we do now know the correct base, convert the remembered input * into a number. */ SB_Reset (&S); IVal = 0; while ((C = SB_Get (&S)) != '\0') { DigitVal = HexVal (C); if (DigitVal >= Base) { Error ("Numeric constant contains digits beyond the radix"); } IVal = (IVal * Base) + DigitVal; } /* We don't need the string buffer any longer */ SB_Done (&S); /* Distinguish between integer and floating point constants */ if (!IsFloat) { unsigned Types; int HaveSuffix; /* Check for a suffix and determine the possible types */ HaveSuffix = 1; if (toupper (CurC) == 'U') { /* Unsigned type */ NextChar (); if (toupper (CurC) != 'L') { Types = IT_UINT | IT_ULONG; } else { NextChar (); Types = IT_ULONG; } } else if (toupper (CurC) == 'L') { /* Long type */ NextChar (); if (toupper (CurC) != 'U') { Types = IT_LONG | IT_ULONG; } else { NextChar (); Types = IT_ULONG; } } else { HaveSuffix = 0; if (Prefix == 10) { /* Decimal constants are of any type but uint */ Types = IT_INT | IT_LONG | IT_ULONG; } else { /* Octal or hex constants are of any type */ Types = IT_INT | IT_UINT | IT_LONG | IT_ULONG; } } /* Check the range to determine the type */ if (IVal > 0x7FFF) { /* Out of range for int */ Types &= ~IT_INT; /* If the value is in the range 0x8000..0xFFFF, unsigned int is not * allowed, and we don't have a type specifying suffix, emit a * warning, because the constant is of type long. */ if (IVal <= 0xFFFF && (Types & IT_UINT) == 0 && !HaveSuffix) { Warning ("Constant is long"); } } if (IVal > 0xFFFF) { /* Out of range for unsigned int */ Types &= ~IT_UINT; } if (IVal > 0x7FFFFFFF) { /* Out of range for long int */ Types &= ~IT_LONG; } /* Now set the type string to the smallest type in types */ if (Types & IT_INT) { NextTok.Type = type_int; } else if (Types & IT_UINT) { NextTok.Type = type_uint; } else if (Types & IT_LONG) { NextTok.Type = type_long; } else { NextTok.Type = type_ulong; } /* Set the value and the token */ NextTok.IVal = IVal; NextTok.Tok = TOK_ICONST; } else { /* Float constant */ Double FVal = FP_D_FromInt (IVal); /* Convert to double */ /* Check for a fractional part and read it */ if (CurC == '.') { Double Scale; /* Skip the dot */ NextChar (); /* Read fractional digits */ Scale = FP_D_Make (1.0); while (IsXDigit (CurC) && (DigitVal = HexVal (CurC)) < Base) { /* Get the value of this digit */ Double FracVal = FP_D_Div (FP_D_FromInt (DigitVal * Base), Scale); /* Add it to the float value */ FVal = FP_D_Add (FVal, FracVal); /* Scale base */ Scale = FP_D_Mul (Scale, FP_D_FromInt (DigitVal)); /* Skip the digit */ NextChar (); } } /* Check for an exponent and read it */ if ((Base == 16 && toupper (CurC) == 'F') || (Base == 10 && toupper (CurC) == 'E')) { unsigned Digits; unsigned Exp; /* Skip the exponent notifier */ NextChar (); /* Read an optional sign */ if (CurC == '-') { NextChar (); } else if (CurC == '+') { NextChar (); } /* Read exponent digits. Since we support only 32 bit floats * with a maximum exponent of +-/127, we read the exponent * part as integer with up to 3 digits and drop the remainder. * This avoids an overflow of Exp. The exponent is always * decimal, even for hex float consts. */ Digits = 0; Exp = 0; while (IsDigit (CurC)) { if (++Digits <= 3) { Exp = Exp * 10 + HexVal (CurC); } NextChar (); } /* Check for errors: We must have exponent digits, and not more * than three. */ if (Digits == 0) { Error ("Floating constant exponent has no digits"); } else if (Digits > 3) { Warning ("Floating constant exponent is too large"); } /* Scale the exponent and adjust the value accordingly */ if (Exp) { FVal = FP_D_Mul (FVal, FP_D_Make (pow (10, Exp))); } } /* Check for a suffix and determine the type of the constant */ if (toupper (CurC) == 'F') { NextChar (); NextTok.Type = type_float; } else { NextTok.Type = type_double; } /* Set the value and the token */ NextTok.FVal = FVal; NextTok.Tok = TOK_FCONST; } } void NextToken (void) /* Get next token from input stream */ { ident token; /* We have to skip white space here before shifting tokens, since the * tokens and the current line info is invalid at startup and will get * initialized by reading the first time from the file. Remember if * we were at end of input and handle that later. */ int GotEOF = (SkipWhite() == 0); /* Current token is the lookahead token */ if (CurTok.LI) { ReleaseLineInfo (CurTok.LI); } CurTok = NextTok; /* When reading the first time from the file, the line info in NextTok, * which was copied to CurTok is invalid. Since the information from * the token is used for error messages, we must make it valid. */ if (CurTok.LI == 0) { CurTok.LI = UseLineInfo (GetCurLineInfo ()); } /* Remember the starting position of the next token */ NextTok.LI = UseLineInfo (GetCurLineInfo ()); /* Now handle end of input. */ if (GotEOF) { /* End of file reached */ NextTok.Tok = TOK_CEOF; return; } /* Determine the next token from the lookahead */ if (IsDigit (CurC) || (CurC == '.' && IsDigit (NextC))) { /* A number */ NumericConst (); return; } /* Check for wide character literals */ if (CurC == 'L' && NextC == '\"') { StringConst (); return; } /* Check for keywords and identifiers */ if (IsSym (token)) { /* Check for a keyword */ if ((NextTok.Tok = FindKey (token)) != TOK_IDENT) { /* Reserved word found */ return; } /* No reserved word, check for special symbols */ if (token[0] == '_' && token[1] == '_') { /* Special symbols */ if (strcmp (token+2, "FILE__") == 0) { NextTok.SVal = AddLiteral (GetCurrentFile()); NextTok.Tok = TOK_SCONST; return; } else if (strcmp (token+2, "LINE__") == 0) { NextTok.Tok = TOK_ICONST; NextTok.IVal = GetCurrentLine(); NextTok.Type = type_int; return; } else if (strcmp (token+2, "func__") == 0) { /* __func__ is only defined in functions */ if (CurrentFunc) { NextTok.SVal = AddLiteral (F_GetFuncName (CurrentFunc)); NextTok.Tok = TOK_SCONST; return; } } } /* No reserved word but identifier */ strcpy (NextTok.Ident, token); NextTok.Tok = TOK_IDENT; return; } /* Monstrous switch statement ahead... */ switch (CurC) { case '!': NextChar (); if (CurC == '=') { SetTok (TOK_NE); } else { NextTok.Tok = TOK_BOOL_NOT; } break; case '\"': StringConst (); break; case '%': NextChar (); if (CurC == '=') { SetTok (TOK_MOD_ASSIGN); } else { NextTok.Tok = TOK_MOD; } break; case '&': NextChar (); switch (CurC) { case '&': SetTok (TOK_BOOL_AND); break; case '=': SetTok (TOK_AND_ASSIGN); break; default: NextTok.Tok = TOK_AND; } break; case '\'': CharConst (); break; case '(': SetTok (TOK_LPAREN); break; case ')': SetTok (TOK_RPAREN); break; case '*': NextChar (); if (CurC == '=') { SetTok (TOK_MUL_ASSIGN); } else { NextTok.Tok = TOK_STAR; } break; case '+': NextChar (); switch (CurC) { case '+': SetTok (TOK_INC); break; case '=': SetTok (TOK_PLUS_ASSIGN); break; default: NextTok.Tok = TOK_PLUS; } break; case ',': SetTok (TOK_COMMA); break; case '-': NextChar (); switch (CurC) { case '-': SetTok (TOK_DEC); break; case '=': SetTok (TOK_MINUS_ASSIGN); break; case '>': SetTok (TOK_PTR_REF); break; default: NextTok.Tok = TOK_MINUS; } break; case '.': NextChar (); if (CurC == '.') { NextChar (); if (CurC == '.') { SetTok (TOK_ELLIPSIS); } else { UnknownChar (CurC); } } else { NextTok.Tok = TOK_DOT; } break; case '/': NextChar (); if (CurC == '=') { SetTok (TOK_DIV_ASSIGN); } else { NextTok.Tok = TOK_DIV; } break; case ':': SetTok (TOK_COLON); break; case ';': SetTok (TOK_SEMI); break; case '<': NextChar (); switch (CurC) { case '=': SetTok (TOK_LE); break; case '<': NextChar (); if (CurC == '=') { SetTok (TOK_SHL_ASSIGN); } else { NextTok.Tok = TOK_SHL; } break; default: NextTok.Tok = TOK_LT; } break; case '=': NextChar (); if (CurC == '=') { SetTok (TOK_EQ); } else { NextTok.Tok = TOK_ASSIGN; } break; case '>': NextChar (); switch (CurC) { case '=': SetTok (TOK_GE); break; case '>': NextChar (); if (CurC == '=') { SetTok (TOK_SHR_ASSIGN); } else { NextTok.Tok = TOK_SHR; } break; default: NextTok.Tok = TOK_GT; } break; case '?': SetTok (TOK_QUEST); break; case '[': SetTok (TOK_LBRACK); break; case ']': SetTok (TOK_RBRACK); break; case '^': NextChar (); if (CurC == '=') { SetTok (TOK_XOR_ASSIGN); } else { NextTok.Tok = TOK_XOR; } break; case '{': SetTok (TOK_LCURLY); break; case '|': NextChar (); switch (CurC) { case '|': SetTok (TOK_BOOL_OR); break; case '=': SetTok (TOK_OR_ASSIGN); break; default: NextTok.Tok = TOK_OR; } break; case '}': SetTok (TOK_RCURLY); break; case '~': SetTok (TOK_COMP); break; default: UnknownChar (CurC); } } void SkipTokens (const token_t* TokenList, unsigned TokenCount) /* Skip tokens until we reach TOK_CEOF or a token in the given token list. * This routine is used for error recovery. */ { while (CurTok.Tok != TOK_CEOF) { /* Check if the current token is in the token list */ unsigned I; for (I = 0; I < TokenCount; ++I) { if (CurTok.Tok == TokenList[I]) { /* Found a token in the list */ return; } } /* Not in the list: Skip it */ NextToken (); } } int Consume (token_t Token, const char* ErrorMsg) /* Eat token if it is the next in the input stream, otherwise print an error * message. Returns true if the token was found and false otherwise. */ { if (CurTok.Tok == Token) { NextToken (); return 1; } else { Error ("%s", ErrorMsg); return 0; } } int ConsumeColon (void) /* Check for a colon and skip it. */ { return Consume (TOK_COLON, "`:' expected"); } int ConsumeSemi (void) /* Check for a semicolon and skip it. */ { /* Try do be smart about typos... */ if (CurTok.Tok == TOK_SEMI) { NextToken (); return 1; } else { Error ("`;' expected"); if (CurTok.Tok == TOK_COLON || CurTok.Tok == TOK_COMMA) { NextToken (); } return 0; } } int ConsumeComma (void) /* Check for a comma and skip it. */ { /* Try do be smart about typos... */ if (CurTok.Tok == TOK_COMMA) { NextToken (); return 1; } else { Error ("`,' expected"); if (CurTok.Tok == TOK_SEMI) { NextToken (); } return 0; } } int ConsumeLParen (void) /* Check for a left parenthesis and skip it */ { return Consume (TOK_LPAREN, "`(' expected"); } int ConsumeRParen (void) /* Check for a right parenthesis and skip it */ { return Consume (TOK_RPAREN, "`)' expected"); } int ConsumeLBrack (void) /* Check for a left bracket and skip it */ { return Consume (TOK_LBRACK, "`[' expected"); } int ConsumeRBrack (void) /* Check for a right bracket and skip it */ { return Consume (TOK_RBRACK, "`]' expected"); } int ConsumeLCurly (void) /* Check for a left curly brace and skip it */ { return Consume (TOK_LCURLY, "`{' expected"); } int ConsumeRCurly (void) /* Check for a right curly brace and skip it */ { return Consume (TOK_RCURLY, "`}' expected"); }
847
./cc65/src/cc65/dataseg.c
/*****************************************************************************/ /* */ /* dataseg.c */ /* */ /* Data segment structure */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "dataseg.h" #include "error.h" #include "output.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ DataSeg* NewDataSeg (const char* Name, SymEntry* Func) /* Create a new data segment, initialize and return it */ { /* Allocate memory */ DataSeg* S = xmalloc (sizeof (DataSeg)); /* Initialize the fields */ S->SegName = xstrdup (Name); S->Func = Func; InitCollection (&S->Lines); /* Return the new struct */ return S; } void DS_Append (DataSeg* Target, const DataSeg* Source) /* Append the data from Source to Target */ { unsigned I; /* Append all lines from Source to Target */ unsigned Count = CollCount (&Source->Lines); for (I = 0; I < Count; ++I) { CollAppend (&Target->Lines, xstrdup (CollConstAt (&Source->Lines, I))); } } void DS_AddVLine (DataSeg* S, const char* Format, va_list ap) /* Add a line to the given data segment */ { /* Format the line */ char Buf [256]; xvsprintf (Buf, sizeof (Buf), Format, ap); /* Add a copy to the data segment */ CollAppend (&S->Lines, xstrdup (Buf)); } void DS_AddLine (DataSeg* S, const char* Format, ...) /* Add a line to the given data segment */ { va_list ap; va_start (ap, Format); DS_AddVLine (S, Format, ap); va_end (ap); } void DS_Output (const DataSeg* S) /* Output the data segment data to the output file */ { unsigned I; /* Get the number of entries in this segment */ unsigned Count = CollCount (&S->Lines); /* If the segment is actually empty, bail out */ if (Count == 0) { return; } /* Output the segment directive */ WriteOutput (".segment\t\"%s\"\n\n", S->SegName); /* Output all entries */ for (I = 0; I < Count; ++I) { WriteOutput ("%s\n", (const char*) CollConstAt (&S->Lines, I)); } /* Add an additional newline after the segment output */ WriteOutput ("\n"); }
848
./cc65/src/cc65/anonname.c
/*****************************************************************************/ /* */ /* anonname.c */ /* */ /* Create names for anonymous variables/types */ /* */ /* */ /* */ /* (C) 2000-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "xsprintf.h" /* cc65 */ #include "anonname.h" #include "ident.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ static const char AnonTag[] = "$anon"; /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* AnonName (char* Buf, const char* Spec) /* Get a name for an anonymous variable or type. The given buffer is expected * to be IDENTSIZE characters long. A pointer to the buffer is returned. */ { static unsigned ACount = 0; xsprintf (Buf, IDENTSIZE, "%s-%s-%04X", AnonTag, Spec, ++ACount); return Buf; } int IsAnonName (const char* Name) /* Check if the given symbol name is that of an anonymous symbol */ { return (strncmp (Name, AnonTag, sizeof (AnonTag) - 1) == 0); }
849
./cc65/src/cc65/shiftexpr.c
/*****************************************************************************/ /* */ /* shiftexpr.c */ /* */ /* Parse the << and >> operators */ /* */ /* */ /* */ /* (C) 2004-2006 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "asmcode.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "exprdesc.h" #include "loadexpr.h" #include "scanner.h" #include "shiftexpr.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void ShiftExpr (struct ExprDesc* Expr) /* Parse the << and >> operators. */ { ExprDesc Expr2; CodeMark Mark1; CodeMark Mark2; token_t Tok; /* The operator token */ Type* EffType; /* Effective lhs type */ Type* ResultType; /* Type of the result */ unsigned ExprBits; /* Bits of the lhs operand */ unsigned GenFlags; /* Generator flags */ unsigned ltype; int rconst; /* Operand is a constant */ /* Evaluate the lhs */ ExprWithCheck (hie8, Expr); while (CurTok.Tok == TOK_SHL || CurTok.Tok == TOK_SHR) { /* All operators that call this function expect an int on the lhs */ if (!IsClassInt (Expr->Type)) { Error ("Integer expression expected"); ED_MakeConstAbsInt (Expr, 1); } /* Remember the operator token, then skip it */ Tok = CurTok.Tok; NextToken (); /* Get the type of the result */ ResultType = EffType = IntPromotion (Expr->Type); /* Prepare the code generator flags */ GenFlags = TypeOf (ResultType); /* Calculate the number of bits the lhs operand has */ ExprBits = SizeOf (ResultType) * 8; /* Get the lhs on stack */ GetCodePos (&Mark1); ltype = TypeOf (Expr->Type); if (ED_IsConstAbs (Expr)) { /* Constant value */ GetCodePos (&Mark2); g_push (ltype | CF_CONST, Expr->IVal); } else { /* Value not constant */ LoadExpr (CF_NONE, Expr); GetCodePos (&Mark2); g_push (ltype, 0); } /* Get the right hand side */ ExprWithCheck (hie8, &Expr2); /* Check the type of the rhs */ if (!IsClassInt (Expr2.Type)) { Error ("Integer expression expected"); ED_MakeConstAbsInt (&Expr2, 1); } /* Check for a constant right side expression */ rconst = ED_IsConstAbs (&Expr2); if (!rconst) { /* Not constant, load into the primary */ LoadExpr (CF_NONE, &Expr2); } else { /* The rhs is a constant numeric value. */ GenFlags |= CF_CONST; /* Remove the code that pushes the rhs onto the stack. */ RemoveCode (&Mark2); /* If the shift count is greater or equal than the bit count of * the operand, the behaviour is undefined according to the * standard. */ if (Expr2.IVal < 0 || Expr2.IVal >= (long) ExprBits) { Warning ("Shift count too large for operand type"); Expr2.IVal &= ExprBits - 1; } /* If the shift count is zero, nothing happens */ if (Expr2.IVal == 0) { /* Result is already in Expr, remove the generated code */ RemoveCode (&Mark1); /* Done */ goto Next; } /* If the left hand side is a constant, the result is constant */ if (ED_IsConstAbs (Expr)) { /* Evaluate the result */ switch (Tok) { case TOK_SHL: Expr->IVal <<= Expr2.IVal; break; case TOK_SHR: Expr->IVal >>= Expr2.IVal; break; default: /* Shutup gcc */ break; } /* Both operands are constant, remove the generated code */ RemoveCode (&Mark1); /* Done */ goto Next; } /* If we're shifting an integer or unsigned to the right, the * lhs has a const address, and the shift count is larger than 8, * we can load just the high byte as a char with the correct * signedness, and reduce the shift count by 8. If the remaining * shift count is zero, we're done. */ if (Tok == TOK_SHR && IsTypeInt (Expr->Type) && ED_IsLVal (Expr) && (ED_IsLocConst (Expr) || ED_IsLocStack (Expr)) && Expr2.IVal >= 8) { Type* OldType; /* Increase the address by one and decrease the shift count */ ++Expr->IVal; Expr2.IVal -= 8; /* Replace the type of the expression temporarily by the * corresponding char type. */ OldType = Expr->Type; if (IsSignUnsigned (Expr->Type)) { Expr->Type = type_uchar; } else { Expr->Type = type_schar; } /* Remove the generated load code */ RemoveCode (&Mark1); /* Generate again code for the load, this time with the new type */ LoadExpr (CF_NONE, Expr); /* Reset the type */ Expr->Type = OldType; /* If the shift count is now zero, we're done */ if (Expr2.IVal == 0) { /* Be sure to mark the value as in the primary */ goto MakeRVal; } } } /* Generate code */ switch (Tok) { case TOK_SHL: g_asl (GenFlags, Expr2.IVal); break; case TOK_SHR: g_asr (GenFlags, Expr2.IVal); break; default: break; } MakeRVal: /* We have a rvalue in the primary now */ ED_MakeRValExpr (Expr); Next: /* Set the type of the result */ Expr->Type = ResultType; } }
850
./cc65/src/cc65/coptptrstore.c
/*****************************************************************************/ /* */ /* coptptrstore.c */ /* */ /* Optimize stores through pointers */ /* */ /* */ /* */ /* (C) 2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "chartype.h" #include "strbuf.h" #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptptrstore.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static unsigned OptPtrStore1Sub (CodeSeg* S, unsigned I, CodeEntry** const L) /* Check if this is one of the allowed suboperation for OptPtrStore1 */ { /* Check for a label attached to the entry */ if (CE_HasLabel (L[0])) { return 0; } /* Check for single insn sub ops */ if (L[0]->OPC == OP65_AND || L[0]->OPC == OP65_EOR || L[0]->OPC == OP65_ORA || (L[0]->OPC == OP65_JSR && (strncmp (L[0]->Arg, "shlax", 5) == 0 || strncmp (L[0]->Arg, "shrax", 5) == 0) && strlen (L[0]->Arg) == 6 && IsDigit (L[0]->Arg[5]))) { /* One insn */ return 1; } else if (L[0]->OPC == OP65_CLC && (L[1] = CS_GetNextEntry (S, I)) != 0 && L[1]->OPC == OP65_ADC && !CE_HasLabel (L[1])) { return 2; } else if (L[0]->OPC == OP65_SEC && (L[1] = CS_GetNextEntry (S, I)) != 0 && L[1]->OPC == OP65_SBC && !CE_HasLabel (L[1])) { return 2; } /* Not found */ return 0; } static const char* LoadAXZP (CodeSeg* S, unsigned I) /* If the two instructions preceeding S/I are a load of A/X from a two byte * zero byte location, return the name of the zero page location. Otherwise * return NULL. */ { CodeEntry* L[2]; unsigned Len; if (I >= 2 && CS_GetEntries (S, L, I-2, 2) && L[0]->OPC == OP65_LDA && L[0]->AM == AM65_ZP && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_ZP && !CE_HasLabel (L[1]) && (Len = strlen (L[0]->Arg)) == strlen (L[1]->Arg) - 2 && memcmp (L[0]->Arg, L[1]->Arg, Len) == 0 && L[1]->Arg[Len] == '+' && L[1]->Arg[Len+1] == '1') { /* Return the label */ return L[0]->Arg; } else { /* Not found */ return 0; } } static const char* LoadAXImm (CodeSeg* S, unsigned I) /* If the instructions preceeding S/I are a load of A/X of a constant value * or a word sized address label, return the address of the location as a * string. * Beware: In case of a numeric value, the result is returned in static * storage which is overwritten with each call. */ { static StrBuf Buf = STATIC_STRBUF_INITIALIZER; CodeEntry* L[2]; CodeEntry* ALoad; CodeEntry* XLoad; unsigned Len; /* Fetch entry at I and check if A/X is known */ L[0] = CS_GetEntry (S, I); if (L[0] != 0 && RegValIsKnown (L[0]->RI->In.RegA) && RegValIsKnown (L[0]->RI->In.RegX)) { /* Numeric argument - get low and high byte */ unsigned Lo = (L[0]->RI->In.RegA & 0xFF); unsigned Hi = (L[0]->RI->In.RegX & 0xFF); /* Format into buffer */ SB_Printf (&Buf, "$%04X", Lo | (Hi << 8)); /* Return the address as a string */ return SB_GetConstBuf (&Buf); } /* Search back for the two instructions loading A and X. Abort * the search if the registers are changed in any other way or * if a label is reached while we don't have both loads. */ ALoad = 0; XLoad = 0; while (I-- > 0) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the loads of A and X */ if (ALoad == 0 && E->OPC == OP65_LDA && E->AM == AM65_IMM) { ALoad = E; } else if (E->Chg & REG_A) { /* A is changed before we get the load */ return 0; } else if (XLoad == 0 && E->OPC == OP65_LDX && E->AM == AM65_IMM) { XLoad = E; } else if (E->Chg & REG_X) { /* X is changed before we get the load */ return 0; } if (ALoad != 0 && XLoad != 0) { /* We have both */ break; } /* If we have a label, before both are found, bail out */ if (CE_HasLabel (E)) { return 0; } } /* Check for a load of a label address */ if ((Len = strlen (ALoad->Arg)) > 3 && ALoad->Arg[0] == '<' && ALoad->Arg[1] == '(' && strlen (XLoad->Arg) == Len && XLoad->Arg[0] == '>' && memcmp (ALoad->Arg+1, XLoad->Arg+1, Len-1) == 0) { /* Load of an address label */ SB_CopyBuf (&Buf, ALoad->Arg + 2, Len - 3); SB_Terminate (&Buf); return SB_GetConstBuf (&Buf); } /* Not found */ return 0; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptPtrStore1 (CodeSeg* S) /* Search for the sequence: * * clc * adc xxx * bcc L * inx * L: jsr pushax * ldx #$00 * lda yyy * ldy #$00 * jsr staspidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy xxx * ldx #$00 * lda yyy * sta (ptr1),y * * or by * * ldy xxx * ldx #$00 * lda yyy * sta (zp),y * * or by * * ldy xxx * ldx #$00 * lda yyy * sta label,y * * or by * * ldy xxx * ldx #$00 * lda yyy * sta $xxxx,y * * depending on the code preceeding the sequence above. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[9]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_CLC && CS_GetEntries (S, L+1, I+1, 8) && L[1]->OPC == OP65_ADC && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP || L[1]->AM == AM65_IMM || (L[1]->AM == AM65_ZP_INDY && RegValIsKnown (L[1]->RI->In.RegY))) && (L[2]->OPC == OP65_BCC || L[2]->OPC == OP65_JCC) && L[2]->JumpTo != 0 && L[2]->JumpTo->Owner == L[4] && L[3]->OPC == OP65_INX && CE_IsCallTo (L[4], "pushax") && L[5]->OPC == OP65_LDX && L[6]->OPC == OP65_LDA && L[7]->OPC == OP65_LDY && CE_IsKnownImm (L[7], 0) && CE_IsCallTo (L[8], "staspidx") && !CS_RangeHasLabel (S, I+1, 3) && !CS_RangeHasLabel (S, I+5, 4)) { CodeEntry* X; const char* Loc; am_t AM; /* Track the insertion point */ unsigned IP = I + 9; if ((Loc = LoadAXZP (S, I)) != 0) { /* If the sequence is preceeded by a load of a ZP value, * we can use this ZP value as a pointer using ZP * indirect Y addressing. */ AM = AM65_ZP_INDY; } else if ((Loc = LoadAXImm (S, I)) != 0) { /* If the sequence is preceeded by a load of an immediate * value, we can use this absolute value as an address * using absolute indexed Y addressing. */ AM = AM65_ABSY; } /* If we don't have a store location, we use ptr1 with zp * indirect Y addressing. We must store the value in A/X into * ptr1 in this case. */ if (Loc == 0) { /* Must use ptr1 */ Loc = "ptr1"; AM = AM65_ZP_INDY; X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); } /* If the index is loaded from (zp),y, we cannot do that directly. * Note: In this case, the Y register will contain the correct * value after removing the old code, so we don't need to load * it here. */ if (L[1]->AM == AM65_ZP_INDY) { X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); } else { X = NewCodeEntry (OP65_LDY, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); } X = NewCodeEntry (OP65_LDX, L[5]->AM, L[5]->Arg, 0, L[5]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDA, L[6]->AM, L[6]->Arg, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STA, AM, Loc, 0, L[8]->LI); CS_InsertEntry (S, X, IP++); /* Remove the old code */ CS_DelEntries (S, I, 9); /* Skip most of the generated replacement code */ I += 3; /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrStore2 (CodeSeg* S) /* Search for the sequence: * * clc * adc xxx * bcc L * inx * L: jsr pushax * ldy yyy * ldx #$00 * lda (sp),y * ldy #$00 * jsr staspidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy yyy-2 * ldx #$00 * lda (sp),y * ldy xxx * sta (ptr1),y * * or by * * ldy yyy-2 * ldx #$00 * lda (sp),y * ldy xxx * sta (zp),y * * or by * * ldy yyy-2 * ldx #$00 * lda (sp),y * ldy xxx * sta label,y * * or by * * ldy yyy-2 * ldx #$00 * lda (sp),y * ldy xxx * sta $xxxx,y * * depending on the code preceeding the sequence above. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[10]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_CLC && CS_GetEntries (S, L+1, I+1, 9) && L[1]->OPC == OP65_ADC && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP || L[1]->AM == AM65_IMM || (L[1]->AM == AM65_ZP_INDY && RegValIsKnown (L[1]->RI->In.RegY))) && (L[2]->OPC == OP65_BCC || L[2]->OPC == OP65_JCC) && L[2]->JumpTo != 0 && L[2]->JumpTo->Owner == L[4] && L[3]->OPC == OP65_INX && CE_IsCallTo (L[4], "pushax") && L[5]->OPC == OP65_LDY && CE_IsConstImm (L[5]) && L[6]->OPC == OP65_LDX && L[7]->OPC == OP65_LDA && L[7]->AM == AM65_ZP_INDY && strcmp (L[7]->Arg, "sp") == 0 && L[8]->OPC == OP65_LDY && (L[8]->AM == AM65_ABS || L[8]->AM == AM65_ZP || L[8]->AM == AM65_IMM) && CE_IsCallTo (L[9], "staspidx") && !CS_RangeHasLabel (S, I+1, 3) && !CS_RangeHasLabel (S, I+5, 5)) { CodeEntry* X; const char* Arg; const char* Loc; am_t AM; /* Track the insertion point */ unsigned IP = I + 10; if ((Loc = LoadAXZP (S, I)) != 0) { /* If the sequence is preceeded by a load of a ZP value, * we can use this ZP value as a pointer using ZP * indirect Y addressing. */ AM = AM65_ZP_INDY; } else if ((Loc = LoadAXImm (S, I)) != 0) { /* If the sequence is preceeded by a load of an immediate * value, we can use this absolute value as an address * using absolute indexed Y addressing. */ AM = AM65_ABSY; } /* If we don't have a store location, we use ptr1 with zp * indirect Y addressing. We must store the value in A/X into * ptr1 in this case. */ if (Loc == 0) { /* Must use ptr1 */ Loc = "ptr1"; AM = AM65_ZP_INDY; X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); } /* Generate four different replacements depending on the addressing * mode of the store and from where the index is loaded: * * 1. If the index is not loaded ZP indirect Y, we can use Y for * the store index. * * 2. If the index is loaded ZP indirect Y and we store absolute * indexed, we need Y to load the index and will therefore * use X as index for the store. The disadvantage is that we * need to reload X later. * * 3. If the index is loaded ZP indirect Y and we store ZP indirect * Y, we must use Y for load and store and must therefore save * the A register when loading Y the second time. */ if (L[1]->AM != AM65_ZP_INDY) { /* Case 1 */ Arg = MakeHexArg (L[5]->Num - 2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[5]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDX, L[6]->AM, L[6]->Arg, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDA, L[7]->AM, L[7]->Arg, 0, L[7]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDY, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STA, AM, Loc, 0, L[9]->LI); CS_InsertEntry (S, X, IP++); } else if (AM == AM65_ABSY) { /* Case 2 */ X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); Arg = MakeHexArg (L[5]->Num - 2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[5]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDA, L[7]->AM, L[7]->Arg, 0, L[7]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STA, AM65_ABSX, Loc, 0, L[9]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDX, L[6]->AM, L[6]->Arg, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); } else { /* Case 3 */ Arg = MakeHexArg (L[5]->Num - 2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[5]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDX, L[6]->AM, L[6]->Arg, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDA, L[7]->AM, L[7]->Arg, 0, L[7]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); Arg = MakeHexArg (L[1]->RI->In.RegY); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, L[6]->LI); CS_InsertEntry (S, X, IP++); X = NewCodeEntry (OP65_STA, AM, Loc, 0, L[9]->LI); CS_InsertEntry (S, X, IP++); } /* Remove the old code */ CS_DelEntries (S, I, 10); /* Skip most of the generated replacement code */ I += 4; /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrStore3 (CodeSeg* S) /* Search for the sequence: * * jsr pushax * ldy xxx * jsr ldauidx * subop * ldy yyy * jsr staspidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy xxx * ldx #$00 * lda (ptr1),y * subop * ldy yyy * sta (ptr1),y * * In case a/x is loaded from the register bank before the pushax, we can even * use the register bank instead of ptr1. * */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { unsigned K; CodeEntry* L[10]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "pushax") && CS_GetEntries (S, L+1, I+1, 3) && L[1]->OPC == OP65_LDY && CE_IsConstImm (L[1]) && !CE_HasLabel (L[1]) && CE_IsCallTo (L[2], "ldauidx") && !CE_HasLabel (L[2]) && (K = OptPtrStore1Sub (S, I+3, L+3)) > 0 && CS_GetEntries (S, L+3+K, I+3+K, 2) && L[3+K]->OPC == OP65_LDY && CE_IsConstImm (L[3+K]) && !CE_HasLabel (L[3+K]) && CE_IsCallTo (L[4+K], "staspidx") && !CE_HasLabel (L[4+K])) { const char* RegBank = 0; const char* ZPLoc = "ptr1"; CodeEntry* X; /* Get the preceeding two instructions and check them. We check * for: * lda regbank+n * ldx regbank+n+1 */ if (I > 1) { CodeEntry* P[2]; P[0] = CS_GetEntry (S, I-2); P[1] = CS_GetEntry (S, I-1); if (P[0]->OPC == OP65_LDA && P[0]->AM == AM65_ZP && P[1]->OPC == OP65_LDX && P[1]->AM == AM65_ZP && !CE_HasLabel (P[1]) && strncmp (P[0]->Arg, "regbank+", 8) == 0) { unsigned Len = strlen (P[0]->Arg); if (strncmp (P[0]->Arg, P[1]->Arg, Len) == 0 && P[1]->Arg[Len+0] == '+' && P[1]->Arg[Len+1] == '1' && P[1]->Arg[Len+2] == '\0') { /* Ok, found. Use the name of the register bank */ RegBank = ZPLoc = P[0]->Arg; } } } /* Insert the load via the zp pointer */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI); CS_InsertEntry (S, X, I+3); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, ZPLoc, 0, L[2]->LI); CS_InsertEntry (S, X, I+4); /* Insert the store through the zp pointer */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLoc, 0, L[3]->LI); CS_InsertEntry (S, X, I+6+K); /* Delete the old code */ CS_DelEntry (S, I+7+K); /* jsr spaspidx */ CS_DelEntry (S, I+2); /* jsr ldauidx */ /* Create and insert the stores into the zp pointer if needed */ if (RegBank == 0) { X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+1); X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI); CS_InsertEntry (S, X, I+2); } /* Delete more old code. Do it here to keep a label attached to * entry I in place. */ CS_DelEntry (S, I); /* jsr pushax */ /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
851
./cc65/src/cc65/coptcmp.c
/*****************************************************************************/ /* */ /* coptcmp.c */ /* */ /* Optimize compares */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "error.h" #include "coptcmp.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Table used to invert a condition, indexed by condition */ static const unsigned char CmpInvertTab [] = { CMP_NE, CMP_EQ, CMP_LE, CMP_LT, CMP_GE, CMP_GT, CMP_ULE, CMP_ULT, CMP_UGE, CMP_UGT }; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void ReplaceCmp (CodeSeg* S, unsigned I, cmp_t Cond) /* Helper function for the replacement of routines that return a boolean * followed by a conditional jump. Instead of the boolean value, the condition * codes are evaluated directly. * I is the index of the conditional branch, the sequence is already checked * to be correct. */ { CodeEntry* N; CodeLabel* L; /* Get the entry */ CodeEntry* E = CS_GetEntry (S, I); /* Replace the conditional branch */ switch (Cond) { case CMP_EQ: CE_ReplaceOPC (E, OP65_JEQ); break; case CMP_NE: CE_ReplaceOPC (E, OP65_JNE); break; case CMP_GT: /* Replace by * beq @L * jpl Target * @L: ... */ if ((N = CS_GetNextEntry (S, I)) == 0) { /* No such entry */ Internal ("Invalid program flow"); } L = CS_GenLabel (S, N); N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, N, I); CE_ReplaceOPC (E, OP65_JPL); break; case CMP_GE: CE_ReplaceOPC (E, OP65_JPL); break; case CMP_LT: CE_ReplaceOPC (E, OP65_JMI); break; case CMP_LE: /* Replace by * jmi Target * jeq Target */ CE_ReplaceOPC (E, OP65_JMI); L = E->JumpTo; N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, N, I+1); break; case CMP_UGT: /* Replace by * beq @L * jcs Target * @L: ... */ if ((N = CS_GetNextEntry (S, I)) == 0) { /* No such entry */ Internal ("Invalid program flow"); } L = CS_GenLabel (S, N); N = NewCodeEntry (OP65_BEQ, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, N, I); CE_ReplaceOPC (E, OP65_JCS); break; case CMP_UGE: CE_ReplaceOPC (E, OP65_JCS); break; case CMP_ULT: CE_ReplaceOPC (E, OP65_JCC); break; case CMP_ULE: /* Replace by * jcc Target * jeq Target */ CE_ReplaceOPC (E, OP65_JCC); L = E->JumpTo; N = NewCodeEntry (OP65_JEQ, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, N, I+1); break; default: Internal ("Unknown jump condition: %d", Cond); } } static int IsImmCmp16 (CodeEntry** L) /* Check if the instructions at L are an immidiate compare of a/x: * * */ { return (L[0]->OPC == OP65_CPX && L[0]->AM == AM65_IMM && (L[0]->Flags & CEF_NUMARG) != 0 && !CE_HasLabel (L[0]) && (L[1]->OPC == OP65_JNE || L[1]->OPC == OP65_BNE) && L[1]->JumpTo != 0 && !CE_HasLabel (L[1]) && L[2]->OPC == OP65_CMP && L[2]->AM == AM65_IMM && (L[2]->Flags & CEF_NUMARG) != 0 && (L[3]->Info & OF_CBRA) != 0 && L[3]->JumpTo != 0 && (L[1]->JumpTo->Owner == L[3] || L[1]->JumpTo == L[3]->JumpTo)); } static int GetCmpRegVal (const CodeEntry* E) /* Return the register value for an immediate compare */ { switch (E->OPC) { case OP65_CMP: return E->RI->In.RegA; case OP65_CPX: return E->RI->In.RegX; case OP65_CPY: return E->RI->In.RegY; default: Internal ("Invalid opcode in GetCmpRegVal"); return 0; /* Not reached */ } } /*****************************************************************************/ /* Remove calls to the bool transformer subroutines */ /*****************************************************************************/ unsigned OptBoolTrans (CodeSeg* S) /* Try to remove the call to boolean transformer routines where the call is * not really needed. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; cmp_t Cond; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a boolean transformer */ if (E->OPC == OP65_JSR && (Cond = FindBoolCmpCond (E->Arg)) != CMP_INV && (N = CS_GetNextEntry (S, I)) != 0 && (N->Info & OF_ZBRA) != 0) { /* Make the boolean transformer unnecessary by changing the * the conditional jump to evaluate the condition flags that * are set after the compare directly. Note: jeq jumps if * the condition is not met, jne jumps if the condition is met. * Invert the code if we jump on condition not met. */ if (GetBranchCond (N->OPC) == BC_EQ) { /* Jumps if condition false, invert condition */ Cond = CmpInvertTab [Cond]; } /* Check if we can replace the code by something better */ ReplaceCmp (S, I+1, Cond); /* Remove the call to the bool transformer */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } /*****************************************************************************/ /* Optimizations for compares */ /*****************************************************************************/ unsigned OptCmp1 (CodeSeg* S) /* Search for the sequence * * ldx xx * stx tmp1 * ora tmp1 * * and replace it by * * ora xx */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDX && !CS_RangeHasLabel (S, I+1, 2) && CS_GetEntries (S, L+1, I+1, 2) && L[1]->OPC == OP65_STX && strcmp (L[1]->Arg, "tmp1") == 0 && L[2]->OPC == OP65_ORA && strcmp (L[2]->Arg, "tmp1") == 0) { CodeEntry* X; /* Insert the ora instead */ X = NewCodeEntry (OP65_ORA, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I); /* Remove all other instructions */ CS_DelEntries (S, I+1, 3); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp2 (CodeSeg* S) /* Search for the sequence * * stx xx * stx tmp1 * ora tmp1 * * and replace it by * * stx xx * ora xx */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_STX && !CS_RangeHasLabel (S, I+1, 2) && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_STX && strcmp (L[0]->Arg, "tmp1") == 0 && L[1]->OPC == OP65_ORA && strcmp (L[1]->Arg, "tmp1") == 0) { /* Remove the remaining instructions */ CS_DelEntries (S, I+1, 2); /* Insert the ora instead */ CS_InsertEntry (S, NewCodeEntry (OP65_ORA, E->AM, E->Arg, 0, E->LI), I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp3 (CodeSeg* S) /* Search for * * lda/and/ora/eor ... * cmp #$00 * jeq/jne * or * lda/and/ora/eor ... * cmp #$00 * jsr boolxx * * and remove the cmp. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if ((L[0]->OPC == OP65_ADC || L[0]->OPC == OP65_AND || L[0]->OPC == OP65_ASL || L[0]->OPC == OP65_DEA || L[0]->OPC == OP65_EOR || L[0]->OPC == OP65_INA || L[0]->OPC == OP65_LDA || L[0]->OPC == OP65_LSR || L[0]->OPC == OP65_ORA || L[0]->OPC == OP65_PLA || L[0]->OPC == OP65_SBC || L[0]->OPC == OP65_TXA || L[0]->OPC == OP65_TYA) && !CS_RangeHasLabel (S, I+1, 2) && CS_GetEntries (S, L+1, I+1, 2) && L[1]->OPC == OP65_CMP && CE_IsKnownImm (L[1], 0)) { int Delete = 0; /* Check for the call to boolxx. We only remove the compare if * the carry flag is not evaluated later, because the load will * not set the carry flag. */ if (L[2]->OPC == OP65_JSR) { switch (FindBoolCmpCond (L[2]->Arg)) { case CMP_EQ: case CMP_NE: case CMP_GT: case CMP_GE: case CMP_LT: case CMP_LE: /* Remove the compare */ Delete = 1; break; case CMP_UGT: case CMP_UGE: case CMP_ULT: case CMP_ULE: case CMP_INV: /* Leave it alone */ break; } } else if ((L[2]->Info & OF_FBRA) != 0) { /* The following insn branches on the condition of the load, * so the compare instruction might be removed. For safety, * do some more checks if the carry isn't used later, since * the compare does set the carry, but the load does not. */ CodeEntry* E; CodeEntry* N; if ((E = CS_GetNextEntry (S, I+2)) != 0 && L[2]->JumpTo != 0 && (N = L[2]->JumpTo->Owner) != 0 && N->OPC != OP65_BCC && N->OPC != OP65_BCS && N->OPC != OP65_JCC && N->OPC != OP65_JCS && (N->OPC != OP65_JSR || FindBoolCmpCond (N->Arg) == CMP_INV)) { /* The following insn branches on the condition of a load, * and there's no use of the carry flag in sight, so the * compare instruction can be removed. */ Delete = 1; } } /* Delete the compare if we can */ if (Delete) { CS_DelEntry (S, I+1); ++Changes; } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp4 (CodeSeg* S) /* Search for * * lda x * ldx y * cpx #a * bne L1 * cmp #b * L1: jne/jeq L2 * * If a is zero, we may remove the compare. If a and b are both zero, we may * replace it by the sequence * * lda x * ora x+1 * jne/jeq ... * * L1 may be either the label at the branch instruction, or the target label * of this instruction. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_LDA && CS_GetEntries (S, L, I+1, 5) && L[0]->OPC == OP65_LDX && !CE_HasLabel (L[0]) && IsImmCmp16 (L+1) && !RegAXUsed (S, I+6)) { if ((L[4]->Info & OF_FBRA) != 0 && L[1]->Num == 0 && L[3]->Num == 0) { /* The value is zero, we may use the simple code version. */ CE_ReplaceOPC (L[0], OP65_ORA); CS_DelEntries (S, I+2, 3); } else { /* Move the lda instruction after the first branch. This will * improve speed, since the load is delayed after the first * test. */ CS_MoveEntry (S, I, I+4); /* We will replace the ldx/cpx by lda/cmp */ CE_ReplaceOPC (L[0], OP65_LDA); CE_ReplaceOPC (L[1], OP65_CMP); /* Beware: If the first LDA instruction had a label, we have * to move this label to the top of the sequence again. */ if (CE_HasLabel (E)) { CS_MoveLabels (S, E, L[0]); } } ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp5 (CodeSeg* S) /* Optimize compares of local variables: * * ldy #o * jsr ldaxysp * cpx #a * bne L1 * cmp #b * jne/jeq L2 */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[6]; /* Get the next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && CS_GetEntries (S, L+1, I+1, 5) && !CE_HasLabel (L[1]) && CE_IsCallTo (L[1], "ldaxysp") && IsImmCmp16 (L+2)) { if ((L[5]->Info & OF_FBRA) != 0 && L[2]->Num == 0 && L[4]->Num == 0) { CodeEntry* X; char Buf[20]; /* The value is zero, we may use the simple code version: * ldy #o-1 * lda (sp),y * ldy #o * ora (sp),y * jne/jeq ... */ sprintf (Buf, "$%02X", (int)(L[0]->Num-1)); X = NewCodeEntry (OP65_LDY, AM65_IMM, Buf, 0, L[0]->LI); CS_InsertEntry (S, X, I+1); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_LDY, AM65_IMM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+3); X = NewCodeEntry (OP65_ORA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+4); CS_DelEntries (S, I+5, 3); /* cpx/bne/cmp */ CS_DelEntry (S, I); /* ldy */ } else { CodeEntry* X; char Buf[20]; /* Change the code to just use the A register. Move the load * of the low byte after the first branch if possible: * * ldy #o * lda (sp),y * cmp #a * bne L1 * ldy #o-1 * lda (sp),y * cmp #b * jne/jeq ... */ X = NewCodeEntry (OP65_LDY, AM65_IMM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+3); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+4); X = NewCodeEntry (OP65_CMP, L[2]->AM, L[2]->Arg, 0, L[2]->LI); CS_InsertEntry (S, X, I+5); sprintf (Buf, "$%02X", (int)(L[0]->Num-1)); X = NewCodeEntry (OP65_LDY, AM65_IMM, Buf, 0, L[0]->LI); CS_InsertEntry (S, X, I+7); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[1]->LI); CS_InsertEntry (S, X, I+8); CS_DelEntries (S, I, 3); /* ldy/jsr/cpx */ } ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp6 (CodeSeg* S) /* Search for calls to compare subroutines followed by a conditional branch * and replace them by cheaper versions, since the branch means that the * boolean value returned by these routines is not needed (we may also check * that explicitly, but for the current code generator it is always true). */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* N; cmp_t Cond; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && (Cond = FindTosCmpCond (E->Arg)) != CMP_INV && (N = CS_GetNextEntry (S, I)) != 0 && (N->Info & OF_ZBRA) != 0 && !CE_HasLabel (N)) { /* The tos... functions will return a boolean value in a/x and * the Z flag says if this value is zero or not. We will call * a cheaper subroutine instead, one that does not return a * boolean value but only valid flags. Note: jeq jumps if * the condition is not met, jne jumps if the condition is met. * Invert the code if we jump on condition not met. */ if (GetBranchCond (N->OPC) == BC_EQ) { /* Jumps if condition false, invert condition */ Cond = CmpInvertTab [Cond]; } /* Replace the subroutine call. */ E = NewCodeEntry (OP65_JSR, AM65_ABS, "tosicmp", 0, E->LI); CS_InsertEntry (S, E, I+1); CS_DelEntry (S, I); /* Replace the conditional branch */ ReplaceCmp (S, I+1, Cond); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp7 (CodeSeg* S) /* Search for a sequence ldx/txa/branch and remove the txa if A is not * used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if ((E->OPC == OP65_LDX) && CS_GetEntries (S, L, I+1, 2) && L[0]->OPC == OP65_TXA && !CE_HasLabel (L[0]) && (L[1]->Info & OF_FBRA) != 0 && !CE_HasLabel (L[1]) && !RegAUsed (S, I+3)) { /* Remove the txa */ CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp8 (CodeSeg* S) /* Check for register compares where the contents of the register and therefore * the result of the compare is known. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { int RegVal; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a compare against an immediate value */ if ((E->Info & OF_CMP) != 0 && (RegVal = GetCmpRegVal (E)) >= 0 && CE_IsConstImm (E)) { /* We are able to evaluate the compare at compile time. Check if * one or more branches are ahead. */ unsigned JumpsChanged = 0; CodeEntry* N; while ((N = CS_GetNextEntry (S, I)) != 0 && /* Followed by something.. */ (N->Info & OF_CBRA) != 0 && /* ..that is a cond branch.. */ !CE_HasLabel (N)) { /* ..and has no label */ /* Evaluate the branch condition */ int Cond; switch (GetBranchCond (N->OPC)) { case BC_CC: Cond = ((unsigned char)RegVal) < ((unsigned char)E->Num); break; case BC_CS: Cond = ((unsigned char)RegVal) >= ((unsigned char)E->Num); break; case BC_EQ: Cond = ((unsigned char)RegVal) == ((unsigned char)E->Num); break; case BC_MI: Cond = ((signed char)RegVal) < ((signed char)E->Num); break; case BC_NE: Cond = ((unsigned char)RegVal) != ((unsigned char)E->Num); break; case BC_PL: Cond = ((signed char)RegVal) >= ((signed char)E->Num); break; case BC_VC: case BC_VS: /* Not set by the compare operation, bail out (Note: * Just skipping anything here is rather stupid, but * the sequence is never generated by the compiler, * so it's quite safe to skip). */ goto NextEntry; default: Internal ("Unknown branch condition"); } /* If the condition is false, we may remove the jump. Otherwise * the branch will always be taken, so we may replace it by a * jump (and bail out). */ if (!Cond) { CS_DelEntry (S, I+1); } else { CodeLabel* L = N->JumpTo; const char* LabelName = L? L->Name : N->Arg; CodeEntry* X = NewCodeEntry (OP65_JMP, AM65_BRA, LabelName, L, N->LI); CS_InsertEntry (S, X, I+2); CS_DelEntry (S, I+1); } /* Remember, we had changes */ ++JumpsChanged; ++Changes; } /* If we have made changes above, we may also remove the compare */ if (JumpsChanged) { CS_DelEntry (S, I); } } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptCmp9 (CodeSeg* S) /* Search for the sequence * * sbc xx * bvs/bvc L * eor #$80 * L: asl a * bcc/bcs somewhere * * If A is not used later (which should be the case), we can branch on the N * flag instead of the carry flag and remove the asl. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_SBC && CS_GetEntries (S, L+1, I+1, 4) && (L[1]->OPC == OP65_BVC || L[1]->OPC == OP65_BVS) && L[1]->JumpTo != 0 && L[1]->JumpTo->Owner == L[3] && L[2]->OPC == OP65_EOR && CE_IsKnownImm (L[2], 0x80) && L[3]->OPC == OP65_ASL && L[3]->AM == AM65_ACC && (L[4]->OPC == OP65_BCC || L[4]->OPC == OP65_BCS || L[4]->OPC == OP65_JCC || L[4]->OPC == OP65_JCS) && !CE_HasLabel (L[4]) && !RegAUsed (S, I+4)) { /* Replace the branch condition */ switch (GetBranchCond (L[4]->OPC)) { case BC_CC: CE_ReplaceOPC (L[4], OP65_JPL); break; case BC_CS: CE_ReplaceOPC (L[4], OP65_JMI); break; default: Internal ("Unknown branch condition in OptCmp9"); } /* Delete the asl insn */ CS_DelEntry (S, I+3); /* Next sequence is somewhat ahead (if any) */ I += 3; /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
852
./cc65/src/cc65/scanstrbuf.c
/*****************************************************************************/ /* */ /* scanstrbuf.c */ /* */ /* Small scanner for input from a StrBuf */ /* */ /* */ /* */ /* (C) 2002-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" #include "tgttrans.h" /* cc65 */ #include "datatype.h" #include "error.h" #include "hexval.h" #include "ident.h" #include "scanstrbuf.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static int ParseChar (StrBuf* B) /* Parse a character. Converts \n into EOL, etc. */ { unsigned I; unsigned Val; int C; /* Check for escape chars */ if ((C = SB_Get (B)) == '\\') { switch (SB_Peek (B)) { case '?': C = '?'; SB_Skip (B); break; case 'a': C = '\a'; SB_Skip (B); break; case 'b': C = '\b'; SB_Skip (B); break; case 'f': C = '\f'; SB_Skip (B); break; case 'r': C = '\r'; SB_Skip (B); break; case 'n': C = '\n'; SB_Skip (B); break; case 't': C = '\t'; SB_Skip (B); break; case 'v': C = '\v'; SB_Skip (B); break; case '\"': C = '\"'; SB_Skip (B); break; case '\'': C = '\''; SB_Skip (B); break; case '\\': C = '\\'; SB_Skip (B); break; case 'x': case 'X': /* Hex character constant */ SB_Skip (B); C = HexVal (SB_Get (B)) << 4; C |= HexVal (SB_Get (B)); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': /* Octal constant */ I = 0; Val = SB_Get (B) - '0'; while (SB_Peek (B) >= '0' && SB_Peek (B) <= '7' && ++I <= 3) { Val = (Val << 3) | (SB_Get (B) - '0'); } C = (int) Val; if (Val > 256) { Error ("Character constant out of range"); C = ' '; } break; default: Error ("Illegal character constant 0x%02X", SB_Get (B)); C = ' '; break; } } /* Return the character */ return C; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ void SB_SkipWhite (StrBuf* B) /* Skip whitespace in the string buffer */ { while (IsBlank (SB_Peek (B))) { SB_Skip (B); } } int SB_GetSym (StrBuf* B, StrBuf* Ident, const char* SpecialChars) /* Get a symbol from the string buffer. If SpecialChars is not NULL, it * points to a string that contains characters allowed within the string in * addition to letters, digits and the underline. Note: The identifier must * still begin with a letter. * Returns 1 if a symbol was found and 0 otherwise but doesn't output any * errors. */ { /* Handle a NULL argument for SpecialChars transparently */ if (SpecialChars == 0) { SpecialChars = ""; } /* Clear Ident */ SB_Clear (Ident); if (IsIdent (SB_Peek (B))) { char C = SB_Peek (B); do { SB_AppendChar (Ident, C); SB_Skip (B); C = SB_Peek (B); } while (IsIdent (C) || IsDigit (C) || (C != '\0' && strchr (SpecialChars, C) != 0)); SB_Terminate (Ident); return 1; } else { return 0; } } int SB_GetString (StrBuf* B, StrBuf* S) /* Get a string from the string buffer. Returns 1 if a string was found and 0 * otherwise. Errors are only output in case of invalid strings (missing end * of string). */ { char C; /* Clear S */ SB_Clear (S); /* A string starts with quote marks */ if (SB_Peek (B) == '\"') { /* String follows, be sure to concatenate strings */ while (SB_Peek (B) == '\"') { /* Skip the quote char */ SB_Skip (B); /* Read the actual string contents */ while ((C = SB_Peek (B)) != '\"') { if (C == '\0') { Error ("Unexpected end of string"); break; } SB_AppendChar (S, ParseChar (B)); } /* Skip the closing quote char if there was one */ SB_Skip (B); /* Skip white space, read new input */ SB_SkipWhite (B); } /* Terminate the string */ SB_Terminate (S); /* Success */ return 1; } else { /* Not a string */ SB_Terminate (S); return 0; } } int SB_GetNumber (StrBuf* B, long* Val) /* Get a number from the string buffer. Accepted formats are decimal, octal, * hex and character constants. Numeric constants may be preceeded by a * minus or plus sign. The function returns 1 if a number was found and * zero otherwise. Errors are only output for invalid numbers. */ { int Sign; char C; unsigned Base; unsigned DigitVal; /* Initialize Val */ *Val = 0; /* Handle character constants */ if (SB_Peek (B) == '\'') { /* Character constant */ SB_Skip (B); *Val = SignExtendChar (TgtTranslateChar (ParseChar (B))); if (SB_Peek (B) != '\'') { Error ("`\'' expected"); return 0; } else { /* Skip the quote */ SB_Skip (B); return 1; } } /* Check for a sign. A sign must be followed by a digit, otherwise it's * not a number */ Sign = 1; switch (SB_Peek (B)) { case '-': Sign = -1; /* FALLTHROUGH */ case '+': if (!IsDigit (SB_LookAt (B, SB_GetIndex (B) + 1))) { return 0; } SB_Skip (B); break; } /* We must have a digit now, otherwise its not a number */ C = SB_Peek (B); if (!IsDigit (C)) { return 0; } /* Determine the base */ if (C == '0') { /* Hex or octal */ SB_Skip (B); if (tolower (SB_Peek (B)) == 'x') { SB_Skip (B); Base = 16; if (!IsXDigit (SB_Peek (B))) { Error ("Invalid hexadecimal number"); return 0; } } else { Base = 8; } } else { Base = 10; } /* Read the number */ while (IsXDigit (C = SB_Peek (B)) && (DigitVal = HexVal (C)) < Base) { *Val = (*Val * Base) + DigitVal; SB_Skip (B); } /* Allow optional 'U' and 'L' modifiers */ C = SB_Peek (B); if (C == 'u' || C == 'U') { SB_Skip (B); C = SB_Peek (B); if (C == 'l' || C == 'L') { SB_Skip (B); } } else if (C == 'l' || C == 'L') { SB_Skip (B); C = SB_Peek (B); if (C == 'u' || C == 'U') { SB_Skip (B); } } /* Success, value read is in Val */ *Val *= Sign; return 1; }
853
./cc65/src/cc65/asmstmt.c
/*****************************************************************************/ /* */ /* asmstmt.c */ /* */ /* Inline assembler statements for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2001-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xsprintf.h" /* cc65 */ #include "asmlabel.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "function.h" #include "litpool.h" #include "scanner.h" #include "stackptr.h" #include "symtab.h" #include "asmstmt.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void AsmRangeError (unsigned Arg) /* Print a diagnostic about a range error in the argument with the given number */ { Error ("Range error in argument %u", Arg); } static void AsmErrorSkip (void) /* Called in case of an error, skips tokens until the closing paren or a * semicolon is reached. */ { static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI }; SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0])); } static SymEntry* AsmGetSym (unsigned Arg, unsigned Type) /* Find the symbol with the name currently in NextTok. The symbol must be of * the given type. On errors, NULL is returned. */ { SymEntry* Sym; /* We expect an argument separated by a comma */ ConsumeComma (); /* Argument must be an identifier */ if (CurTok.Tok != TOK_IDENT) { Error ("Identifier expected for argument %u", Arg); AsmErrorSkip (); return 0; } /* Get a pointer to the symbol table entry */ Sym = FindSym (CurTok.Ident); /* Did we find a symbol with this name? */ if (Sym == 0) { Error ("Undefined symbol `%s' for argument %u", CurTok.Ident, Arg); AsmErrorSkip (); return 0; } /* We found the symbol - skip the name token */ NextToken (); /* Check if we have a global symbol */ if ((Sym->Flags & Type) != Type) { Error ("Type of argument %u differs from format specifier", Arg); AsmErrorSkip (); return 0; } /* Mark the symbol as referenced */ Sym->Flags |= SC_REF; /* Return it */ return Sym; } static void ParseByteArg (StrBuf* T, unsigned Arg) /* Parse the %b format specifier */ { ExprDesc Expr; char Buf [16]; /* We expect an argument separated by a comma */ ConsumeComma (); /* Evaluate the expression */ ConstAbsIntExpr (hie1, &Expr); /* Check the range but allow negative values if the type is signed */ if (IsSignUnsigned (Expr.Type)) { if (Expr.IVal < 0 || Expr.IVal > 0xFF) { AsmRangeError (Arg); Expr.IVal = 0; } } else { if (Expr.IVal < -128 || Expr.IVal > 127) { AsmRangeError (Arg); Expr.IVal = 0; } } /* Convert into a hex number */ xsprintf (Buf, sizeof (Buf), "$%02lX", Expr.IVal & 0xFF); /* Add the number to the target buffer */ SB_AppendStr (T, Buf); } static void ParseWordArg (StrBuf* T, unsigned Arg) /* Parse the %w format specifier */ { ExprDesc Expr; char Buf [16]; /* We expect an argument separated by a comma */ ConsumeComma (); /* Evaluate the expression */ ConstAbsIntExpr (hie1, &Expr); /* Check the range but allow negative values if the type is signed */ if (IsSignUnsigned (Expr.Type)) { if (Expr.IVal < 0 || Expr.IVal > 0xFFFF) { AsmRangeError (Arg); Expr.IVal = 0; } } else { if (Expr.IVal < -32768 || Expr.IVal > 32767) { AsmRangeError (Arg); Expr.IVal = 0; } } /* Convert into a hex number */ xsprintf (Buf, sizeof (Buf), "$%04lX", Expr.IVal & 0xFFFF); /* Add the number to the target buffer */ SB_AppendStr (T, Buf); } static void ParseLongArg (StrBuf* T, unsigned Arg attribute ((unused))) /* Parse the %l format specifier */ { ExprDesc Expr; char Buf [16]; /* We expect an argument separated by a comma */ ConsumeComma (); /* Evaluate the expression */ ConstAbsIntExpr (hie1, &Expr); /* Convert into a hex number */ xsprintf (Buf, sizeof (Buf), "$%08lX", Expr.IVal & 0xFFFFFFFF); /* Add the number to the target buffer */ SB_AppendStr (T, Buf); } static void ParseGVarArg (StrBuf* T, unsigned Arg) /* Parse the %v format specifier */ { /* Parse the symbol name parameter and check the type */ SymEntry* Sym = AsmGetSym (Arg, SC_STATIC); if (Sym == 0) { /* Some sort of error */ return; } /* Check for external linkage */ if (Sym->Flags & (SC_EXTERN | SC_STORAGE | SC_FUNC)) { /* External linkage or a function */ /* ### FIXME: Asm name should be generated by codegen */ SB_AppendChar (T, '_'); SB_AppendStr (T, Sym->Name); } else if (Sym->Flags & SC_REGISTER) { char Buf[32]; xsprintf (Buf, sizeof (Buf), "regbank+%d", Sym->V.R.RegOffs); SB_AppendStr (T, Buf); } else { /* Static variable */ char Buf [16]; xsprintf (Buf, sizeof (Buf), "L%04X", Sym->V.Label); SB_AppendStr (T, Buf); } } static void ParseLVarArg (StrBuf* T, unsigned Arg) /* Parse the %o format specifier */ { unsigned Offs; char Buf [16]; /* Parse the symbol name parameter and check the type */ SymEntry* Sym = AsmGetSym (Arg, SC_AUTO); if (Sym == 0) { /* Some sort of error */ return; } /* The symbol may be a parameter to a variadic function. In this case, we * don't have a fixed stack offset, so check it and bail out with an error * if this is the case. */ if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) { Error ("Argument %u has no fixed stack offset", Arg); AsmErrorSkip (); return; } /* Calculate the current offset from SP */ Offs = Sym->V.Offs - StackPtr; /* Output the offset */ xsprintf (Buf, sizeof (Buf), (Offs > 0xFF)? "$%04X" : "$%02X", Offs); SB_AppendStr (T, Buf); } static void ParseLabelArg (StrBuf* T, unsigned Arg attribute ((unused))) /* Parse the %g format specifier */ { /* We expect an identifier separated by a comma */ ConsumeComma (); if (CurTok.Tok != TOK_IDENT) { Error ("Label name expected"); } else { /* Add a new label symbol if we don't have one until now */ SymEntry* Entry = AddLabelSym (CurTok.Ident, SC_REF); /* Append the label name to the buffer */ SB_AppendStr (T, LocalLabelName (Entry->V.Label)); /* Eat the label name */ NextToken (); } } static void ParseStrArg (StrBuf* T, unsigned Arg attribute ((unused))) /* Parse the %s format specifier */ { ExprDesc Expr; char Buf [64]; /* We expect an argument separated by a comma */ ConsumeComma (); /* Check what comes */ switch (CurTok.Tok) { case TOK_IDENT: /* Identifier */ SB_AppendStr (T, CurTok.Ident); NextToken (); break; case TOK_SCONST: /* String constant */ SB_Append (T, GetLiteralStrBuf (CurTok.SVal)); NextToken (); break; default: ConstAbsIntExpr (hie1, &Expr); xsprintf (Buf, sizeof (Buf), "%ld", Expr.IVal); SB_AppendStr (T, Buf); break; } } static void ParseAsm (void) /* Parse the contents of the ASM statement */ { unsigned Arg; char C; /* Create a target string buffer */ StrBuf T = AUTO_STRBUF_INITIALIZER; /* Create a string buffer from the string literal */ StrBuf S = AUTO_STRBUF_INITIALIZER; SB_Append (&S, GetLiteralStrBuf (CurTok.SVal)); /* Skip the string token */ NextToken (); /* Parse the statement. It may contain several lines and one or more * of the following place holders: * %b - Numerical 8 bit value * %w - Numerical 16 bit value * %l - Numerical 32 bit value * %v - Assembler name of a (global) variable * %o - Stack offset of a (local) variable * %g - Assembler name of a C label * %s - Any argument converted to a string (almost) * %% - The % sign */ Arg = 0; while ((C = SB_Get (&S)) != '\0') { /* If it is a newline, the current line is ready to go */ if (C == '\n') { /* Pass it to the backend and start over */ g_asmcode (&T); SB_Clear (&T); } else if (C == '%') { /* Format specifier */ ++Arg; C = SB_Get (&S); switch (C) { case '%': SB_AppendChar (&T, '%'); break; case 'b': ParseByteArg (&T, Arg); break; case 'g': ParseLabelArg (&T, Arg); break; case 'l': ParseLongArg (&T, Arg); break; case 'o': ParseLVarArg (&T, Arg); break; case 's': ParseStrArg (&T, Arg); break; case 'v': ParseGVarArg (&T, Arg); break; case 'w': ParseWordArg (&T, Arg); break; default: Error ("Error in __asm__ format specifier %u", Arg); AsmErrorSkip (); goto Done; } } else { /* A normal character, just copy it */ SB_AppendChar (&T, C); } } /* If the target buffer is not empty, we have a last line in there */ if (!SB_IsEmpty (&T)) { g_asmcode (&T); } Done: /* Call the string buf destructors */ SB_Done (&S); SB_Done (&T); } void AsmStatement (void) /* This function parses ASM statements. The syntax of the ASM directive * looks like the one defined for C++ (C has no ASM directive), that is, * a string literal in parenthesis. */ { /* Skip the ASM */ NextToken (); /* Need left parenthesis */ if (!ConsumeLParen ()) { return; } /* String literal */ if (CurTok.Tok != TOK_SCONST) { /* Print a diagnostic */ Error ("String literal expected"); /* Try some smart error recovery: Skip tokens until we reach the * enclosing paren, or a semicolon. */ AsmErrorSkip (); } else { /* Parse the ASM statement */ ParseAsm (); } /* Closing paren needed */ ConsumeRParen (); }
854
./cc65/src/cc65/input.c
/*****************************************************************************/ /* */ /* input.c */ /* */ /* Input file handling */ /* */ /* */ /* */ /* (C) 2000-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <errno.h> /* common */ #include "check.h" #include "coll.h" #include "filestat.h" #include "fname.h" #include "print.h" #include "strbuf.h" #include "xmalloc.h" /* cc65 */ #include "codegen.h" #include "error.h" #include "global.h" #include "incpath.h" #include "input.h" #include "lineinfo.h" #include "output.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* The current input line */ StrBuf* Line; /* Current and next input character */ char CurC = '\0'; char NextC = '\0'; /* Maximum count of nested includes */ #define MAX_INC_NESTING 16 /* Struct that describes an input file */ typedef struct IFile IFile; struct IFile { unsigned Index; /* File index */ unsigned Usage; /* Usage counter */ unsigned long Size; /* File size */ unsigned long MTime; /* Time of last modification */ InputType Type; /* Type of input file */ char Name[1]; /* Name of file (dynamically allocated) */ }; /* Struct that describes an active input file */ typedef struct AFile AFile; struct AFile { unsigned Line; /* Line number for this file */ FILE* F; /* Input file stream */ IFile* Input; /* Points to corresponding IFile */ int SearchPath; /* True if we've added a path for this file */ }; /* List of all input files */ static Collection IFiles = STATIC_COLLECTION_INITIALIZER; /* List of all active files */ static Collection AFiles = STATIC_COLLECTION_INITIALIZER; /* Input stack used when preprocessing. */ static Collection InputStack = STATIC_COLLECTION_INITIALIZER; /*****************************************************************************/ /* struct IFile */ /*****************************************************************************/ static IFile* NewIFile (const char* Name, InputType Type) /* Create and return a new IFile */ { /* Get the length of the name */ unsigned Len = strlen (Name); /* Allocate a IFile structure */ IFile* IF = (IFile*) xmalloc (sizeof (IFile) + Len); /* Initialize the fields */ IF->Index = CollCount (&IFiles) + 1; IF->Usage = 0; IF->Size = 0; IF->MTime = 0; IF->Type = Type; memcpy (IF->Name, Name, Len+1); /* Insert the new structure into the IFile collection */ CollAppend (&IFiles, IF); /* Return the new struct */ return IF; } /*****************************************************************************/ /* struct AFile */ /*****************************************************************************/ static AFile* NewAFile (IFile* IF, FILE* F) /* Create a new AFile, push it onto the stack, add the path of the file to * the path search list, and finally return a pointer to the new AFile struct. */ { StrBuf Path = AUTO_STRBUF_INITIALIZER; /* Allocate a AFile structure */ AFile* AF = (AFile*) xmalloc (sizeof (AFile)); /* Initialize the fields */ AF->Line = 0; AF->F = F; AF->Input = IF; /* Increment the usage counter of the corresponding IFile. If this * is the first use, set the file data and output debug info if * requested. */ if (IF->Usage++ == 0) { /* Get file size and modification time. There a race condition here, * since we cannot use fileno() (non standard identifier in standard * header file), and therefore not fstat. When using stat with the * file name, there's a risk that the file was deleted and recreated * while it was open. Since mtime and size are only used to check * if a file has changed in the debugger, we will ignore this problem * here. */ struct stat Buf; if (FileStat (IF->Name, &Buf) != 0) { /* Error */ Fatal ("Cannot stat `%s': %s", IF->Name, strerror (errno)); } IF->Size = (unsigned long) Buf.st_size; IF->MTime = (unsigned long) Buf.st_mtime; /* Set the debug data */ g_fileinfo (IF->Name, IF->Size, IF->MTime); } /* Insert the new structure into the AFile collection */ CollAppend (&AFiles, AF); /* Get the path of this file and add it as an extra search path. * To avoid file search overhead, we will add one path only once. * This is checked by the PushSearchPath function. */ SB_CopyBuf (&Path, IF->Name, FindName (IF->Name) - IF->Name); SB_Terminate (&Path); AF->SearchPath = PushSearchPath (UsrIncSearchPath, SB_GetConstBuf (&Path)); SB_Done (&Path); /* Return the new struct */ return AF; } static void FreeAFile (AFile* AF) /* Free an AFile structure */ { xfree (AF); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static IFile* FindFile (const char* Name) /* Find the file with the given name in the list of all files. Since the list * is not large (usually less than 10), I don't care about using hashes or * similar things and do a linear search. */ { unsigned I; for (I = 0; I < CollCount (&IFiles); ++I) { /* Get the file struct */ IFile* IF = (IFile*) CollAt (&IFiles, I); /* Check the name */ if (strcmp (Name, IF->Name) == 0) { /* Found, return the struct */ return IF; } } /* Not found */ return 0; } void OpenMainFile (const char* Name) /* Open the main file. Will call Fatal() in case of failures. */ { AFile* MainFile; /* Setup a new IFile structure for the main file */ IFile* IF = NewIFile (Name, IT_MAIN); /* Open the file for reading */ FILE* F = fopen (Name, "r"); if (F == 0) { /* Cannot open */ Fatal ("Cannot open input file `%s': %s", Name, strerror (errno)); } /* Allocate a new AFile structure for the file */ MainFile = NewAFile (IF, F); /* Allocate the input line buffer */ Line = NewStrBuf (); /* Update the line infos, so we have a valid line info even at start of * the main file before the first line is read. */ UpdateLineInfo (MainFile->Input, MainFile->Line, Line); } void OpenIncludeFile (const char* Name, InputType IT) /* Open an include file and insert it into the tables. */ { char* N; FILE* F; IFile* IF; /* Check for the maximum include nesting */ if (CollCount (&AFiles) > MAX_INC_NESTING) { PPError ("Include nesting too deep"); return; } /* Search for the file */ N = SearchFile ((IT == IT_SYSINC)? SysIncSearchPath : UsrIncSearchPath, Name); if (N == 0) { PPError ("Include file `%s' not found", Name); return; } /* Search the list of all input files for this file. If we don't find * it, create a new IFile object. */ IF = FindFile (N); if (IF == 0) { IF = NewIFile (N, IT); } /* We don't need N any longer, since we may now use IF->Name */ xfree (N); /* Open the file */ F = fopen (IF->Name, "r"); if (F == 0) { /* Error opening the file */ PPError ("Cannot open include file `%s': %s", IF->Name, strerror (errno)); return; } /* Debugging output */ Print (stdout, 1, "Opened include file `%s'\n", IF->Name); /* Allocate a new AFile structure */ (void) NewAFile (IF, F); } static void CloseIncludeFile (void) /* Close an include file and switch to the higher level file. Set Input to * NULL if this was the main file. */ { AFile* Input; /* Get the number of active input files */ unsigned AFileCount = CollCount (&AFiles); /* Must have an input file when called */ PRECONDITION (AFileCount > 0); /* Get the current active input file */ Input = (AFile*) CollLast (&AFiles); /* Close the current input file (we're just reading so no error check) */ fclose (Input->F); /* Delete the last active file from the active file collection */ CollDelete (&AFiles, AFileCount-1); /* If we had added an extra search path for this AFile, remove it */ if (Input->SearchPath) { PopSearchPath (UsrIncSearchPath); } /* Delete the active file structure */ FreeAFile (Input); } static void GetInputChar (void) /* Read the next character from the input stream and make CurC and NextC * valid. If end of line is reached, both are set to NUL, no more lines * are read by this function. */ { /* Drop all pushed fragments that don't have data left */ while (SB_GetIndex (Line) >= SB_GetLen (Line)) { /* Cannot read more from this line, check next line on stack if any */ if (CollCount (&InputStack) == 0) { /* This is THE line */ break; } FreeStrBuf (Line); Line = CollPop (&InputStack); } /* Now get the next characters from the line */ if (SB_GetIndex (Line) >= SB_GetLen (Line)) { CurC = NextC = '\0'; } else { CurC = SB_AtUnchecked (Line, SB_GetIndex (Line)); if (SB_GetIndex (Line) + 1 < SB_GetLen (Line)) { /* NextC comes from this fragment */ NextC = SB_AtUnchecked (Line, SB_GetIndex (Line) + 1); } else { /* NextC comes from next fragment */ if (CollCount (&InputStack) > 0) { NextC = ' '; } else { NextC = '\0'; } } } } void NextChar (void) /* Skip the current input character and read the next one from the input * stream. CurC and NextC are valid after the call. If end of line is * reached, both are set to NUL, no more lines are read by this function. */ { /* Skip the last character read */ SB_Skip (Line); /* Read the next one */ GetInputChar (); } void ClearLine (void) /* Clear the current input line */ { unsigned I; /* Remove all pushed fragments from the input stack */ for (I = 0; I < CollCount (&InputStack); ++I) { FreeStrBuf (CollAtUnchecked (&InputStack, I)); } CollDeleteAll (&InputStack); /* Clear the contents of Line */ SB_Clear (Line); CurC = '\0'; NextC = '\0'; } StrBuf* InitLine (StrBuf* Buf) /* Initialize Line from Buf and read CurC and NextC from the new input line. * The function returns the old input line. */ { StrBuf* OldLine = Line; Line = Buf; CurC = SB_LookAt (Buf, SB_GetIndex (Buf)); NextC = SB_LookAt (Buf, SB_GetIndex (Buf) + 1); return OldLine; } int NextLine (void) /* Get a line from the current input. Returns 0 on end of file. */ { AFile* Input; /* Clear the current line */ ClearLine (); /* If there is no file open, bail out, otherwise get the current input file */ if (CollCount (&AFiles) == 0) { return 0; } Input = CollLast (&AFiles); /* Read characters until we have one complete line */ while (1) { /* Read the next character */ int C = fgetc (Input->F); /* Check for EOF */ if (C == EOF) { /* Accept files without a newline at the end */ if (SB_NotEmpty (Line)) { ++Input->Line; break; } /* Leave the current file */ CloseIncludeFile (); /* If there is no file open, bail out, otherwise get the * previous input file and start over. */ if (CollCount (&AFiles) == 0) { return 0; } Input = CollLast (&AFiles); continue; } /* Check for end of line */ if (C == '\n') { /* We got a new line */ ++Input->Line; /* If the \n is preceeded by a \r, remove the \r, so we can read * DOS/Windows files under *nix. */ if (SB_LookAtLast (Line) == '\r') { SB_Drop (Line, 1); } /* If we don't have a line continuation character at the end, * we're done with this line. Otherwise replace the character * by a newline and continue reading. */ if (SB_LookAtLast (Line) == '\\') { Line->Buf[Line->Len-1] = '\n'; } else { break; } } else if (C != '\0') { /* Ignore embedded NULs */ /* Just some character, add it to the line */ SB_AppendChar (Line, C); } } /* Add a termination character to the string buffer */ SB_Terminate (Line); /* Initialize the current and next characters. */ InitLine (Line); /* Create line information for this line */ UpdateLineInfo (Input->Input, Input->Line, Line); /* Done */ return 1; } const char* GetInputFile (const struct IFile* IF) /* Return a filename from an IFile struct */ { return IF->Name; } const char* GetCurrentFile (void) /* Return the name of the current input file */ { unsigned AFileCount = CollCount (&AFiles); if (AFileCount > 0) { const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1); return AF->Input->Name; } else { /* No open file. Use the main file if we have one. */ unsigned IFileCount = CollCount (&IFiles); if (IFileCount > 0) { const IFile* IF = (const IFile*) CollAt (&IFiles, 0); return IF->Name; } else { return "(outside file scope)"; } } } unsigned GetCurrentLine (void) /* Return the line number in the current input file */ { unsigned AFileCount = CollCount (&AFiles); if (AFileCount > 0) { const AFile* AF = (const AFile*) CollAt (&AFiles, AFileCount-1); return AF->Line; } else { /* No open file */ return 0; } } static void WriteEscaped (FILE* F, const char* Name) /* Write a file name to a dependency file escaping spaces */ { while (*Name) { if (*Name == ' ') { /* Escape spaces */ fputc ('\\', F); } fputc (*Name, F); ++Name; } } static void WriteDep (FILE* F, InputType Types) /* Helper function. Writes all file names that match Types to the output */ { unsigned I; /* Loop over all files */ unsigned FileCount = CollCount (&IFiles); for (I = 0; I < FileCount; ++I) { /* Get the next input file */ const IFile* IF = (const IFile*) CollAt (&IFiles, I); /* Ignore it if it is not of the correct type */ if ((IF->Type & Types) == 0) { continue; } /* If this is not the first file, add a space */ if (I > 0) { fputc (' ', F); } /* Print the dependency escaping spaces */ WriteEscaped (F, IF->Name); } } static void CreateDepFile (const char* Name, InputType Types) /* Create a dependency file with the given name and place dependencies for * all files with the given types there. */ { /* Open the file */ FILE* F = fopen (Name, "w"); if (F == 0) { Fatal ("Cannot open dependency file `%s': %s", Name, strerror (errno)); } /* If a dependency target was given, use it, otherwise use the output * file name as target, followed by a tab character. */ if (SB_IsEmpty (&DepTarget)) { WriteEscaped (F, OutputFilename); } else { WriteEscaped (F, SB_GetConstBuf (&DepTarget)); } fputs (":\t", F); /* Write out the dependencies for the output file */ WriteDep (F, Types); fputs ("\n\n", F); /* Write out a phony dependency for the included files */ WriteDep (F, Types); fputs (":\n\n", F); /* Close the file, check for errors */ if (fclose (F) != 0) { remove (Name); Fatal ("Cannot write to dependeny file (disk full?)"); } } void CreateDependencies (void) /* Create dependency files requested by the user */ { if (SB_NotEmpty (&DepName)) { CreateDepFile (SB_GetConstBuf (&DepName), IT_MAIN | IT_USRINC); } if (SB_NotEmpty (&FullDepName)) { CreateDepFile (SB_GetConstBuf (&FullDepName), IT_MAIN | IT_SYSINC | IT_USRINC); } }
855
./cc65/src/cc65/codeinfo.c
/*****************************************************************************/ /* */ /* codeinfo.c */ /* */ /* Additional information about 6502 code */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "chartype.h" #include "coll.h" #include "debugflag.h" /* cc65 */ #include "codeent.h" #include "codeseg.h" #include "datatype.h" #include "error.h" #include "reginfo.h" #include "symtab.h" #include "codeinfo.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Table with the compare suffixes */ static const char CmpSuffixTab [][4] = { "eq", "ne", "gt", "ge", "lt", "le", "ugt", "uge", "ult", "ule" }; /* Table listing the function names and code info values for known internally * used functions. This table should get auto-generated in the future. */ typedef struct FuncInfo FuncInfo; struct FuncInfo { const char* Name; /* Function name */ unsigned short Use; /* Register usage */ unsigned short Chg; /* Changed/destroyed registers */ }; /* Note for the shift functions: Shifts are done modulo 32, so all shift * routines are marked to use only the A register. The remainder is ignored * anyway. */ static const FuncInfo FuncInfoTable[] = { { "addeq0sp", REG_AX, REG_AXY }, { "addeqysp", REG_AXY, REG_AXY }, { "addysp", REG_Y, REG_NONE }, { "aslax1", REG_AX, REG_AX | REG_TMP1 }, { "aslax2", REG_AX, REG_AX | REG_TMP1 }, { "aslax3", REG_AX, REG_AX | REG_TMP1 }, { "aslax4", REG_AX, REG_AX | REG_TMP1 }, { "aslaxy", REG_AXY, REG_AXY | REG_TMP1 }, { "asleax1", REG_EAX, REG_EAX | REG_TMP1 }, { "asleax2", REG_EAX, REG_EAX | REG_TMP1 }, { "asleax3", REG_EAX, REG_EAX | REG_TMP1 }, { "asleax4", REG_EAX, REG_EAXY | REG_TMP1 }, { "asrax1", REG_AX, REG_AX | REG_TMP1 }, { "asrax2", REG_AX, REG_AX | REG_TMP1 }, { "asrax3", REG_AX, REG_AX | REG_TMP1 }, { "asrax4", REG_AX, REG_AX | REG_TMP1 }, { "asraxy", REG_AXY, REG_AXY | REG_TMP1 }, { "asreax1", REG_EAX, REG_EAX | REG_TMP1 }, { "asreax2", REG_EAX, REG_EAX | REG_TMP1 }, { "asreax3", REG_EAX, REG_EAX | REG_TMP1 }, { "asreax4", REG_EAX, REG_EAXY | REG_TMP1 }, { "bnega", REG_A, REG_AX }, { "bnegax", REG_AX, REG_AX }, { "bnegeax", REG_EAX, REG_EAX }, { "booleq", REG_NONE, REG_AX }, { "boolge", REG_NONE, REG_AX }, { "boolgt", REG_NONE, REG_AX }, { "boolle", REG_NONE, REG_AX }, { "boollt", REG_NONE, REG_AX }, { "boolne", REG_NONE, REG_AX }, { "booluge", REG_NONE, REG_AX }, { "boolugt", REG_NONE, REG_AX }, { "boolule", REG_NONE, REG_AX }, { "boolult", REG_NONE, REG_AX }, { "callax", REG_AX, REG_ALL }, { "complax", REG_AX, REG_AX }, { "decax1", REG_AX, REG_AX }, { "decax2", REG_AX, REG_AX }, { "decax3", REG_AX, REG_AX }, { "decax4", REG_AX, REG_AX }, { "decax5", REG_AX, REG_AX }, { "decax6", REG_AX, REG_AX }, { "decax7", REG_AX, REG_AX }, { "decax8", REG_AX, REG_AX }, { "decaxy", REG_AXY, REG_AX | REG_TMP1 }, { "deceaxy", REG_EAXY, REG_EAX }, { "decsp1", REG_NONE, REG_Y }, { "decsp2", REG_NONE, REG_A }, { "decsp3", REG_NONE, REG_A }, { "decsp4", REG_NONE, REG_A }, { "decsp5", REG_NONE, REG_A }, { "decsp6", REG_NONE, REG_A }, { "decsp7", REG_NONE, REG_A }, { "decsp8", REG_NONE, REG_A }, { "incax1", REG_AX, REG_AX }, { "incax2", REG_AX, REG_AX }, { "incax3", REG_AX, REG_AXY | REG_TMP1 }, { "incax4", REG_AX, REG_AXY | REG_TMP1 }, { "incax5", REG_AX, REG_AXY | REG_TMP1 }, { "incax6", REG_AX, REG_AXY | REG_TMP1 }, { "incax7", REG_AX, REG_AXY | REG_TMP1 }, { "incax8", REG_AX, REG_AXY | REG_TMP1 }, { "incaxy", REG_AXY, REG_AXY | REG_TMP1 }, { "incsp1", REG_NONE, REG_NONE }, { "incsp2", REG_NONE, REG_Y }, { "incsp3", REG_NONE, REG_Y }, { "incsp4", REG_NONE, REG_Y }, { "incsp5", REG_NONE, REG_Y }, { "incsp6", REG_NONE, REG_Y }, { "incsp7", REG_NONE, REG_Y }, { "incsp8", REG_NONE, REG_Y }, { "laddeq", REG_EAXY|REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "laddeq0sp", REG_EAX, REG_EAXY }, { "laddeq1", REG_Y | REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "laddeqa", REG_AY | REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "laddeqysp", REG_EAXY, REG_EAXY }, { "ldaidx", REG_AXY, REG_AX | REG_PTR1 }, { "ldauidx", REG_AXY, REG_AX | REG_PTR1 }, { "ldax0sp", REG_NONE, REG_AXY }, { "ldaxi", REG_AX, REG_AXY | REG_PTR1 }, { "ldaxidx", REG_AXY, REG_AXY | REG_PTR1 }, { "ldaxysp", REG_Y, REG_AXY }, { "ldeax0sp", REG_NONE, REG_EAXY }, { "ldeaxi", REG_AX, REG_EAXY | REG_PTR1 }, { "ldeaxidx", REG_AXY, REG_EAXY | REG_PTR1 }, { "ldeaxysp", REG_Y, REG_EAXY }, { "leaa0sp", REG_A, REG_AX }, { "leaaxsp", REG_AX, REG_AX }, { "lsubeq", REG_EAXY|REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "lsubeq0sp", REG_EAX, REG_EAXY }, { "lsubeq1", REG_Y | REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "lsubeqa", REG_AY | REG_PTR1_LO, REG_EAXY | REG_PTR1_HI }, { "lsubeqysp", REG_EAXY, REG_EAXY }, { "mulax10", REG_AX, REG_AX | REG_PTR1 }, { "mulax3", REG_AX, REG_AX | REG_PTR1 }, { "mulax5", REG_AX, REG_AX | REG_PTR1 }, { "mulax6", REG_AX, REG_AX | REG_PTR1 }, { "mulax7", REG_AX, REG_AX | REG_PTR1 }, { "mulax9", REG_AX, REG_AX | REG_PTR1 }, { "negax", REG_AX, REG_AX }, { "push0", REG_NONE, REG_AXY }, { "push0ax", REG_AX, REG_Y | REG_SREG }, { "push1", REG_NONE, REG_AXY }, { "push2", REG_NONE, REG_AXY }, { "push3", REG_NONE, REG_AXY }, { "push4", REG_NONE, REG_AXY }, { "push5", REG_NONE, REG_AXY }, { "push6", REG_NONE, REG_AXY }, { "push7", REG_NONE, REG_AXY }, { "pusha", REG_A, REG_Y }, { "pusha0", REG_A, REG_XY }, { "pusha0sp", REG_NONE, REG_AY }, { "pushaFF", REG_A, REG_Y }, { "pushax", REG_AX, REG_Y }, { "pushaysp", REG_Y, REG_AY }, { "pushc0", REG_NONE, REG_A | REG_Y }, { "pushc1", REG_NONE, REG_A | REG_Y }, { "pushc2", REG_NONE, REG_A | REG_Y }, { "pusheax", REG_EAX, REG_Y }, { "pushl0", REG_NONE, REG_AXY }, { "pushw", REG_AX, REG_AXY | REG_PTR1 }, { "pushw0sp", REG_NONE, REG_AXY }, { "pushwidx", REG_AXY, REG_AXY | REG_PTR1 }, { "pushwysp", REG_Y, REG_AXY }, { "regswap", REG_AXY, REG_AXY | REG_TMP1 }, { "regswap1", REG_XY, REG_A }, { "regswap2", REG_XY, REG_A | REG_Y }, { "return0", REG_NONE, REG_AX }, { "return1", REG_NONE, REG_AX }, { "shlax1", REG_AX, REG_AX | REG_TMP1 }, { "shlax2", REG_AX, REG_AX | REG_TMP1 }, { "shlax3", REG_AX, REG_AX | REG_TMP1 }, { "shlax4", REG_AX, REG_AX | REG_TMP1 }, { "shlaxy", REG_AXY, REG_AXY | REG_TMP1 }, { "shleax1", REG_EAX, REG_EAX | REG_TMP1 }, { "shleax2", REG_EAX, REG_EAX | REG_TMP1 }, { "shleax3", REG_EAX, REG_EAX | REG_TMP1 }, { "shleax4", REG_EAX, REG_EAXY | REG_TMP1 }, { "shrax1", REG_AX, REG_AX | REG_TMP1 }, { "shrax2", REG_AX, REG_AX | REG_TMP1 }, { "shrax3", REG_AX, REG_AX | REG_TMP1 }, { "shrax4", REG_AX, REG_AX | REG_TMP1 }, { "shraxy", REG_AXY, REG_AXY | REG_TMP1 }, { "shreax1", REG_EAX, REG_EAX | REG_TMP1 }, { "shreax2", REG_EAX, REG_EAX | REG_TMP1 }, { "shreax3", REG_EAX, REG_EAX | REG_TMP1 }, { "shreax4", REG_EAX, REG_EAXY | REG_TMP1 }, { "staspidx", REG_A | REG_Y, REG_Y | REG_TMP1 | REG_PTR1 }, { "stax0sp", REG_AX, REG_Y }, { "staxspidx", REG_AXY, REG_TMP1 | REG_PTR1 }, { "staxysp", REG_AXY, REG_Y }, { "steax0sp", REG_EAX, REG_Y }, { "steaxysp", REG_EAXY, REG_Y }, { "subeq0sp", REG_AX, REG_AXY }, { "subeqysp", REG_AXY, REG_AXY }, { "subysp", REG_Y, REG_AY }, { "tosadd0ax", REG_AX, REG_EAXY | REG_TMP1 }, { "tosadda0", REG_A, REG_AXY }, { "tosaddax", REG_AX, REG_AXY }, { "tosaddeax", REG_EAX, REG_EAXY | REG_TMP1 }, { "tosand0ax", REG_AX, REG_EAXY | REG_TMP1 }, { "tosanda0", REG_A, REG_AXY }, { "tosandax", REG_AX, REG_AXY }, { "tosandeax", REG_EAX, REG_EAXY | REG_TMP1 }, { "tosaslax", REG_A, REG_AXY | REG_TMP1 }, { "tosasleax", REG_A, REG_EAXY | REG_TMP1 }, { "tosasrax", REG_A, REG_AXY | REG_TMP1 }, { "tosasreax", REG_A, REG_EAXY | REG_TMP1 }, { "tosdiv0ax", REG_AX, REG_ALL }, { "tosdiva0", REG_A, REG_ALL }, { "tosdivax", REG_AX, REG_ALL }, { "tosdiveax", REG_EAX, REG_ALL }, { "toseq00", REG_NONE, REG_AXY | REG_SREG }, { "toseqa0", REG_A, REG_AXY | REG_SREG }, { "toseqax", REG_AX, REG_AXY | REG_SREG }, { "toseqeax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosge00", REG_NONE, REG_AXY | REG_SREG }, { "tosgea0", REG_A, REG_AXY | REG_SREG }, { "tosgeax", REG_AX, REG_AXY | REG_SREG }, { "tosgeeax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosgt00", REG_NONE, REG_AXY | REG_SREG }, { "tosgta0", REG_A, REG_AXY | REG_SREG }, { "tosgtax", REG_AX, REG_AXY | REG_SREG }, { "tosgteax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosicmp", REG_AX, REG_AXY | REG_SREG }, { "tosicmp0", REG_A, REG_AXY | REG_SREG }, { "toslcmp", REG_EAX, REG_A | REG_Y | REG_PTR1 }, { "tosle00", REG_NONE, REG_AXY | REG_SREG }, { "toslea0", REG_A, REG_AXY | REG_SREG }, { "tosleax", REG_AX, REG_AXY | REG_SREG }, { "tosleeax", REG_EAX, REG_AXY | REG_PTR1 }, { "toslt00", REG_NONE, REG_AXY | REG_SREG }, { "toslta0", REG_A, REG_AXY | REG_SREG }, { "tosltax", REG_AX, REG_AXY | REG_SREG }, { "toslteax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosmod0ax", REG_AX, REG_ALL }, { "tosmodeax", REG_EAX, REG_ALL }, { "tosmul0ax", REG_AX, REG_ALL }, { "tosmula0", REG_A, REG_ALL }, { "tosmulax", REG_AX, REG_ALL }, { "tosmuleax", REG_EAX, REG_ALL }, { "tosne00", REG_NONE, REG_AXY | REG_SREG }, { "tosnea0", REG_A, REG_AXY | REG_SREG }, { "tosneax", REG_AX, REG_AXY | REG_SREG }, { "tosneeax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosor0ax", REG_AX, REG_EAXY | REG_TMP1 }, { "tosora0", REG_A, REG_AXY | REG_TMP1 }, { "tosorax", REG_AX, REG_AXY | REG_TMP1 }, { "tosoreax", REG_EAX, REG_EAXY | REG_TMP1 }, { "tosrsub0ax", REG_AX, REG_EAXY | REG_TMP1 }, { "tosrsuba0", REG_A, REG_AXY | REG_TMP1 }, { "tosrsubax", REG_AX, REG_AXY | REG_TMP1 }, { "tosrsubeax", REG_EAX, REG_EAXY | REG_TMP1 }, { "tosshlax", REG_A, REG_AXY | REG_TMP1 }, { "tosshleax", REG_A, REG_EAXY | REG_TMP1 }, { "tosshrax", REG_A, REG_AXY | REG_TMP1 }, { "tosshreax", REG_A, REG_EAXY | REG_TMP1 }, { "tossub0ax", REG_AX, REG_EAXY }, { "tossuba0", REG_A, REG_AXY }, { "tossubax", REG_AX, REG_AXY }, { "tossubeax", REG_EAX, REG_EAXY }, { "tosudiv0ax", REG_AX, REG_ALL & ~REG_SAVE }, { "tosudiva0", REG_A, REG_EAXY | REG_PTR1 }, /* also ptr4 */ { "tosudivax", REG_AX, REG_EAXY | REG_PTR1 }, /* also ptr4 */ { "tosudiveax", REG_EAX, REG_ALL & ~REG_SAVE }, { "tosuge00", REG_NONE, REG_AXY | REG_SREG }, { "tosugea0", REG_A, REG_AXY | REG_SREG }, { "tosugeax", REG_AX, REG_AXY | REG_SREG }, { "tosugeeax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosugt00", REG_NONE, REG_AXY | REG_SREG }, { "tosugta0", REG_A, REG_AXY | REG_SREG }, { "tosugtax", REG_AX, REG_AXY | REG_SREG }, { "tosugteax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosule00", REG_NONE, REG_AXY | REG_SREG }, { "tosulea0", REG_A, REG_AXY | REG_SREG }, { "tosuleax", REG_AX, REG_AXY | REG_SREG }, { "tosuleeax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosult00", REG_NONE, REG_AXY | REG_SREG }, { "tosulta0", REG_A, REG_AXY | REG_SREG }, { "tosultax", REG_AX, REG_AXY | REG_SREG }, { "tosulteax", REG_EAX, REG_AXY | REG_PTR1 }, { "tosumod0ax", REG_AX, REG_ALL & ~REG_SAVE }, { "tosumoda0", REG_A, REG_EAXY | REG_PTR1 }, /* also ptr4 */ { "tosumodax", REG_AX, REG_EAXY | REG_PTR1 }, /* also ptr4 */ { "tosumodeax", REG_EAX, REG_ALL & ~REG_SAVE }, { "tosumul0ax", REG_AX, REG_ALL }, { "tosumula0", REG_A, REG_ALL }, { "tosumulax", REG_AX, REG_ALL }, { "tosumuleax", REG_EAX, REG_ALL }, { "tosxor0ax", REG_AX, REG_EAXY | REG_TMP1 }, { "tosxora0", REG_A, REG_AXY | REG_TMP1 }, { "tosxorax", REG_AX, REG_AXY | REG_TMP1 }, { "tosxoreax", REG_EAX, REG_EAXY | REG_TMP1 }, { "tsteax", REG_EAX, REG_Y }, { "utsteax", REG_EAX, REG_Y }, }; #define FuncInfoCount (sizeof(FuncInfoTable) / sizeof(FuncInfoTable[0])) /* Table with names of zero page locations used by the compiler */ static const ZPInfo ZPInfoTable[] = { { 0, "ptr1", REG_PTR1_LO, REG_PTR1 }, { 0, "ptr1+1", REG_PTR1_HI, REG_PTR1 }, { 0, "ptr2", REG_PTR2_LO, REG_PTR2 }, { 0, "ptr2+1", REG_PTR2_HI, REG_PTR2 }, { 4, "ptr3", REG_NONE, REG_NONE }, { 4, "ptr4", REG_NONE, REG_NONE }, { 7, "regbank", REG_NONE, REG_NONE }, { 0, "regsave", REG_SAVE_LO, REG_SAVE }, { 0, "regsave+1", REG_SAVE_HI, REG_SAVE }, { 0, "sp", REG_SP_LO, REG_SP }, { 0, "sp+1", REG_SP_HI, REG_SP }, { 0, "sreg", REG_SREG_LO, REG_SREG }, { 0, "sreg+1", REG_SREG_HI, REG_SREG }, { 0, "tmp1", REG_TMP1, REG_TMP1 }, { 0, "tmp2", REG_NONE, REG_NONE }, { 0, "tmp3", REG_NONE, REG_NONE }, { 0, "tmp4", REG_NONE, REG_NONE }, }; #define ZPInfoCount (sizeof(ZPInfoTable) / sizeof(ZPInfoTable[0])) /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int CompareFuncInfo (const void* Key, const void* Info) /* Compare function for bsearch */ { return strcmp (Key, ((const FuncInfo*) Info)->Name); } void GetFuncInfo (const char* Name, unsigned short* Use, unsigned short* Chg) /* For the given function, lookup register information and store it into * the given variables. If the function is unknown, assume it will use and * load all registers. */ { /* If the function name starts with an underline, it is an external * function. Search for it in the symbol table. If the function does * not start with an underline, it may be a runtime support function. * Search for it in the list of builtin functions. */ if (Name[0] == '_') { /* Search in the symbol table, skip the leading underscore */ SymEntry* E = FindGlobalSym (Name+1); /* Did we find it in the top level table? */ if (E && IsTypeFunc (E->Type)) { FuncDesc* D = E->V.F.Func; /* A function may use the A or A/X registers if it is a fastcall * function. If it is not a fastcall function but a variadic one, * it will use the Y register (the parameter size is passed here). * In all other cases, no registers are used. However, we assume * that any function will destroy all registers. */ if (IsQualFastcall (E->Type) && D->ParamCount > 0) { /* Will use registers depending on the last param */ unsigned LastParamSize = CheckedSizeOf (D->LastParam->Type); if (LastParamSize == 1) { *Use = REG_A; } else if (LastParamSize == 2) { *Use = REG_AX; } else { *Use = REG_EAX; } } else if ((D->Flags & FD_VARIADIC) != 0) { *Use = REG_Y; } else { /* Will not use any registers */ *Use = REG_NONE; } /* Will destroy all registers */ *Chg = REG_ALL; /* Done */ return; } } else if (IsDigit (Name[0]) || Name[0] == '$') { /* A call to a numeric address. Assume that anything gets used and * destroyed. This is not a real problem, since numeric addresses * are used mostly in inline assembly anyway. */ *Use = REG_ALL; *Chg = REG_ALL; return; } else { /* Search for the function in the list of builtin functions */ const FuncInfo* Info = bsearch (Name, FuncInfoTable, FuncInfoCount, sizeof(FuncInfo), CompareFuncInfo); /* Do we know the function? */ if (Info) { /* Use the information we have */ *Use = Info->Use; *Chg = Info->Chg; } else { /* It's an internal function we have no information for. If in * debug mode, output an additional warning, so we have a chance * to fix it. Otherwise assume that the internal function will * use and change all registers. */ if (Debug) { fprintf (stderr, "No info about internal function `%s'\n", Name); } *Use = REG_ALL; *Chg = REG_ALL; } return; } /* Function not found - assume that the primary register is input, and all * registers are changed */ *Use = REG_EAXY; *Chg = REG_ALL; } static int CompareZPInfo (const void* Name, const void* Info) /* Compare function for bsearch */ { /* Cast the pointers to the correct data type */ const char* N = (const char*) Name; const ZPInfo* E = (const ZPInfo*) Info; /* Do the compare. Be careful because of the length (Info may contain * more than just the zeropage name). */ if (E->Len == 0) { /* Do a full compare */ return strcmp (N, E->Name); } else { /* Only compare the first part */ int Res = strncmp (N, E->Name, E->Len); if (Res == 0 && (N[E->Len] != '\0' && N[E->Len] != '+')) { /* Name is actually longer than Info->Name */ Res = -1; } return Res; } } const ZPInfo* GetZPInfo (const char* Name) /* If the given name is a zero page symbol, return a pointer to the info * struct for this symbol, otherwise return NULL. */ { /* Search for the zp location in the list */ return bsearch (Name, ZPInfoTable, ZPInfoCount, sizeof(ZPInfo), CompareZPInfo); } static unsigned GetRegInfo2 (CodeSeg* S, CodeEntry* E, int Index, Collection* Visited, unsigned Used, unsigned Unused, unsigned Wanted) /* Recursively called subfunction for GetRegInfo. */ { /* Follow the instruction flow recording register usage. */ while (1) { unsigned R; /* Check if we have already visited the current code entry. If so, * bail out. */ if (CE_HasMark (E)) { break; } /* Mark this entry as already visited */ CE_SetMark (E); CollAppend (Visited, E); /* Evaluate the used registers */ R = E->Use; if (E->OPC == OP65_RTS || ((E->Info & OF_UBRA) != 0 && E->JumpTo == 0)) { /* This instruction will leave the function */ R |= S->ExitRegs; } if (R != REG_NONE) { /* We are not interested in the use of any register that has been * used before. */ R &= ~Unused; /* Remember the remaining registers */ Used |= R; } /* Evaluate the changed registers */ if ((R = E->Chg) != REG_NONE) { /* We are not interested in the use of any register that has been * used before. */ R &= ~Used; /* Remember the remaining registers */ Unused |= R; } /* If we know about all registers now, bail out */ if (((Used | Unused) & Wanted) == Wanted) { break; } /* If the instruction is an RTS or RTI, we're done */ if ((E->Info & OF_RET) != 0) { break; } /* If we have an unconditional branch, follow this branch if possible, * otherwise we're done. */ if ((E->Info & OF_UBRA) != 0) { /* Does this jump have a valid target? */ if (E->JumpTo) { /* Unconditional jump */ E = E->JumpTo->Owner; Index = -1; /* Invalidate */ } else { /* Jump outside means we're done */ break; } /* In case of conditional branches, follow the branch if possible and * follow the normal flow (branch not taken) afterwards. If we cannot * follow the branch, we're done. */ } else if ((E->Info & OF_CBRA) != 0) { /* Recursively determine register usage at the branch target */ unsigned U1; unsigned U2; if (E->JumpTo) { /* Jump to internal label */ U1 = GetRegInfo2 (S, E->JumpTo->Owner, -1, Visited, Used, Unused, Wanted); } else { /* Jump to external label. This will effectively exit the * function, so we use the exitregs information here. */ U1 = S->ExitRegs; } /* Get the next entry */ if (Index < 0) { Index = CS_GetEntryIndex (S, E); } if ((E = CS_GetEntry (S, ++Index)) == 0) { Internal ("GetRegInfo2: No next entry!"); } /* Follow flow if branch not taken */ U2 = GetRegInfo2 (S, E, Index, Visited, Used, Unused, Wanted); /* Registers are used if they're use in any of the branches */ return U1 | U2; } else { /* Just go to the next instruction */ if (Index < 0) { Index = CS_GetEntryIndex (S, E); } E = CS_GetEntry (S, ++Index); if (E == 0) { /* No next entry */ Internal ("GetRegInfo2: No next entry!"); } } } /* Return to the caller the complement of all unused registers */ return Used; } static unsigned GetRegInfo1 (CodeSeg* S, CodeEntry* E, int Index, Collection* Visited, unsigned Used, unsigned Unused, unsigned Wanted) /* Recursively called subfunction for GetRegInfo. */ { /* Remember the current count of the line collection */ unsigned Count = CollCount (Visited); /* Call the worker routine */ unsigned R = GetRegInfo2 (S, E, Index, Visited, Used, Unused, Wanted); /* Restore the old count, unmarking all new entries */ unsigned NewCount = CollCount (Visited); while (NewCount-- > Count) { CodeEntry* E = CollAt (Visited, NewCount); CE_ResetMark (E); CollDelete (Visited, NewCount); } /* Return the registers used */ return R; } unsigned GetRegInfo (struct CodeSeg* S, unsigned Index, unsigned Wanted) /* Determine register usage information for the instructions starting at the * given index. */ { CodeEntry* E; Collection Visited; /* Visited entries */ unsigned R; /* Get the code entry for the given index */ if (Index >= CS_GetEntryCount (S)) { /* There is no such code entry */ return REG_NONE; } E = CS_GetEntry (S, Index); /* Initialize the data structure used to collection information */ InitCollection (&Visited); /* Call the recursive subfunction */ R = GetRegInfo1 (S, E, Index, &Visited, REG_NONE, REG_NONE, Wanted); /* Delete the line collection */ DoneCollection (&Visited); /* Return the registers used */ return R; } int RegAUsed (struct CodeSeg* S, unsigned Index) /* Check if the value in A is used. */ { return (GetRegInfo (S, Index, REG_A) & REG_A) != 0; } int RegXUsed (struct CodeSeg* S, unsigned Index) /* Check if the value in X is used. */ { return (GetRegInfo (S, Index, REG_X) & REG_X) != 0; } int RegYUsed (struct CodeSeg* S, unsigned Index) /* Check if the value in Y is used. */ { return (GetRegInfo (S, Index, REG_Y) & REG_Y) != 0; } int RegAXUsed (struct CodeSeg* S, unsigned Index) /* Check if the value in A or(!) the value in X are used. */ { return (GetRegInfo (S, Index, REG_AX) & REG_AX) != 0; } int RegEAXUsed (struct CodeSeg* S, unsigned Index) /* Check if any of the four bytes in EAX are used. */ { return (GetRegInfo (S, Index, REG_EAX) & REG_EAX) != 0; } unsigned GetKnownReg (unsigned Use, const RegContents* RC) /* Return the register or zero page location from the set in Use, thats * contents are known. If Use does not contain any register, or if the * register in question does not have a known value, return REG_NONE. */ { if ((Use & REG_A) != 0) { return (RC == 0 || RC->RegA >= 0)? REG_A : REG_NONE; } else if ((Use & REG_X) != 0) { return (RC == 0 || RC->RegX >= 0)? REG_X : REG_NONE; } else if ((Use & REG_Y) != 0) { return (RC == 0 || RC->RegY >= 0)? REG_Y : REG_NONE; } else if ((Use & REG_TMP1) != 0) { return (RC == 0 || RC->Tmp1 >= 0)? REG_TMP1 : REG_NONE; } else if ((Use & REG_PTR1_LO) != 0) { return (RC == 0 || RC->Ptr1Lo >= 0)? REG_PTR1_LO : REG_NONE; } else if ((Use & REG_PTR1_HI) != 0) { return (RC == 0 || RC->Ptr1Hi >= 0)? REG_PTR1_HI : REG_NONE; } else if ((Use & REG_SREG_LO) != 0) { return (RC == 0 || RC->SRegLo >= 0)? REG_SREG_LO : REG_NONE; } else if ((Use & REG_SREG_HI) != 0) { return (RC == 0 || RC->SRegHi >= 0)? REG_SREG_HI : REG_NONE; } else { return REG_NONE; } } static cmp_t FindCmpCond (const char* Code, unsigned CodeLen) /* Search for a compare condition by the given code using the given length */ { unsigned I; /* Linear search */ for (I = 0; I < sizeof (CmpSuffixTab) / sizeof (CmpSuffixTab [0]); ++I) { if (strncmp (Code, CmpSuffixTab [I], CodeLen) == 0) { /* Found */ return I; } } /* Not found */ return CMP_INV; } cmp_t FindBoolCmpCond (const char* Name) /* Check if the given string is the name of one of the boolean transformer * subroutine, and if so, return the condition that is evaluated by this * routine. Return CMP_INV if the condition is not recognised. */ { /* Check for the correct subroutine name */ if (strncmp (Name, "bool", 4) == 0) { /* Name is ok, search for the code in the table */ return FindCmpCond (Name+4, strlen(Name)-4); } else { /* Not found */ return CMP_INV; } } cmp_t FindTosCmpCond (const char* Name) /* Check if this is a call to one of the TOS compare functions (tosgtax). * Return the condition code or CMP_INV on failure. */ { unsigned Len = strlen (Name); /* Check for the correct subroutine name */ if (strncmp (Name, "tos", 3) == 0 && strcmp (Name+Len-2, "ax") == 0) { /* Name is ok, search for the code in the table */ return FindCmpCond (Name+3, Len-3-2); } else { /* Not found */ return CMP_INV; } }
856
./cc65/src/cc65/coptshift.c
/*****************************************************************************/ /* */ /* coptshift.c */ /* */ /* Optimize shifts */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptshift.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Shift types. Shift type is in the first byte, shift count in the second */ enum { SHIFT_NONE = 0x0000, /* Masks */ SHIFT_MASK_COUNT = 0x00FF, SHIFT_MASK_DIR = 0x0F00, SHIFT_MASK_MODE = 0xF000, /* Arithmetic or logical */ SHIFT_MASK_TYPE = SHIFT_MASK_DIR | SHIFT_MASK_MODE, /* Shift counts */ SHIFT_COUNT_Y = 0x0000, /* Count is in Y register */ SHIFT_COUNT_1 = 0x0001, SHIFT_COUNT_2 = 0x0002, SHIFT_COUNT_3 = 0x0003, SHIFT_COUNT_4 = 0x0004, SHIFT_COUNT_5 = 0x0005, SHIFT_COUNT_6 = 0x0006, SHIFT_COUNT_7 = 0x0007, /* Shift directions */ SHIFT_DIR_LEFT = 0x0100, SHIFT_DIR_RIGHT = 0x0200, /* Shift modes */ SHIFT_MODE_ARITH = 0x1000, SHIFT_MODE_LOGICAL = 0x2000, /* Shift types */ SHIFT_TYPE_ASL = SHIFT_DIR_LEFT | SHIFT_MODE_ARITH, SHIFT_TYPE_ASR = SHIFT_DIR_RIGHT | SHIFT_MODE_ARITH, SHIFT_TYPE_LSL = SHIFT_DIR_LEFT | SHIFT_MODE_LOGICAL, SHIFT_TYPE_LSR = SHIFT_DIR_RIGHT | SHIFT_MODE_LOGICAL, /* Complete specs */ SHIFT_ASL_Y = SHIFT_TYPE_ASL | SHIFT_COUNT_Y, SHIFT_ASR_Y = SHIFT_TYPE_ASR | SHIFT_COUNT_Y, SHIFT_LSL_Y = SHIFT_TYPE_LSL | SHIFT_COUNT_Y, SHIFT_LSR_Y = SHIFT_TYPE_LSR | SHIFT_COUNT_Y, SHIFT_ASL_1 = SHIFT_TYPE_ASL | SHIFT_COUNT_1, SHIFT_ASR_1 = SHIFT_TYPE_ASR | SHIFT_COUNT_1, SHIFT_LSL_1 = SHIFT_TYPE_LSL | SHIFT_COUNT_1, SHIFT_LSR_1 = SHIFT_TYPE_LSR | SHIFT_COUNT_1, SHIFT_ASL_2 = SHIFT_TYPE_ASL | SHIFT_COUNT_2, SHIFT_ASR_2 = SHIFT_TYPE_ASR | SHIFT_COUNT_2, SHIFT_LSL_2 = SHIFT_TYPE_LSL | SHIFT_COUNT_2, SHIFT_LSR_2 = SHIFT_TYPE_LSR | SHIFT_COUNT_2, SHIFT_ASL_3 = SHIFT_TYPE_ASL | SHIFT_COUNT_3, SHIFT_ASR_3 = SHIFT_TYPE_ASR | SHIFT_COUNT_3, SHIFT_LSL_3 = SHIFT_TYPE_LSL | SHIFT_COUNT_3, SHIFT_LSR_3 = SHIFT_TYPE_LSR | SHIFT_COUNT_3, SHIFT_ASL_4 = SHIFT_TYPE_ASL | SHIFT_COUNT_4, SHIFT_ASR_4 = SHIFT_TYPE_ASR | SHIFT_COUNT_4, SHIFT_LSL_4 = SHIFT_TYPE_LSL | SHIFT_COUNT_4, SHIFT_LSR_4 = SHIFT_TYPE_LSR | SHIFT_COUNT_4, SHIFT_ASL_5 = SHIFT_TYPE_ASL | SHIFT_COUNT_5, SHIFT_ASR_5 = SHIFT_TYPE_ASR | SHIFT_COUNT_5, SHIFT_LSL_5 = SHIFT_TYPE_LSL | SHIFT_COUNT_5, SHIFT_LSR_5 = SHIFT_TYPE_LSR | SHIFT_COUNT_5, SHIFT_ASL_6 = SHIFT_TYPE_ASL | SHIFT_COUNT_6, SHIFT_ASR_6 = SHIFT_TYPE_ASR | SHIFT_COUNT_6, SHIFT_LSL_6 = SHIFT_TYPE_LSL | SHIFT_COUNT_6, SHIFT_LSR_6 = SHIFT_TYPE_LSR | SHIFT_COUNT_6, SHIFT_ASL_7 = SHIFT_TYPE_ASL | SHIFT_COUNT_7, SHIFT_ASR_7 = SHIFT_TYPE_ASR | SHIFT_COUNT_7, SHIFT_LSL_7 = SHIFT_TYPE_LSL | SHIFT_COUNT_7, SHIFT_LSR_7 = SHIFT_TYPE_LSR | SHIFT_COUNT_7, }; /* Macros to extract values from a shift type */ #define SHIFT_COUNT(S) ((S) & SHIFT_MASK_COUNT) #define SHIFT_DIR(S) ((S) & SHIFT_MASK_DIR) #define SHIFT_MODE(S) ((S) & SHIFT_MASK_MODE) #define SHIFT_TYPE(S) ((S) & SHIFT_MASK_TYPE) /*****************************************************************************/ /* Helper routines */ /*****************************************************************************/ static unsigned GetShift (const char* Name) /* Determine the shift from the name of the subroutine */ { unsigned Type; if (strncmp (Name, "aslax", 5) == 0) { Type = SHIFT_TYPE_ASL; } else if (strncmp (Name, "asrax", 5) == 0) { Type = SHIFT_TYPE_ASR; } else if (strncmp (Name, "shlax", 5) == 0) { Type = SHIFT_TYPE_LSL; } else if (strncmp (Name, "shrax", 5) == 0) { Type = SHIFT_TYPE_LSR; } else { /* Nothing we know */ return SHIFT_NONE; } /* Get the count */ switch (Name[5]) { case 'y': Type |= SHIFT_COUNT_Y; break; case '1': Type |= SHIFT_COUNT_1; break; case '2': Type |= SHIFT_COUNT_2; break; case '3': Type |= SHIFT_COUNT_3; break; case '4': Type |= SHIFT_COUNT_4; break; case '5': Type |= SHIFT_COUNT_5; break; case '6': Type |= SHIFT_COUNT_6; break; case '7': Type |= SHIFT_COUNT_7; break; default: return SHIFT_NONE; } /* Make sure nothing follows */ if (Name[6] == '\0') { return Type; } else { return SHIFT_NONE; } } /*****************************************************************************/ /* Optimize shifts */ /*****************************************************************************/ unsigned OptShift1 (CodeSeg* S) /* A call to the shlaxN routine may get replaced by one or more asl insns * if the value of X is not used later. If X is used later, but it is zero * on entry and it's a shift by one, it may get replaced by: * * asl a * bcc L1 * inx * L1: * */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { unsigned Shift; CodeEntry* N; CodeEntry* X; CodeLabel* L; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && (Shift = GetShift (E->Arg)) != SHIFT_NONE && SHIFT_DIR (Shift) == SHIFT_DIR_LEFT) { unsigned Count = SHIFT_COUNT (Shift); if (!RegXUsed (S, I+1)) { if (Count == SHIFT_COUNT_Y) { CodeLabel* L; if (S->CodeSizeFactor < 200) { goto NextEntry; } /* Change into * * L1: asl a * dey * bpl L1 * ror a */ /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+1); L = CS_GenLabel (S, X); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+2); /* bpl L1 */ X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, X, I+3); /* ror a */ X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+4); } else { /* Insert shift insns */ while (Count--) { X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+1); } } } else if (E->RI->In.RegX == 0 && Count == 1 && (N = CS_GetNextEntry (S, I)) != 0) { /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+1); /* bcc L1 */ L = CS_GenLabel (S, N); X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, X, I+2); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+3); } else { /* We won't handle this one */ goto NextEntry; } /* Delete the call to shlax */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptShift2(CodeSeg* S) /* A call to the asrax1 routines may get replaced by something simpler, if * X is not used later: * * cmp #$80 * ror a * */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { unsigned Shift; unsigned Count; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && (Shift = GetShift (E->Arg)) != SHIFT_NONE && SHIFT_TYPE (Shift) == SHIFT_TYPE_ASR && (Count = SHIFT_COUNT (Shift)) > 0 && Count * 100 <= S->CodeSizeFactor && !RegXUsed (S, I+1)) { CodeEntry* X; unsigned J = I+1; /* Generate the replacement sequence */ while (Count--) { /* cmp #$80 */ X = NewCodeEntry (OP65_CMP, AM65_IMM, "$80", 0, E->LI); CS_InsertEntry (S, X, J++); /* ror a */ X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, J++); } /* Delete the call to asrax */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptShift3 (CodeSeg* S) /* The sequence * * bcc L * inx * L: jsr shrax1 * * may get replaced by * * ror a * * if X is zero on entry. For shift counts > 1, more * * shr a * * must be added. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { unsigned Shift; unsigned Count; CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if ((L[0]->OPC == OP65_BCC || L[0]->OPC == OP65_JCC) && L[0]->JumpTo != 0 && L[0]->RI->In.RegX == 0 && CS_GetEntries (S, L+1, I+1, 2) && L[1]->OPC == OP65_INX && L[0]->JumpTo->Owner == L[2] && !CS_RangeHasLabel (S, I, 2) && L[2]->OPC == OP65_JSR && (Shift = GetShift (L[2]->Arg)) != SHIFT_NONE && SHIFT_DIR (Shift) == SHIFT_DIR_RIGHT && (Count = SHIFT_COUNT (Shift)) > 0) { /* Add the replacement insn instead */ CodeEntry* X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+3); while (--Count) { X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+4); } /* Remove the bcs/dex/jsr */ CS_DelEntries (S, I, 3); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptShift4 (CodeSeg* S) /* Calls to the asraxN or shraxN routines may get replaced by one or more lsr * insns if the value of X is zero. */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { unsigned Shift; unsigned Count; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for the sequence */ if (E->OPC == OP65_JSR && (Shift = GetShift (E->Arg)) != SHIFT_NONE && SHIFT_DIR (Shift) == SHIFT_DIR_RIGHT && E->RI->In.RegX == 0) { CodeEntry* X; /* Shift count may be in Y */ Count = SHIFT_COUNT (Shift); if (Count == SHIFT_COUNT_Y) { CodeLabel* L; if (S->CodeSizeFactor < 200) { /* Not acceptable */ goto NextEntry; } /* Generate: * * L1: lsr a * dey * bpl L1 * rol a * * A negative shift count or one that is greater or equal than * the bit width of the left operand (which is promoted to * integer before the operation) causes undefined behaviour, so * above transformation is safe. */ /* lsr a */ X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+1); L = CS_GenLabel (S, X); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, E->LI); CS_InsertEntry (S, X, I+2); /* bpl L1 */ X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, E->LI); CS_InsertEntry (S, X, I+3); /* rol a */ X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+4); } else { /* Insert shift insns */ while (Count--) { X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, I+1); } } /* Delete the call to shrax */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptShift5 (CodeSeg* S) /* Search for the sequence * * lda xxx * ldx yyy * jsr aslax1/asrax1/shlax1/shrax1 * sta aaa * stx bbb * * and replace it by * * lda xxx * asl a * sta aaa * lda yyy * rol a * sta bbb * * or similar, provided that a/x is not used later */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { unsigned ShiftType; CodeEntry* L[5]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && (L[0]->AM == AM65_ABS || L[0]->AM == AM65_ZP) && CS_GetEntries (S, L+1, I+1, 4) && !CS_RangeHasLabel (S, I+1, 4) && L[1]->OPC == OP65_LDX && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP) && L[2]->OPC == OP65_JSR && (ShiftType = GetShift (L[2]->Arg)) != SHIFT_NONE && SHIFT_COUNT(ShiftType) == 1 && L[3]->OPC == OP65_STA && (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP) && L[4]->OPC == OP65_STX && (L[4]->AM == AM65_ABS || L[4]->AM == AM65_ZP) && !RegAXUsed (S, I+5)) { CodeEntry* X; /* Handle the four shift types differently */ switch (ShiftType) { case SHIFT_ASR_1: X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+5); X = NewCodeEntry (OP65_CMP, AM65_IMM, "$80", 0, L[2]->LI); CS_InsertEntry (S, X, I+6); X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+7); X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI); CS_InsertEntry (S, X, I+8); X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+9); X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+10); X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+11); CS_DelEntries (S, I, 5); break; case SHIFT_LSR_1: X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+5); X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+6); X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI); CS_InsertEntry (S, X, I+7); X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+8); X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+9); X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+10); CS_DelEntries (S, I, 5); break; case SHIFT_LSL_1: case SHIFT_ASL_1: /* These two are identical */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+1); X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+2); X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+3); X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, L[2]->LI); CS_InsertEntry (S, X, I+4); X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI); CS_InsertEntry (S, X, I+5); CS_DelEntries (S, I+6, 4); break; } /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptShift6 (CodeSeg* S) /* Inline the shift subroutines. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { unsigned Shift; unsigned Count; CodeEntry* X; unsigned IP; /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check for a call to one of the shift routine */ if (E->OPC == OP65_JSR && (Shift = GetShift (E->Arg)) != SHIFT_NONE && SHIFT_DIR (Shift) == SHIFT_DIR_LEFT && (Count = SHIFT_COUNT (Shift)) > 0) { /* Code is: * * stx tmp1 * asl a * rol tmp1 * (repeat ShiftCount-1 times) * ldx tmp1 * * which makes 4 + 3 * ShiftCount bytes, compared to the original * 3 bytes for the subroutine call. However, in most cases, the * final load of the X register gets merged with some other insn * and replaces a txa, so for a shift count of 1, we get a factor * of 200, which matches nicely the CodeSizeFactor enabled with -Oi */ if (Count > 1 || S->CodeSizeFactor > 200) { unsigned Size = 4 + 3 * Count; if ((Size * 100 / 3) > S->CodeSizeFactor) { /* Not acceptable */ goto NextEntry; } } /* Inline the code. Insertion point is behind the subroutine call */ IP = (I + 1); /* stx tmp1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, E->LI); CS_InsertEntry (S, X, IP++); while (Count--) { /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI); CS_InsertEntry (S, X, IP++); /* rol tmp1 */ X = NewCodeEntry (OP65_ROL, AM65_ZP, "tmp1", 0, E->LI); CS_InsertEntry (S, X, IP++); } /* ldx tmp1 */ X = NewCodeEntry (OP65_LDX, AM65_ZP, "tmp1", 0, E->LI); CS_InsertEntry (S, X, IP++); /* Remove the subroutine call */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } NextEntry: /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
857
./cc65/src/cc65/reginfo.c
/*****************************************************************************/ /* */ /* reginfo.c */ /* */ /* 6502 register tracking info */ /* */ /* */ /* */ /* (C) 2001-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" /* cc65 */ #include "reginfo.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void RC_Invalidate (RegContents* C) /* Invalidate all registers */ { C->RegA = UNKNOWN_REGVAL; C->RegX = UNKNOWN_REGVAL; C->RegY = UNKNOWN_REGVAL; C->SRegLo = UNKNOWN_REGVAL; C->SRegHi = UNKNOWN_REGVAL; C->Ptr1Lo = UNKNOWN_REGVAL; C->Ptr1Hi = UNKNOWN_REGVAL; C->Tmp1 = UNKNOWN_REGVAL; } void RC_InvalidateZP (RegContents* C) /* Invalidate all ZP registers */ { C->SRegLo = UNKNOWN_REGVAL; C->SRegHi = UNKNOWN_REGVAL; C->Ptr1Lo = UNKNOWN_REGVAL; C->Ptr1Hi = UNKNOWN_REGVAL; C->Tmp1 = UNKNOWN_REGVAL; } static void RC_Dump1 (FILE* F, const char* Desc, short Val) /* Dump one register value */ { if (RegValIsKnown (Val)) { fprintf (F, "%s=$%02X ", Desc, Val); } else { fprintf (F, "%s=$XX ", Desc); } } void RC_Dump (FILE* F, const RegContents* RC) /* Dump the contents of the given RegContents struct */ { RC_Dump1 (F, "A", RC->RegA); RC_Dump1 (F, "X", RC->RegX); RC_Dump1 (F, "Y", RC->RegY); RC_Dump1 (F, "SREG", RC->SRegLo); RC_Dump1 (F, "SREG+1", RC->SRegHi); RC_Dump1 (F, "PTR1", RC->Ptr1Lo); RC_Dump1 (F, "PTR1+1", RC->Ptr1Hi); RC_Dump1 (F, "TMP1", RC->Tmp1); fprintf (F, "\n"); } RegInfo* NewRegInfo (const RegContents* RC) /* Allocate a new register info, initialize and return it. If RC is not * a NULL pointer, it is used to initialize both, the input and output * registers. If the pointer is NULL, all registers are set to unknown. */ { /* Allocate memory */ RegInfo* RI = xmalloc (sizeof (RegInfo)); /* Initialize the registers */ if (RC) { RI->In = *RC; RI->Out = *RC; RI->Out2 = *RC; } else { RC_Invalidate (&RI->In); RC_Invalidate (&RI->Out); RC_Invalidate (&RI->Out2); } /* Return the new struct */ return RI; } void FreeRegInfo (RegInfo* RI) /* Free a RegInfo struct */ { xfree (RI); } void DumpRegInfo (const char* Desc, const RegInfo* RI) /* Dump the register info for debugging */ { fprintf (stdout, "%s:\n", Desc); fprintf (stdout, "In: "); RC_Dump (stdout, &RI->In); fprintf (stdout, "Out: "); RC_Dump (stdout, &RI->Out); }
858
./cc65/src/cc65/pragma.c
/*****************************************************************************/ /* */ /* pragma.c */ /* */ /* Pragma handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "chartype.h" #include "segnames.h" #include "tgttrans.h" /* cc65 */ #include "codegen.h" #include "error.h" #include "expr.h" #include "global.h" #include "litpool.h" #include "scanner.h" #include "scanstrbuf.h" #include "symtab.h" #include "pragma.h" /*****************************************************************************/ /* data */ /*****************************************************************************/ /* Tokens for the #pragmas */ typedef enum { PRAGMA_ILLEGAL = -1, PRAGMA_ALIGN, PRAGMA_BSS_NAME, PRAGMA_BSSSEG, /* obsolete */ PRAGMA_CHARMAP, PRAGMA_CHECK_STACK, PRAGMA_CHECKSTACK, /* obsolete */ PRAGMA_CODE_NAME, PRAGMA_CODESEG, /* obsolete */ PRAGMA_CODESIZE, PRAGMA_DATA_NAME, PRAGMA_DATASEG, /* obsolete */ PRAGMA_LOCAL_STRINGS, PRAGMA_OPTIMIZE, PRAGMA_REGVARADDR, PRAGMA_REGISTER_VARS, PRAGMA_REGVARS, /* obsolete */ PRAGMA_RODATA_NAME, PRAGMA_RODATASEG, /* obsolete */ PRAGMA_SIGNED_CHARS, PRAGMA_SIGNEDCHARS, /* obsolete */ PRAGMA_STATIC_LOCALS, PRAGMA_STATICLOCALS, /* obsolete */ PRAGMA_WARN, PRAGMA_WRITABLE_STRINGS, PRAGMA_ZPSYM, PRAGMA_COUNT } pragma_t; /* Pragma table */ static const struct Pragma { const char* Key; /* Keyword */ pragma_t Tok; /* Token */ } Pragmas[PRAGMA_COUNT] = { { "align", PRAGMA_ALIGN }, { "bss-name", PRAGMA_BSS_NAME }, { "bssseg", PRAGMA_BSSSEG }, /* obsolete */ { "charmap", PRAGMA_CHARMAP }, { "check-stack", PRAGMA_CHECK_STACK }, { "checkstack", PRAGMA_CHECKSTACK }, /* obsolete */ { "code-name", PRAGMA_CODE_NAME }, { "codeseg", PRAGMA_CODESEG }, /* obsolete */ { "codesize", PRAGMA_CODESIZE }, { "data-name", PRAGMA_DATA_NAME }, { "dataseg", PRAGMA_DATASEG }, /* obsolete */ { "local-strings", PRAGMA_LOCAL_STRINGS }, { "optimize", PRAGMA_OPTIMIZE }, { "register-vars", PRAGMA_REGISTER_VARS }, { "regvaraddr", PRAGMA_REGVARADDR }, { "regvars", PRAGMA_REGVARS }, /* obsolete */ { "rodata-name", PRAGMA_RODATA_NAME }, { "rodataseg", PRAGMA_RODATASEG }, /* obsolete */ { "signed-chars", PRAGMA_SIGNED_CHARS }, { "signedchars", PRAGMA_SIGNEDCHARS }, /* obsolete */ { "static-locals", PRAGMA_STATIC_LOCALS }, { "staticlocals", PRAGMA_STATICLOCALS }, /* obsolete */ { "warn", PRAGMA_WARN }, { "writable-strings", PRAGMA_WRITABLE_STRINGS }, { "zpsym", PRAGMA_ZPSYM }, }; /* Result of ParsePushPop */ typedef enum { PP_NONE, PP_POP, PP_PUSH, PP_ERROR, } PushPopResult; /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void PragmaErrorSkip (void) /* Called in case of an error, skips tokens until the closing paren or a * semicolon is reached. */ { static const token_t TokenList[] = { TOK_RPAREN, TOK_SEMI }; SkipTokens (TokenList, sizeof(TokenList) / sizeof(TokenList[0])); } static int CmpKey (const void* Key, const void* Elem) /* Compare function for bsearch */ { return strcmp ((const char*) Key, ((const struct Pragma*) Elem)->Key); } static pragma_t FindPragma (const StrBuf* Key) /* Find a pragma and return the token. Return PRAGMA_ILLEGAL if the keyword is * not a valid pragma. */ { struct Pragma* P; P = bsearch (SB_GetConstBuf (Key), Pragmas, PRAGMA_COUNT, sizeof (Pragmas[0]), CmpKey); return P? P->Tok : PRAGMA_ILLEGAL; } static int GetComma (StrBuf* B) /* Expects and skips a comma in B. Prints an error and returns zero if no * comma is found. Return a value <> 0 otherwise. */ { SB_SkipWhite (B); if (SB_Get (B) != ',') { Error ("Comma expected"); return 0; } SB_SkipWhite (B); return 1; } static int GetString (StrBuf* B, StrBuf* S) /* Expects and skips a string in B. Prints an error and returns zero if no * string is found. Returns a value <> 0 otherwise. */ { if (!SB_GetString (B, S)) { Error ("String literal expected"); return 0; } return 1; } static int GetNumber (StrBuf* B, long* Val) /* Expects and skips a number in B. Prints an eror and returns zero if no * number is found. Returns a value <> 0 otherwise. */ { if (!SB_GetNumber (B, Val)) { Error ("Constant integer expected"); return 0; } return 1; } static IntStack* GetWarning (StrBuf* B) /* Get a warning name from the string buffer. Returns a pointer to the intstack * that holds the state of the warning, and NULL in case of errors. The * function will output error messages in case of problems. */ { IntStack* S = 0; StrBuf W = AUTO_STRBUF_INITIALIZER; /* The warning name is a symbol but the '-' char is allowed within */ if (SB_GetSym (B, &W, "-")) { /* Map the warning name to an IntStack that contains its state */ S = FindWarning (SB_GetConstBuf (&W)); /* Handle errors */ if (S == 0) { Error ("Pragma expects a warning name as first argument"); } } /* Deallocate the string */ SB_Done (&W); /* Done */ return S; } static int HasStr (StrBuf* B, const char* E) /* Checks if E follows in B. If so, skips it and returns true */ { unsigned Len = strlen (E); if (SB_GetLen (B) - SB_GetIndex (B) >= Len) { if (strncmp (SB_GetConstBuf (B) + SB_GetIndex (B), E, Len) == 0) { /* Found */ SB_SkipMultiple (B, Len); return 1; } } return 0; } static PushPopResult ParsePushPop (StrBuf* B) /* Check for and parse the "push" and "pop" keywords. In case of "push", a * following comma is expected and skipped. */ { StrBuf Ident = AUTO_STRBUF_INITIALIZER; PushPopResult Res = PP_NONE; /* Remember the current string index, so we can go back in case of errors */ unsigned Index = SB_GetIndex (B); /* Try to read an identifier */ if (SB_GetSym (B, &Ident, 0)) { /* Check if we have a first argument named "pop" */ if (SB_CompareStr (&Ident, "pop") == 0) { Res = PP_POP; /* Check if we have a first argument named "push" */ } else if (SB_CompareStr (&Ident, "push") == 0) { Res = PP_PUSH; /* Skip the following comma */ if (!GetComma (B)) { /* Error already flagged by GetComma */ Res = PP_ERROR; } } else { /* Unknown keyword, roll back */ SB_SetIndex (B, Index); } } /* Free the string buffer and return the result */ SB_Done (&Ident); return Res; } static void PopInt (IntStack* S) /* Pops an integer from an IntStack. Prints an error if the stack is empty */ { if (IS_GetCount (S) < 2) { Error ("Cannot pop, stack is empty"); } else { IS_Drop (S); } } static void PushInt (IntStack* S, long Val) /* Pushes an integer onto an IntStack. Prints an error if the stack is full */ { if (IS_IsFull (S)) { Error ("Cannot push: stack overflow"); } else { IS_Push (S, Val); } } static int BoolKeyword (StrBuf* Ident) /* Check if the identifier in Ident is a keyword for a boolean value. Currently * accepted are true/false/on/off. */ { if (SB_CompareStr (Ident, "true") == 0) { return 1; } if (SB_CompareStr (Ident, "on") == 0) { return 1; } if (SB_CompareStr (Ident, "false") == 0) { return 0; } if (SB_CompareStr (Ident, "off") == 0) { return 0; } /* Error */ Error ("Pragma argument must be one of `on', `off', `true' or `false'"); return 0; } /*****************************************************************************/ /* Pragma handling functions */ /*****************************************************************************/ static void StringPragma (StrBuf* B, void (*Func) (const char*)) /* Handle a pragma that expects a string parameter */ { StrBuf S = AUTO_STRBUF_INITIALIZER; /* We expect a string here */ if (GetString (B, &S)) { /* Call the given function with the string argument */ Func (SB_GetConstBuf (&S)); } /* Call the string buf destructor */ SB_Done (&S); } static void SegNamePragma (StrBuf* B, segment_t Seg) /* Handle a pragma that expects a segment name parameter */ { StrBuf S = AUTO_STRBUF_INITIALIZER; const char* Name; /* Check for the "push" or "pop" keywords */ int Push = 0; switch (ParsePushPop (B)) { case PP_NONE: break; case PP_PUSH: Push = 1; break; case PP_POP: /* Pop the old value and output it */ PopSegName (Seg); g_segname (Seg); /* Done */ goto ExitPoint; case PP_ERROR: /* Bail out */ goto ExitPoint; default: Internal ("Invalid result from ParsePushPop"); } /* A string argument must follow */ if (!GetString (B, &S)) { goto ExitPoint; } /* Get the string */ Name = SB_GetConstBuf (&S); /* Check if the name is valid */ if (ValidSegName (Name)) { /* Set the new name */ if (Push) { PushSegName (Seg, Name); } else { SetSegName (Seg, Name); } g_segname (Seg); } else { /* Segment name is invalid */ Error ("Illegal segment name: `%s'", Name); } ExitPoint: /* Call the string buf destructor */ SB_Done (&S); } static void CharMapPragma (StrBuf* B) /* Change the character map */ { long Index, C; /* Read the character index */ if (!GetNumber (B, &Index)) { return; } if (Index < 1 || Index > 255) { if (Index == 0) { /* For groepaz */ Error ("Remapping 0 is not allowed"); } else { Error ("Character index out of range"); } return; } /* Comma follows */ if (!GetComma (B)) { return; } /* Read the character code */ if (!GetNumber (B, &C)) { return; } if (C < 1 || C > 255) { if (C == 0) { /* For groepaz */ Error ("Remapping 0 is not allowed"); } else { Error ("Character code out of range"); } return; } /* Remap the character */ TgtTranslateSet ((unsigned) Index, (unsigned char) C); } static void WarnPragma (StrBuf* B) /* Enable/disable warnings */ { long Val; int Push; /* A warning name must follow */ IntStack* S = GetWarning (B); if (S == 0) { return; } /* Comma follows */ if (!GetComma (B)) { return; } /* Check for the "push" or "pop" keywords */ switch (ParsePushPop (B)) { case PP_NONE: Push = 0; break; case PP_PUSH: Push = 1; break; case PP_POP: /* Pop the old value and bail out */ PopInt (S); return; case PP_ERROR: /* Bail out */ return; default: Internal ("Invalid result from ParsePushPop"); } /* Boolean argument follows */ if (HasStr (B, "true") || HasStr (B, "on")) { Val = 1; } else if (HasStr (B, "false") || HasStr (B, "off")) { Val = 0; } else if (!SB_GetNumber (B, &Val)) { Error ("Invalid pragma argument"); return; } /* Set/push the new value */ if (Push) { PushInt (S, Val); } else { IS_Set (S, Val); } } static void FlagPragma (StrBuf* B, IntStack* Stack) /* Handle a pragma that expects a boolean paramater */ { StrBuf Ident = AUTO_STRBUF_INITIALIZER; long Val; int Push; /* Try to read an identifier */ int IsIdent = SB_GetSym (B, &Ident, 0); /* Check if we have a first argument named "pop" */ if (IsIdent && SB_CompareStr (&Ident, "pop") == 0) { PopInt (Stack); /* No other arguments allowed */ return; } /* Check if we have a first argument named "push" */ if (IsIdent && SB_CompareStr (&Ident, "push") == 0) { Push = 1; if (!GetComma (B)) { goto ExitPoint; } IsIdent = SB_GetSym (B, &Ident, 0); } else { Push = 0; } /* Boolean argument follows */ if (IsIdent) { Val = BoolKeyword (&Ident); } else if (!GetNumber (B, &Val)) { goto ExitPoint; } /* Set/push the new value */ if (Push) { PushInt (Stack, Val); } else { IS_Set (Stack, Val); } ExitPoint: /* Free the identifier */ SB_Done (&Ident); } static void IntPragma (StrBuf* B, IntStack* Stack, long Low, long High) /* Handle a pragma that expects an int paramater */ { long Val; int Push; /* Check for the "push" or "pop" keywords */ switch (ParsePushPop (B)) { case PP_NONE: Push = 0; break; case PP_PUSH: Push = 1; break; case PP_POP: /* Pop the old value and bail out */ PopInt (Stack); return; case PP_ERROR: /* Bail out */ return; default: Internal ("Invalid result from ParsePushPop"); } /* Integer argument follows */ if (!GetNumber (B, &Val)) { return; } /* Check the argument */ if (Val < Low || Val > High) { Error ("Pragma argument out of bounds (%ld-%ld)", Low, High); return; } /* Set/push the new value */ if (Push) { PushInt (Stack, Val); } else { IS_Set (Stack, Val); } } static void ParsePragma (void) /* Parse the contents of the _Pragma statement */ { pragma_t Pragma; StrBuf Ident = AUTO_STRBUF_INITIALIZER; /* Create a string buffer from the string literal */ StrBuf B = AUTO_STRBUF_INITIALIZER; SB_Append (&B, GetLiteralStrBuf (CurTok.SVal)); /* Skip the string token */ NextToken (); /* Get the pragma name from the string */ SB_SkipWhite (&B); if (!SB_GetSym (&B, &Ident, "-")) { Error ("Invalid pragma"); goto ExitPoint; } /* Search for the name */ Pragma = FindPragma (&Ident); /* Do we know this pragma? */ if (Pragma == PRAGMA_ILLEGAL) { /* According to the ANSI standard, we're not allowed to generate errors * for unknown pragmas, but warn about them if enabled (the default). */ if (IS_Get (&WarnUnknownPragma)) { Warning ("Unknown pragma `%s'", SB_GetConstBuf (&Ident)); } goto ExitPoint; } /* Check for an open paren */ SB_SkipWhite (&B); if (SB_Get (&B) != '(') { Error ("'(' expected"); goto ExitPoint; } /* Skip white space before the argument */ SB_SkipWhite (&B); /* Switch for the different pragmas */ switch (Pragma) { case PRAGMA_ALIGN: IntPragma (&B, &DataAlignment, 1, 4096); break; case PRAGMA_BSSSEG: Warning ("#pragma bssseg is obsolete, please use #pragma bss-name instead"); /* FALLTHROUGH */ case PRAGMA_BSS_NAME: SegNamePragma (&B, SEG_BSS); break; case PRAGMA_CHARMAP: CharMapPragma (&B); break; case PRAGMA_CHECKSTACK: Warning ("#pragma checkstack is obsolete, please use #pragma check-stack instead"); /* FALLTHROUGH */ case PRAGMA_CHECK_STACK: FlagPragma (&B, &CheckStack); break; case PRAGMA_CODESEG: Warning ("#pragma codeseg is obsolete, please use #pragma code-name instead"); /* FALLTHROUGH */ case PRAGMA_CODE_NAME: SegNamePragma (&B, SEG_CODE); break; case PRAGMA_CODESIZE: IntPragma (&B, &CodeSizeFactor, 10, 1000); break; case PRAGMA_DATASEG: Warning ("#pragma dataseg is obsolete, please use #pragma data-name instead"); /* FALLTHROUGH */ case PRAGMA_DATA_NAME: SegNamePragma (&B, SEG_DATA); break; case PRAGMA_LOCAL_STRINGS: FlagPragma (&B, &LocalStrings); break; case PRAGMA_OPTIMIZE: FlagPragma (&B, &Optimize); break; case PRAGMA_REGVARADDR: FlagPragma (&B, &AllowRegVarAddr); break; case PRAGMA_REGVARS: Warning ("#pragma regvars is obsolete, please use #pragma register-vars instead"); /* FALLTHROUGH */ case PRAGMA_REGISTER_VARS: FlagPragma (&B, &EnableRegVars); break; case PRAGMA_RODATASEG: Warning ("#pragma rodataseg is obsolete, please use #pragma rodata-name instead"); /* FALLTHROUGH */ case PRAGMA_RODATA_NAME: SegNamePragma (&B, SEG_RODATA); break; case PRAGMA_SIGNEDCHARS: Warning ("#pragma signedchars is obsolete, please use #pragma signed-chars instead"); /* FALLTHROUGH */ case PRAGMA_SIGNED_CHARS: FlagPragma (&B, &SignedChars); break; case PRAGMA_STATICLOCALS: Warning ("#pragma staticlocals is obsolete, please use #pragma static-locals instead"); /* FALLTHROUGH */ case PRAGMA_STATIC_LOCALS: FlagPragma (&B, &StaticLocals); break; case PRAGMA_WARN: WarnPragma (&B); break; case PRAGMA_WRITABLE_STRINGS: FlagPragma (&B, &WritableStrings); break; case PRAGMA_ZPSYM: StringPragma (&B, MakeZPSym); break; default: Internal ("Invalid pragma"); } /* Closing paren expected */ SB_SkipWhite (&B); if (SB_Get (&B) != ')') { Error ("')' expected"); goto ExitPoint; } SB_SkipWhite (&B); /* Allow an optional semicolon to be compatible with the old syntax */ if (SB_Peek (&B) == ';') { SB_Skip (&B); SB_SkipWhite (&B); } /* Make sure nothing follows */ if (SB_Peek (&B) != '\0') { Error ("Unexpected input following pragma directive"); } ExitPoint: /* Release the string buffers */ SB_Done (&B); SB_Done (&Ident); } void DoPragma (void) /* Handle pragmas. These come always in form of the new C99 _Pragma() operator. */ { /* Skip the token itself */ NextToken (); /* We expect an opening paren */ if (!ConsumeLParen ()) { return; } /* String literal */ if (CurTok.Tok != TOK_SCONST) { /* Print a diagnostic */ Error ("String literal expected"); /* Try some smart error recovery: Skip tokens until we reach the * enclosing paren, or a semicolon. */ PragmaErrorSkip (); } else { /* Parse the _Pragma statement */ ParsePragma (); } /* Closing paren needed */ ConsumeRParen (); }
859
./cc65/src/cc65/testexpr.c
/*****************************************************************************/ /* */ /* testexpr.c */ /* */ /* Test an expression and jump */ /* */ /* */ /* */ /* (C) 2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codegen.h" #include "error.h" #include "expr.h" #include "loadexpr.h" #include "scanner.h" #include "testexpr.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned Test (unsigned Label, int Invert) /* Evaluate a boolean test expression and jump depending on the result of * the test and on Invert. The function returns one of the TESTEXPR_xx codes * defined above. If the jump is always true, a warning is output. */ { ExprDesc Expr; unsigned Result; /* Read a boolean expression */ BoolExpr (hie0, &Expr); /* Check for a constant expression */ if (ED_IsConstAbs (&Expr)) { /* Result is constant, so we know the outcome */ Result = (Expr.IVal != 0); /* Constant rvalue */ if (!Invert && Expr.IVal == 0) { g_jump (Label); Warning ("Unreachable code"); } else if (Invert && Expr.IVal != 0) { g_jump (Label); } } else { /* Result is unknown */ Result = TESTEXPR_UNKNOWN; /* If the expr hasn't set condition codes, set the force-test flag */ if (!ED_IsTested (&Expr)) { ED_MarkForTest (&Expr); } /* Load the value into the primary register */ LoadExpr (CF_FORCECHAR, &Expr); /* Generate the jump */ if (Invert) { g_truejump (CF_NONE, Label); } else { g_falsejump (CF_NONE, Label); } } /* Return the result */ return Result; } unsigned TestInParens (unsigned Label, int Invert) /* Evaluate a boolean test expression in parenthesis and jump depending on * the result of the test * and on Invert. The function returns one of the * TESTEXPR_xx codes defined above. If the jump is always true, a warning is * output. */ { unsigned Result; /* Eat the parenthesis */ ConsumeLParen (); /* Do the test */ Result = Test (Label, Invert); /* Check for the closing brace */ ConsumeRParen (); /* Return the result of the expression */ return Result; }
860
./cc65/src/cc65/typecmp.c
/*****************************************************************************/ /* */ /* typecmp.c */ /* */ /* Type compare function for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 1998-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* cc65 */ #include "funcdesc.h" #include "symtab.h" #include "typecmp.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void SetResult (typecmp_t* Result, typecmp_t Val) /* Set a new result value if it is less than the existing one */ { if (Val < *Result) { /* printf ("SetResult = %d\n", Val); */ *Result = Val; } } static int ParamsHaveDefaultPromotions (const FuncDesc* F) /* Check if any of the parameters of function F has a default promotion. In * this case, the function is not compatible with an empty parameter name list * declaration. */ { /* Get the symbol table */ const SymTable* Tab = F->SymTab; /* Get the first parameter in the list */ const SymEntry* Sym = Tab->SymHead; /* Walk over all parameters */ while (Sym && (Sym->Flags & SC_PARAM)) { /* If this is an integer type, check if the promoted type is equal * to the original type. If not, we have a default promotion. */ if (IsClassInt (Sym->Type)) { if (IntPromotion (Sym->Type) != Sym->Type) { return 1; } } /* Get the pointer to the next param */ Sym = Sym->NextSym; } /* No default promotions in the parameter list */ return 0; } static int EqualFuncParams (const FuncDesc* F1, const FuncDesc* F2) /* Compare two function symbol tables regarding function parameters. Return 1 * if they are equal and 0 otherwise. */ { /* Get the symbol tables */ const SymTable* Tab1 = F1->SymTab; const SymTable* Tab2 = F2->SymTab; /* Compare the parameter lists */ const SymEntry* Sym1 = Tab1->SymHead; const SymEntry* Sym2 = Tab2->SymHead; /* Compare the fields */ while (Sym1 && (Sym1->Flags & SC_PARAM) && Sym2 && (Sym2->Flags & SC_PARAM)) { /* Get the symbol types */ Type* Type1 = Sym1->Type; Type* Type2 = Sym2->Type; /* If either of both functions is old style, apply the default * promotions to the parameter type. */ if (F1->Flags & FD_OLDSTYLE) { if (IsClassInt (Type1)) { Type1 = IntPromotion (Type1); } } if (F2->Flags & FD_OLDSTYLE) { if (IsClassInt (Type2)) { Type2 = IntPromotion (Type2); } } /* Compare this field */ if (TypeCmp (Type1, Type2) < TC_EQUAL) { /* Field types not equal */ return 0; } /* Get the pointers to the next fields */ Sym1 = Sym1->NextSym; Sym2 = Sym2->NextSym; } /* Check both pointers against NULL or a non parameter to compare the * field count */ return (Sym1 == 0 || (Sym1->Flags & SC_PARAM) == 0) && (Sym2 == 0 || (Sym2->Flags & SC_PARAM) == 0); } static int EqualSymTables (SymTable* Tab1, SymTable* Tab2) /* Compare two symbol tables. Return 1 if they are equal and 0 otherwise */ { /* Compare the parameter lists */ SymEntry* Sym1 = Tab1->SymHead; SymEntry* Sym2 = Tab2->SymHead; /* Compare the fields */ while (Sym1 && Sym2) { /* Compare the names of this field */ if (!HasAnonName (Sym1) || !HasAnonName (Sym2)) { if (strcmp (Sym1->Name, Sym2->Name) != 0) { /* Names are not identical */ return 0; } } /* Compare the types of this field */ if (TypeCmp (Sym1->Type, Sym2->Type) < TC_EQUAL) { /* Field types not equal */ return 0; } /* Get the pointers to the next fields */ Sym1 = Sym1->NextSym; Sym2 = Sym2->NextSym; } /* Check both pointers against NULL to compare the field count */ return (Sym1 == 0 && Sym2 == 0); } static void DoCompare (const Type* lhs, const Type* rhs, typecmp_t* Result) /* Recursively compare two types. */ { unsigned Indirections; unsigned ElementCount; SymEntry* Sym1; SymEntry* Sym2; SymTable* Tab1; SymTable* Tab2; FuncDesc* F1; FuncDesc* F2; /* Initialize stuff */ Indirections = 0; ElementCount = 0; /* Compare two types. Determine, where they differ */ while (lhs->C != T_END) { TypeCode LeftType, RightType; TypeCode LeftSign, RightSign; TypeCode LeftQual, RightQual; long LeftCount, RightCount; /* Check if the end of the type string is reached */ if (rhs->C == T_END) { /* End of comparison reached */ return; } /* Get the raw left and right types, signs and qualifiers */ LeftType = GetType (lhs); RightType = GetType (rhs); LeftSign = GetSignedness (lhs); RightSign = GetSignedness (rhs); LeftQual = GetQualifier (lhs); RightQual = GetQualifier (rhs); /* If the left type is a pointer and the right is an array, both * are compatible. */ if (LeftType == T_TYPE_PTR && RightType == T_TYPE_ARRAY) { RightType = T_TYPE_PTR; } /* If the raw types are not identical, the types are incompatible */ if (LeftType != RightType) { SetResult (Result, TC_INCOMPATIBLE); return; } /* On indirection level zero, a qualifier or sign difference is * accepted. The types are no longer equal, but compatible. */ if (LeftSign != RightSign) { if (ElementCount == 0) { SetResult (Result, TC_SIGN_DIFF); } else { SetResult (Result, TC_INCOMPATIBLE); return; } } if (LeftQual != RightQual) { /* On the first indirection level, different qualifiers mean * that the types are still compatible. On the second level, * this is a (maybe minor) error, so we create a special * return code, since a qualifier is dropped from a pointer. * Starting from the next level, the types are incompatible * if the qualifiers differ. */ /* printf ("Ind = %d %06X != %06X\n", Indirections, LeftQual, RightQual); */ switch (Indirections) { case 0: SetResult (Result, TC_STRICT_COMPATIBLE); break; case 1: /* A non const value on the right is compatible to a * const one to the left, same for volatile. */ if ((LeftQual & T_QUAL_CONST) < (RightQual & T_QUAL_CONST) || (LeftQual & T_QUAL_VOLATILE) < (RightQual & T_QUAL_VOLATILE)) { SetResult (Result, TC_QUAL_DIFF); } else { SetResult (Result, TC_STRICT_COMPATIBLE); } break; default: SetResult (Result, TC_INCOMPATIBLE); return; } } /* Check for special type elements */ switch (LeftType) { case T_TYPE_PTR: ++Indirections; break; case T_TYPE_FUNC: /* Compare the function descriptors */ F1 = GetFuncDesc (lhs); F2 = GetFuncDesc (rhs); /* If one of both functions has an empty parameter list (which * does also mean, it is not a function definition, because the * flag is reset in this case), it is considered equal to any * other definition, provided that the other has no default * promotions in the parameter list. If none of both parameter * lists is empty, we have to check the parameter lists and * other attributes. */ if (F1->Flags & FD_EMPTY) { if ((F2->Flags & FD_EMPTY) == 0) { if (ParamsHaveDefaultPromotions (F2)) { /* Flags differ */ SetResult (Result, TC_INCOMPATIBLE); return; } } } else if (F2->Flags & FD_EMPTY) { if (ParamsHaveDefaultPromotions (F1)) { /* Flags differ */ SetResult (Result, TC_INCOMPATIBLE); return; } } else { /* Check the remaining flags */ if ((F1->Flags & ~FD_IGNORE) != (F2->Flags & ~FD_IGNORE)) { /* Flags differ */ SetResult (Result, TC_INCOMPATIBLE); return; } /* Compare the parameter lists */ if (EqualFuncParams (F1, F2) == 0) { /* Parameter list is not identical */ SetResult (Result, TC_INCOMPATIBLE); return; } } /* Keep on and compare the return type */ break; case T_TYPE_ARRAY: /* Check member count */ LeftCount = GetElementCount (lhs); RightCount = GetElementCount (rhs); if (LeftCount != UNSPECIFIED && RightCount != UNSPECIFIED && LeftCount != RightCount) { /* Member count given but different */ SetResult (Result, TC_INCOMPATIBLE); return; } break; case T_TYPE_STRUCT: case T_TYPE_UNION: /* Compare the fields recursively. To do that, we fetch the * pointer to the struct definition from the type, and compare * the fields. */ Sym1 = GetSymEntry (lhs); Sym2 = GetSymEntry (rhs); /* If one symbol has a name, the names must be identical */ if (!HasAnonName (Sym1) || !HasAnonName (Sym2)) { if (strcmp (Sym1->Name, Sym2->Name) != 0) { /* Names are not identical */ SetResult (Result, TC_INCOMPATIBLE); return; } } /* Get the field tables from the struct entry */ Tab1 = Sym1->V.S.SymTab; Tab2 = Sym2->V.S.SymTab; /* One or both structs may be forward definitions. In this case, * the symbol tables are both non existant. Assume that the * structs are equal in this case. */ if (Tab1 != 0 && Tab2 != 0) { if (EqualSymTables (Tab1, Tab2) == 0) { /* Field lists are not equal */ SetResult (Result, TC_INCOMPATIBLE); return; } } /* Structs are equal */ break; } /* Next type string element */ ++lhs; ++rhs; ++ElementCount; } /* Check if end of rhs reached */ if (rhs->C == T_END) { SetResult (Result, TC_EQUAL); } else { SetResult (Result, TC_INCOMPATIBLE); } } typecmp_t TypeCmp (const Type* lhs, const Type* rhs) /* Compare two types and return the result */ { /* Assume the types are identical */ typecmp_t Result = TC_IDENTICAL; #if 0 printf ("Left : "); PrintRawType (stdout, lhs); printf ("Right: "); PrintRawType (stdout, rhs); #endif /* Recursively compare the types if they aren't identical */ if (rhs != lhs) { DoCompare (lhs, rhs, &Result); } /* Return the result */ return Result; }
861
./cc65/src/cc65/declattr.c
/*****************************************************************************/ /* */ /* declattr.c */ /* */ /* Declaration attributes */ /* */ /* */ /* */ /* (C) 1998-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xmalloc.h" /* cc65 */ #include "declare.h" #include "declattr.h" #include "error.h" #include "scanner.h" #include "symtab.h" #include "typecmp.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Forwards for attribute handlers */ static void NoReturnAttr (Declaration* D); static void UnusedAttr (Declaration* D); /* Attribute table */ typedef struct AttrDesc AttrDesc; struct AttrDesc { const char Name[15]; void (*Handler) (Declaration*); }; static const AttrDesc AttrTable [] = { { "__noreturn__", NoReturnAttr }, { "__unused__", UnusedAttr }, { "noreturn", NoReturnAttr }, { "unused", UnusedAttr }, }; /*****************************************************************************/ /* Struct DeclAttr */ /*****************************************************************************/ static DeclAttr* NewDeclAttr (DeclAttrType AttrType) /* Create a new DeclAttr struct and return it */ { /* Allocate memory */ DeclAttr* A = xmalloc (sizeof (DeclAttr)); /* Initialize the fields */ A->AttrType = AttrType; /* Return the new struct */ return A; } /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static const AttrDesc* FindAttribute (const char* Attr) /* Search the attribute and return the corresponding attribute descriptor. * Return NULL if the attribute name is not known. */ { unsigned A; /* For now do a linear search */ for (A = 0; A < sizeof (AttrTable) / sizeof (AttrTable[0]); ++A) { if (strcmp (Attr, AttrTable[A].Name) == 0) { /* Found */ return AttrTable + A; } } /* Not found */ return 0; } static void ErrorSkip (void) { /* List of tokens to skip */ static const token_t SkipList[] = { TOK_RPAREN, TOK_SEMI }; /* Skip until closing brace or semicolon */ SkipTokens (SkipList, sizeof (SkipList) / sizeof (SkipList[0])); /* If we have a closing brace, read it, otherwise bail out */ if (CurTok.Tok == TOK_RPAREN) { /* Read the two closing braces */ ConsumeRParen (); ConsumeRParen (); } } static void AddAttr (Declaration* D, DeclAttr* A) /* Add an attribute to a declaration */ { /* Allocate the list if necessary, the add the attribute */ if (D->Attributes == 0) { D->Attributes = NewCollection (); } CollAppend (D->Attributes, A); } /*****************************************************************************/ /* Attribute handling code */ /*****************************************************************************/ static void NoReturnAttr (Declaration* D) /* Parse the "noreturn" attribute */ { /* Add the noreturn attribute */ AddAttr (D, NewDeclAttr (atNoReturn)); } static void UnusedAttr (Declaration* D) /* Parse the "unused" attribute */ { /* Add the noreturn attribute */ AddAttr (D, NewDeclAttr (atUnused)); } void ParseAttribute (Declaration* D) /* Parse an additional __attribute__ modifier */ { /* Do we have an attribute? */ if (CurTok.Tok != TOK_ATTRIBUTE) { /* No attribute, bail out */ return; } /* Skip the attribute token */ NextToken (); /* Expect two(!) open braces */ ConsumeLParen (); ConsumeLParen (); /* Read a list of attributes */ while (1) { ident AttrName; const AttrDesc* Attr = 0; /* Identifier follows */ if (CurTok.Tok != TOK_IDENT) { /* No attribute name */ Error ("Attribute name expected"); /* Skip until end of attribute */ ErrorSkip (); /* Bail out */ return; } /* Map the attribute name to its id, then skip the identifier */ strcpy (AttrName, CurTok.Ident); Attr = FindAttribute (AttrName); NextToken (); /* Did we find a valid attribute? */ if (Attr) { /* Call the handler */ Attr->Handler (D); } else { /* Attribute not known, maybe typo */ Error ("Illegal attribute: `%s'", AttrName); /* Skip until end of attribute */ ErrorSkip (); /* Bail out */ return; } /* If a comma follows, there's a next attribute. Otherwise this is the * end of the attribute list. */ if (CurTok.Tok != TOK_COMMA) { break; } NextToken (); } /* The declaration is terminated with two closing braces */ ConsumeRParen (); ConsumeRParen (); }
862
./cc65/src/cc65/hexval.c
/*****************************************************************************/ /* */ /* hexval.c */ /* */ /* Convert hex digits to numeric values */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "chartype.h" /* cc65 */ #include "error.h" #include "hexval.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned HexVal (int C) /* Convert a hex digit into a value. The function will emit an error for * invalid hex digits. */ { if (!IsXDigit (C)) { Error ("Invalid hexadecimal digit: `%c'", C); } if (IsDigit (C)) { return C - '0'; } else { return toupper (C) - 'A' + 10; } }
863
./cc65/src/cc65/stdnames.c
/*****************************************************************************/ /* */ /* stdnames.c */ /* */ /* Assembler names for standard functions in the library */ /* */ /* */ /* */ /* (C) 2004-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "stdnames.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ const char Func__bzero[] = "_bzero"; /* Asm name of "_bzero" */ const char Func_memcpy[] = "memcpy"; /* Asm name of "memcpy" */ const char Func_memset[] = "memset"; /* Asm name of "memset" */ const char Func_strcmp[] = "strcmp"; /* Asm name of "strcmp" */ const char Func_strcpy[] = "strcpy"; /* Asm name of "strcpy" */ const char Func_strlen[] = "strlen"; /* Asm name of "strlen" */
864
./cc65/src/cc65/copttest.c
/*****************************************************************************/ /* */ /* copttest.c */ /* */ /* Optimize test sequences */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "copttest.h" /*****************************************************************************/ /* Optimize tests */ /*****************************************************************************/ unsigned OptTest1 (CodeSeg* S) /* Given a sequence * * stx xxx * ora xxx * beq/bne ... * * If X is zero, the sequence may be changed to * * cmp #$00 * beq/bne ... * * which may be optimized further by another step. * * If A is zero, the sequence may be changed to * * txa * beq/bne ... * */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check if it's the sequence we're searching for */ if (L[0]->OPC == OP65_STX && CS_GetEntries (S, L+1, I+1, 2) && !CE_HasLabel (L[1]) && L[1]->OPC == OP65_ORA && strcmp (L[0]->Arg, L[1]->Arg) == 0 && !CE_HasLabel (L[2]) && (L[2]->Info & OF_ZBRA) != 0) { /* Check if X is zero */ if (L[0]->RI->In.RegX == 0) { /* Insert the compare */ CodeEntry* N = NewCodeEntry (OP65_CMP, AM65_IMM, "$00", 0, L[0]->LI); CS_InsertEntry (S, N, I+2); /* Remove the two other insns */ CS_DelEntry (S, I+1); CS_DelEntry (S, I); /* We had changes */ ++Changes; /* Check if A is zero */ } else if (L[1]->RI->In.RegA == 0) { /* Insert the txa */ CodeEntry* N = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, N, I+2); /* Remove the two other insns */ CS_DelEntry (S, I+1); CS_DelEntry (S, I); /* We had changes */ ++Changes; } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptTest2 (CodeSeg* S) /* Search for an inc/dec operation followed by a load and a conditional * branch based on the flags from the load. Remove the load if the insn * isn't used later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[3]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check if it's the sequence we're searching for */ if ((L[0]->OPC == OP65_INC || L[0]->OPC == OP65_DEC) && CS_GetEntries (S, L+1, I+1, 2) && !CE_HasLabel (L[1]) && (L[1]->Info & OF_LOAD) != 0 && (L[2]->Info & OF_FBRA) != 0 && L[1]->AM == L[0]->AM && strcmp (L[0]->Arg, L[1]->Arg) == 0 && (GetRegInfo (S, I+2, L[1]->Chg) & L[1]->Chg) == 0) { /* Remove the load */ CS_DelEntry (S, I+1); ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
865
./cc65/src/cc65/assignment.c
/*****************************************************************************/ /* */ /* assignment.c */ /* */ /* Parse assignments */ /* */ /* */ /* */ /* (C) 2002-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "asmcode.h" #include "assignment.h" #include "codegen.h" #include "datatype.h" #include "error.h" #include "expr.h" #include "loadexpr.h" #include "scanner.h" #include "stdnames.h" #include "typecmp.h" #include "typeconv.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Assignment (ExprDesc* Expr) /* Parse an assignment */ { ExprDesc Expr2; Type* ltype = Expr->Type; /* We must have an lvalue for an assignment */ if (ED_IsRVal (Expr)) { Error ("Invalid lvalue in assignment"); } /* Check for assignment to const */ if (IsQualConst (ltype)) { Error ("Assignment to const"); } /* Skip the '=' token */ NextToken (); /* cc65 does not have full support for handling structs by value. Since * assigning structs is one of the more useful operations from this * family, allow it here. */ if (IsClassStruct (ltype)) { /* Get the size of the left hand side. */ unsigned Size = SizeOf (ltype); /* If the size is that of a basic type (char, int, long), we will copy * the struct using the primary register, otherwise we use memcpy. In * the former case, push the address only if really needed. */ int UseReg = 1; Type* stype; switch (Size) { case SIZEOF_CHAR: stype = type_uchar; break; case SIZEOF_INT: stype = type_uint; break; case SIZEOF_LONG: stype = type_ulong; break; default: stype = ltype; UseReg = 0; break; } if (UseReg) { PushAddr (Expr); } else { ED_MakeRVal (Expr); LoadExpr (CF_NONE, Expr); g_push (CF_PTR | CF_UNSIGNED, 0); } /* Get the expression on the right of the '=' into the primary */ hie1 (&Expr2); /* Check for equality of the structs */ if (TypeCmp (ltype, Expr2.Type) < TC_STRICT_COMPATIBLE) { Error ("Incompatible types"); } /* Check if the right hand side is an lvalue */ if (ED_IsLVal (&Expr2)) { /* We have an lvalue. Do we copy using the primary? */ if (UseReg) { /* Just use the replacement type */ Expr2.Type = stype; /* Load the value into the primary */ LoadExpr (CF_FORCECHAR, &Expr2); /* Store it into the new location */ Store (Expr, stype); } else { /* We will use memcpy. Push the address of the rhs */ ED_MakeRVal (&Expr2); LoadExpr (CF_NONE, &Expr2); /* Push the address (or whatever is in ax in case of errors) */ g_push (CF_PTR | CF_UNSIGNED, 0); /* Load the size of the struct into the primary */ g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, CheckedSizeOf (ltype), 0); /* Call the memcpy function */ g_call (CF_FIXARGC, Func_memcpy, 4); } } else { /* We have an rvalue. This can only happen if a function returns * a struct, since there is no other way to generate an expression * that as a struct as an rvalue result. We allow only 1, 2, and 4 * byte sized structs and do direct assignment. */ if (UseReg) { /* Do the store */ Store (Expr, stype); } else { /* Print a diagnostic */ Error ("Structs of this size are not supported"); /* Adjust the stack so we won't run in an internal error later */ pop (CF_PTR); } } } else if (ED_IsBitField (Expr)) { CodeMark AndPos; CodeMark PushPos; unsigned Mask; unsigned Flags; /* If the bit-field fits within one byte, do the following operations * with bytes. */ if (Expr->BitOffs / CHAR_BITS == (Expr->BitOffs + Expr->BitWidth - 1) / CHAR_BITS) { Expr->Type = type_uchar; } /* Determine code generator flags */ Flags = TypeOf (Expr->Type); /* Assignment to a bit field. Get the address on stack for the store. */ PushAddr (Expr); /* Load the value from the location */ Expr->Flags &= ~E_BITFIELD; LoadExpr (CF_NONE, Expr); /* Mask unwanted bits */ Mask = (0x0001U << Expr->BitWidth) - 1U; GetCodePos (&AndPos); g_and (Flags | CF_CONST, ~(Mask << Expr->BitOffs)); /* Push it on stack */ GetCodePos (&PushPos); g_push (Flags, 0); /* Read the expression on the right side of the '=' */ MarkedExprWithCheck (hie1, &Expr2); /* Do type conversion if necessary. Beware: Do not use char type * here! */ TypeConversion (&Expr2, ltype); /* Special treatment if the value is constant. */ /* Beware: Expr2 may contain side effects, so there must not be * code generated for Expr2. */ if (ED_IsConstAbsInt (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) { /* Get the value and apply the mask */ unsigned Val = (unsigned) (Expr2.IVal & Mask); /* Since we will do the OR with a constant, we can remove the push */ RemoveCode (&PushPos); /* If the value is equal to the mask now, all bits are one, and we * can remove the mask operation from above. */ if (Val == Mask) { RemoveCode (&AndPos); } /* Generate the or operation */ g_or (Flags | CF_CONST, Val << Expr->BitOffs); } else { /* If necessary, load the value into the primary register */ LoadExpr (CF_NONE, &Expr2); /* Apply the mask */ g_and (Flags | CF_CONST, Mask); /* Shift it into the right position */ g_asl (Flags | CF_CONST, Expr->BitOffs); /* Or both values */ g_or (Flags, 0); } /* Generate a store instruction */ Store (Expr, 0); /* Restore the expression type */ Expr->Type = ltype; } else { /* Get the address on stack if needed */ PushAddr (Expr); /* Read the expression on the right side of the '=' */ hie1 (&Expr2); /* Do type conversion if necessary */ TypeConversion (&Expr2, ltype); /* If necessary, load the value into the primary register */ LoadExpr (CF_NONE, &Expr2); /* Generate a store instruction */ Store (Expr, 0); } /* Value is still in primary and not an lvalue */ ED_MakeRValExpr (Expr); }
866
./cc65/src/cc65/incpath.c
/*****************************************************************************/ /* */ /* incpath.c */ /* */ /* Include path handling for cc65 */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "incpath.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ SearchPath* SysIncSearchPath; /* System include path */ SearchPath* UsrIncSearchPath; /* User include path */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void InitIncludePaths (void) /* Initialize the include path search list */ { /* Create the search path lists */ SysIncSearchPath = NewSearchPath (); UsrIncSearchPath = NewSearchPath (); } void FinishIncludePaths (void) /* Finish creating the include path search lists. */ { /* Add specific paths from the environment */ AddSearchPathFromEnv (SysIncSearchPath, "CC65_INC"); AddSearchPathFromEnv (UsrIncSearchPath, "CC65_INC"); /* Add paths relative to a main directory defined in an env. var. */ AddSubSearchPathFromEnv (SysIncSearchPath, "CC65_HOME", "include"); /* Add some compiled-in search paths if defined at compile time. */ #ifdef CC65_INC AddSearchPath (SysIncSearchPath, STRINGIZE (CC65_INC)); #endif /* Add paths relative to the parent directory of the Windows binary. */ AddSubSearchPathFromWinBin (SysIncSearchPath, "include"); }
867
./cc65/src/cc65/preproc.c
/*****************************************************************************/ /* */ /* preproc.c */ /* */ /* cc65 preprocessor */ /* */ /* */ /* */ /* (C) 1998-2010, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> /* common */ #include "chartype.h" #include "check.h" #include "inline.h" #include "print.h" #include "xmalloc.h" /* cc65 */ #include "codegen.h" #include "error.h" #include "expr.h" #include "global.h" #include "ident.h" #include "incpath.h" #include "input.h" #include "lineinfo.h" #include "macrotab.h" #include "preproc.h" #include "scanner.h" #include "standard.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Set when the preprocessor calls expr() recursively */ unsigned char Preprocessing = 0; /* Management data for #if */ #define MAX_IFS 64 #define IFCOND_NONE 0x00U #define IFCOND_SKIP 0x01U #define IFCOND_ELSE 0x02U #define IFCOND_NEEDTERM 0x04U static unsigned char IfStack[MAX_IFS]; static int IfIndex = -1; /* Buffer for macro expansion */ static StrBuf* MLine; /* Structure used when expanding macros */ typedef struct MacroExp MacroExp; struct MacroExp { Collection ActualArgs; /* Actual arguments */ StrBuf Replacement; /* Replacement with arguments substituted */ Macro* M; /* The macro we're handling */ }; /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static unsigned Pass1 (StrBuf* Source, StrBuf* Target); /* Preprocessor pass 1. Remove whitespace. Handle old and new style comments * and the "defined" operator. */ static void MacroReplacement (StrBuf* Source, StrBuf* Target); /* Perform macro replacement. */ /*****************************************************************************/ /* Low level preprocessor token handling */ /*****************************************************************************/ /* Types of preprocessor tokens */ typedef enum { PP_ILLEGAL = -1, PP_DEFINE, PP_ELIF, PP_ELSE, PP_ENDIF, PP_ERROR, PP_IF, PP_IFDEF, PP_IFNDEF, PP_INCLUDE, PP_LINE, PP_PRAGMA, PP_UNDEF, PP_WARNING, } pptoken_t; /* Preprocessor keyword to token mapping table */ static const struct PPToken { const char* Key; /* Keyword */ pptoken_t Tok; /* Token */ } PPTokens[] = { { "define", PP_DEFINE }, { "elif", PP_ELIF }, { "else", PP_ELSE }, { "endif", PP_ENDIF }, { "error", PP_ERROR }, { "if", PP_IF }, { "ifdef", PP_IFDEF }, { "ifndef", PP_IFNDEF }, { "include", PP_INCLUDE }, { "line", PP_LINE }, { "pragma", PP_PRAGMA }, { "undef", PP_UNDEF }, { "warning", PP_WARNING }, }; /* Number of preprocessor tokens */ #define PPTOKEN_COUNT (sizeof(PPTokens) / sizeof(PPTokens[0])) static int CmpToken (const void* Key, const void* Elem) /* Compare function for bsearch */ { return strcmp ((const char*) Key, ((const struct PPToken*) Elem)->Key); } static pptoken_t FindPPToken (const char* Ident) /* Find a preprocessor token and return it. Return PP_ILLEGAL if the identifier * is not a valid preprocessor token. */ { struct PPToken* P; P = bsearch (Ident, PPTokens, PPTOKEN_COUNT, sizeof (PPTokens[0]), CmpToken); return P? P->Tok : PP_ILLEGAL; } /*****************************************************************************/ /* struct MacroExp */ /*****************************************************************************/ static MacroExp* InitMacroExp (MacroExp* E, Macro* M) /* Initialize a MacroExp structure */ { InitCollection (&E->ActualArgs); SB_Init (&E->Replacement); E->M = M; return E; } static void DoneMacroExp (MacroExp* E) /* Cleanup after use of a MacroExp structure */ { unsigned I; /* Delete the list with actual arguments */ for (I = 0; I < CollCount (&E->ActualArgs); ++I) { FreeStrBuf (CollAtUnchecked (&E->ActualArgs, I)); } DoneCollection (&E->ActualArgs); SB_Done (&E->Replacement); } static void ME_AppendActual (MacroExp* E, StrBuf* Arg) /* Add a copy of Arg to the list of actual macro arguments. * NOTE: This function will clear Arg! */ { /* Create a new string buffer */ StrBuf* A = NewStrBuf (); /* Move the contents of Arg to A */ SB_Move (A, Arg); /* Add A to the actual arguments */ CollAppend (&E->ActualArgs, A); } static StrBuf* ME_GetActual (MacroExp* E, unsigned Index) /* Return an actual macro argument with the given index */ { return CollAt (&E->ActualArgs, Index); } static int ME_ArgIsVariadic (const MacroExp* E) /* Return true if the next actual argument we will add is a variadic one */ { return (E->M->Variadic && E->M->ArgCount == (int) CollCount (&E->ActualArgs) + 1); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void Stringize (StrBuf* Source, StrBuf* Target) /* Stringize the given string: Add double quotes at start and end and preceed * each occurance of " and \ by a backslash. */ { char C; /* Add a starting quote */ SB_AppendChar (Target, '\"'); /* Replace any characters inside the string may not be part of a string * unescaped. */ while ((C = SB_Get (Source)) != '\0') { switch (C) { case '\"': case '\\': SB_AppendChar (Target, '\\'); /* FALLTHROUGH */ default: SB_AppendChar (Target, C); break; } } /* Add the closing quote */ SB_AppendChar (Target, '\"'); } static void OldStyleComment (void) /* Remove an old style C comment from line. */ { /* Remember the current line number, so we can output better error * messages if the comment is not terminated in the current file. */ unsigned StartingLine = GetCurrentLine(); /* Skip the start of comment chars */ NextChar (); NextChar (); /* Skip the comment */ while (CurC != '*' || NextC != '/') { if (CurC == '\0') { if (NextLine () == 0) { PPError ("End-of-file reached in comment starting at line %u", StartingLine); return; } } else { if (CurC == '/' && NextC == '*') { PPWarning ("`/*' found inside a comment"); } NextChar (); } } /* Skip the end of comment chars */ NextChar (); NextChar (); } static void NewStyleComment (void) /* Remove a new style C comment from line. */ { /* Beware: Because line continuation chars are handled when reading * lines, we may only skip til the end of the source line, which * may not be the same as the end of the input line. The end of the * source line is denoted by a lf (\n) character. */ do { NextChar (); } while (CurC != '\n' && CurC != '\0'); if (CurC == '\n') { NextChar (); } } static int SkipWhitespace (int SkipLines) /* Skip white space in the input stream. Do also skip newlines if SkipLines * is true. Return zero if nothing was skipped, otherwise return a * value != zero. */ { int Skipped = 0; while (1) { if (IsSpace (CurC)) { NextChar (); Skipped = 1; } else if (CurC == '\0' && SkipLines) { /* End of line, read next */ if (NextLine () != 0) { Skipped = 1; } else { /* End of input */ break; } } else { /* No more white space */ break; } } return Skipped; } static void CopyQuotedString (StrBuf* Target) /* Copy a single or double quoted string from the input to Target. */ { /* Remember the quote character, copy it to the target buffer and skip it */ char Quote = CurC; SB_AppendChar (Target, CurC); NextChar (); /* Copy the characters inside the string */ while (CurC != '\0' && CurC != Quote) { /* Keep an escaped char */ if (CurC == '\\') { SB_AppendChar (Target, CurC); NextChar (); } /* Copy the character */ SB_AppendChar (Target, CurC); NextChar (); } /* If we had a terminating quote, copy it */ if (CurC != '\0') { SB_AppendChar (Target, CurC); NextChar (); } } /*****************************************************************************/ /* Macro stuff */ /*****************************************************************************/ static int MacName (char* Ident) /* Get a macro symbol name into Ident. If we have an error, print a * diagnostic message and clear the line. */ { if (IsSym (Ident) == 0) { PPError ("Identifier expected"); ClearLine (); return 0; } else { return 1; } } static void ReadMacroArgs (MacroExp* E) /* Identify the arguments to a macro call */ { unsigned Parens; /* Number of open parenthesis */ StrBuf Arg = STATIC_STRBUF_INITIALIZER; /* Read the actual macro arguments */ Parens = 0; while (1) { if (CurC == '(') { /* Nested parenthesis */ SB_AppendChar (&Arg, CurC); NextChar (); ++Parens; } else if (IsQuote (CurC)) { /* Quoted string - just copy */ CopyQuotedString (&Arg); } else if (CurC == ',' || CurC == ')') { if (Parens) { /* Comma or right paren inside nested parenthesis */ if (CurC == ')') { --Parens; } SB_AppendChar (&Arg, CurC); NextChar (); } else if (CurC == ',' && ME_ArgIsVariadic (E)) { /* It's a comma, but we're inside a variadic macro argument, so * just copy it and proceed. */ SB_AppendChar (&Arg, CurC); NextChar (); } else { /* End of actual argument. Remove whitespace from the end. */ while (IsSpace (SB_LookAtLast (&Arg))) { SB_Drop (&Arg, 1); } /* If this is not the single empty argument for a macro with * an empty argument list, remember it. */ if (CurC != ')' || SB_NotEmpty (&Arg) || E->M->ArgCount > 0) { ME_AppendActual (E, &Arg); } /* Check for end of macro param list */ if (CurC == ')') { NextChar (); break; } /* Start the next param */ NextChar (); SB_Clear (&Arg); } } else if (SkipWhitespace (1)) { /* Squeeze runs of blanks within an arg */ if (SB_NotEmpty (&Arg)) { SB_AppendChar (&Arg, ' '); } } else if (CurC == '/' && NextC == '*') { if (SB_NotEmpty (&Arg)) { SB_AppendChar (&Arg, ' '); } OldStyleComment (); } else if (IS_Get (&Standard) >= STD_C99 && CurC == '/' && NextC == '/') { if (SB_NotEmpty (&Arg)) { SB_AppendChar (&Arg, ' '); } NewStyleComment (); } else if (CurC == '\0') { /* End of input inside macro argument list */ PPError ("Unterminated argument list invoking macro `%s'", E->M->Name); ClearLine (); break; } else { /* Just copy the character */ SB_AppendChar (&Arg, CurC); NextChar (); } } /* Deallocate string buf resources */ SB_Done (&Arg); } static void MacroArgSubst (MacroExp* E) /* Argument substitution according to ISO/IEC 9899:1999 (E), 6.10.3.1ff */ { ident Ident; int ArgIdx; StrBuf* OldSource; StrBuf* Arg; int HaveSpace; /* Remember the current input and switch to the macro replacement. */ int OldIndex = SB_GetIndex (&E->M->Replacement); SB_Reset (&E->M->Replacement); OldSource = InitLine (&E->M->Replacement); /* Argument handling loop */ while (CurC != '\0') { /* If we have an identifier, check if it's a macro */ if (IsSym (Ident)) { /* Check if it's a macro argument */ if ((ArgIdx = FindMacroArg (E->M, Ident)) >= 0) { /* A macro argument. Get the corresponding actual argument. */ Arg = ME_GetActual (E, ArgIdx); /* Copy any following whitespace */ HaveSpace = SkipWhitespace (0); /* If a ## operator follows, we have to insert the actual * argument as is, otherwise it must be macro replaced. */ if (CurC == '#' && NextC == '#') { /* ### Add placemarker if necessary */ SB_Append (&E->Replacement, Arg); } else { /* Replace the formal argument by a macro replaced copy * of the actual. */ SB_Reset (Arg); MacroReplacement (Arg, &E->Replacement); /* If we skipped whitespace before, re-add it now */ if (HaveSpace) { SB_AppendChar (&E->Replacement, ' '); } } } else { /* An identifier, keep it */ SB_AppendStr (&E->Replacement, Ident); } } else if (CurC == '#' && NextC == '#') { /* ## operator. */ NextChar (); NextChar (); SkipWhitespace (0); /* Since we need to concatenate the token sequences, remove * any whitespace that was added to target, since it must come * from the input. */ while (IsSpace (SB_LookAtLast (&E->Replacement))) { SB_Drop (&E->Replacement, 1); } /* If the next token is an identifier which is a macro argument, * replace it, otherwise do nothing. */ if (IsSym (Ident)) { /* Check if it's a macro argument */ if ((ArgIdx = FindMacroArg (E->M, Ident)) >= 0) { /* Get the corresponding actual argument and add it. */ SB_Append (&E->Replacement, ME_GetActual (E, ArgIdx)); } else { /* Just an ordinary identifier - add as is */ SB_AppendStr (&E->Replacement, Ident); } } } else if (CurC == '#' && E->M->ArgCount >= 0) { /* A # operator within a macro expansion of a function like * macro. Read the following identifier and check if it's a * macro parameter. */ NextChar (); SkipWhitespace (0); if (!IsSym (Ident) || (ArgIdx = FindMacroArg (E->M, Ident)) < 0) { PPError ("`#' is not followed by a macro parameter"); } else { /* Make a valid string from Replacement */ Arg = ME_GetActual (E, ArgIdx); SB_Reset (Arg); Stringize (Arg, &E->Replacement); } } else if (IsQuote (CurC)) { CopyQuotedString (&E->Replacement); } else { SB_AppendChar (&E->Replacement, CurC); NextChar (); } } #if 0 /* Remove whitespace from the end of the line */ while (IsSpace (SB_LookAtLast (&E->Replacement))) { SB_Drop (&E->Replacement, 1); } #endif /* Switch back the input */ InitLine (OldSource); SB_SetIndex (&E->M->Replacement, OldIndex); } static void MacroCall (StrBuf* Target, Macro* M) /* Process a function like macro */ { MacroExp E; /* Eat the left paren */ NextChar (); /* Initialize our MacroExp structure */ InitMacroExp (&E, M); /* Read the actual macro arguments */ ReadMacroArgs (&E); /* Compare formal and actual argument count */ if (CollCount (&E.ActualArgs) != (unsigned) M->ArgCount) { StrBuf Arg = STATIC_STRBUF_INITIALIZER; /* Argument count mismatch */ PPError ("Macro argument count mismatch"); /* Be sure to make enough empty arguments available */ while (CollCount (&E.ActualArgs) < (unsigned) M->ArgCount) { ME_AppendActual (&E, &Arg); } } /* Replace macro arguments handling the # and ## operators */ MacroArgSubst (&E); /* Do macro replacement on the macro that already has the parameters * substituted. */ M->Expanding = 1; MacroReplacement (&E.Replacement, Target); M->Expanding = 0; /* Free memory allocated for the macro expansion structure */ DoneMacroExp (&E); } static void ExpandMacro (StrBuf* Target, Macro* M) /* Expand a macro into Target */ { #if 0 static unsigned V = 0; printf ("Expanding %s(%u)\n", M->Name, ++V); #endif /* Check if this is a function like macro */ if (M->ArgCount >= 0) { int Whitespace = SkipWhitespace (1); if (CurC != '(') { /* Function like macro but no parameter list */ SB_AppendStr (Target, M->Name); if (Whitespace) { SB_AppendChar (Target, ' '); } } else { /* Function like macro */ MacroCall (Target, M); } } else { MacroExp E; InitMacroExp (&E, M); /* Handle # and ## operators for object like macros */ MacroArgSubst (&E); /* Do macro replacement on the macro that already has the parameters * substituted. */ M->Expanding = 1; MacroReplacement (&E.Replacement, Target); M->Expanding = 0; /* Free memory allocated for the macro expansion structure */ DoneMacroExp (&E); } #if 0 printf ("Done with %s(%u)\n", M->Name, V--); #endif } static void DefineMacro (void) /* Handle a macro definition. */ { ident Ident; Macro* M; Macro* Existing; int C89; /* Read the macro name */ SkipWhitespace (0); if (!MacName (Ident)) { return; } /* Remember if we're in C89 mode */ C89 = (IS_Get (&Standard) == STD_C89); /* Get an existing macro definition with this name */ Existing = FindMacro (Ident); /* Create a new macro definition */ M = NewMacro (Ident); /* Check if this is a function like macro */ if (CurC == '(') { /* Skip the left paren */ NextChar (); /* Set the marker that this is a function like macro */ M->ArgCount = 0; /* Read the formal parameter list */ while (1) { /* Skip white space and check for end of parameter list */ SkipWhitespace (0); if (CurC == ')') { break; } /* The next token must be either an identifier, or - if not in * C89 mode - the ellipsis. */ if (!C89 && CurC == '.') { /* Ellipsis */ NextChar (); if (CurC != '.' || NextC != '.') { PPError ("`...' expected"); ClearLine (); return; } NextChar (); NextChar (); /* Remember that the macro is variadic and use __VA_ARGS__ as * the argument name. */ AddMacroArg (M, "__VA_ARGS__"); M->Variadic = 1; } else { /* Must be macro argument name */ if (MacName (Ident) == 0) { return; } /* __VA_ARGS__ is only allowed in C89 mode */ if (!C89 && strcmp (Ident, "__VA_ARGS__") == 0) { PPWarning ("`__VA_ARGS__' can only appear in the expansion " "of a C99 variadic macro"); } /* Add the macro argument */ AddMacroArg (M, Ident); } /* If we had an ellipsis, or the next char is not a comma, we've * reached the end of the macro argument list. */ SkipWhitespace (0); if (M->Variadic || CurC != ',') { break; } NextChar (); } /* Check for a right paren and eat it if we find one */ if (CurC != ')') { PPError ("`)' expected"); ClearLine (); return; } NextChar (); } /* Skip whitespace before the macro replacement */ SkipWhitespace (0); /* Insert the macro into the macro table and allocate the ActualArgs array */ InsertMacro (M); /* Remove whitespace and comments from the line, store the preprocessed * line into the macro replacement buffer. */ Pass1 (Line, &M->Replacement); /* Remove whitespace from the end of the line */ while (IsSpace (SB_LookAtLast (&M->Replacement))) { SB_Drop (&M->Replacement, 1); } #if 0 printf ("%s: <%.*s>\n", M->Name, SB_GetLen (&M->Replacement), SB_GetConstBuf (&M->Replacement)); #endif /* If we have an existing macro, check if the redefinition is identical. * Print a diagnostic if not. */ if (Existing && MacroCmp (M, Existing) != 0) { PPError ("Macro redefinition is not identical"); } } /*****************************************************************************/ /* Preprocessing */ /*****************************************************************************/ static unsigned Pass1 (StrBuf* Source, StrBuf* Target) /* Preprocessor pass 1. Remove whitespace. Handle old and new style comments * and the "defined" operator. */ { unsigned IdentCount; ident Ident; int HaveParen; /* Switch to the new input source */ StrBuf* OldSource = InitLine (Source); /* Loop removing ws and comments */ IdentCount = 0; while (CurC != '\0') { if (SkipWhitespace (0)) { /* Squeeze runs of blanks */ if (!IsSpace (SB_LookAtLast (Target))) { SB_AppendChar (Target, ' '); } } else if (IsSym (Ident)) { if (Preprocessing && strcmp (Ident, "defined") == 0) { /* Handle the "defined" operator */ SkipWhitespace (0); HaveParen = 0; if (CurC == '(') { HaveParen = 1; NextChar (); SkipWhitespace (0); } if (IsSym (Ident)) { SB_AppendChar (Target, IsMacro (Ident)? '1' : '0'); if (HaveParen) { SkipWhitespace (0); if (CurC != ')') { PPError ("`)' expected"); } else { NextChar (); } } } else { PPError ("Identifier expected"); SB_AppendChar (Target, '0'); } } else { ++IdentCount; SB_AppendStr (Target, Ident); } } else if (IsQuote (CurC)) { CopyQuotedString (Target); } else if (CurC == '/' && NextC == '*') { if (!IsSpace (SB_LookAtLast (Target))) { SB_AppendChar (Target, ' '); } OldStyleComment (); } else if (IS_Get (&Standard) >= STD_C99 && CurC == '/' && NextC == '/') { if (!IsSpace (SB_LookAtLast (Target))) { SB_AppendChar (Target, ' '); } NewStyleComment (); } else { SB_AppendChar (Target, CurC); NextChar (); } } /* Switch back to the old source */ InitLine (OldSource); /* Return the number of identifiers found in the line */ return IdentCount; } static void MacroReplacement (StrBuf* Source, StrBuf* Target) /* Perform macro replacement. */ { ident Ident; Macro* M; /* Remember the current input and switch to Source */ StrBuf* OldSource = InitLine (Source); /* Loop substituting macros */ while (CurC != '\0') { /* If we have an identifier, check if it's a macro */ if (IsSym (Ident)) { /* Check if it's a macro */ if ((M = FindMacro (Ident)) != 0 && !M->Expanding) { /* It's a macro, expand it */ ExpandMacro (Target, M); } else { /* An identifier, keep it */ SB_AppendStr (Target, Ident); } } else if (IsQuote (CurC)) { CopyQuotedString (Target); } else if (IsSpace (CurC)) { if (!IsSpace (SB_LookAtLast (Target))) { SB_AppendChar (Target, CurC); } NextChar (); } else { SB_AppendChar (Target, CurC); NextChar (); } } /* Switch back the input */ InitLine (OldSource); } static void PreprocessLine (void) /* Translate one line. */ { /* Trim whitespace and remove comments. The function returns the number of * identifiers found. If there were any, we will have to check for macros. */ SB_Clear (MLine); if (Pass1 (Line, MLine) > 0) { MLine = InitLine (MLine); SB_Reset (Line); SB_Clear (MLine); MacroReplacement (Line, MLine); } /* Read from the new line */ SB_Reset (MLine); MLine = InitLine (MLine); } static int PushIf (int Skip, int Invert, int Cond) /* Push a new if level onto the if stack */ { /* Check for an overflow of the if stack */ if (IfIndex >= MAX_IFS-1) { PPError ("Too many nested #if clauses"); return 1; } /* Push the #if condition */ ++IfIndex; if (Skip) { IfStack[IfIndex] = IFCOND_SKIP | IFCOND_NEEDTERM; return 1; } else { IfStack[IfIndex] = IFCOND_NONE | IFCOND_NEEDTERM; return (Invert ^ Cond); } } static void DoError (void) /* Print an error */ { SkipWhitespace (0); if (CurC == '\0') { PPError ("Invalid #error directive"); } else { PPError ("#error: %s", SB_GetConstBuf (Line) + SB_GetIndex (Line)); } /* Clear the rest of line */ ClearLine (); } static int DoIf (int Skip) /* Process #if directive */ { ExprDesc Expr; /* We're about to abuse the compiler expression parser to evaluate the * #if expression. Save the current tokens to come back here later. * NOTE: Yes, this is a hack, but it saves a complete separate expression * evaluation for the preprocessor. */ Token SavedCurTok = CurTok; Token SavedNextTok = NextTok; /* Make sure the line infos for the tokens won't get removed */ if (SavedCurTok.LI) { UseLineInfo (SavedCurTok.LI); } if (SavedNextTok.LI) { UseLineInfo (SavedNextTok.LI); } /* Switch into special preprocessing mode */ Preprocessing = 1; /* Expand macros in this line */ PreprocessLine (); /* Add two semicolons as sentinels to the line, so the following * expression evaluation will eat these two tokens but nothing from * the following line. */ SB_AppendStr (Line, ";;"); SB_Terminate (Line); /* Load CurTok and NextTok with tokens from the new input */ NextToken (); NextToken (); /* Call the expression parser */ ConstExpr (hie1, &Expr); /* End preprocessing mode */ Preprocessing = 0; /* Reset the old tokens */ CurTok = SavedCurTok; NextTok = SavedNextTok; /* Set the #if condition according to the expression result */ return PushIf (Skip, 1, Expr.IVal != 0); } static int DoIfDef (int skip, int flag) /* Process #ifdef if flag == 1, or #ifndef if flag == 0. */ { ident Ident; SkipWhitespace (0); if (MacName (Ident) == 0) { return 0; } else { return PushIf (skip, flag, IsMacro(Ident)); } } static void DoInclude (void) /* Open an include file. */ { char RTerm; InputType IT; StrBuf Filename = STATIC_STRBUF_INITIALIZER; /* Preprocess the remainder of the line */ PreprocessLine (); /* Skip blanks */ SkipWhitespace (0); /* Get the next char and check for a valid file name terminator. Setup * the include directory spec (SYS/USR) by looking at the terminator. */ switch (CurC) { case '\"': RTerm = '\"'; IT = IT_USRINC; break; case '<': RTerm = '>'; IT = IT_SYSINC; break; default: PPError ("`\"' or `<' expected"); goto Done; } NextChar (); /* Get a copy of the filename */ while (CurC != '\0' && CurC != RTerm) { SB_AppendChar (&Filename, CurC); NextChar (); } SB_Terminate (&Filename); /* Check if we got a terminator */ if (CurC == RTerm) { /* Open the include file */ OpenIncludeFile (SB_GetConstBuf (&Filename), IT); } else if (CurC == '\0') { /* No terminator found */ PPError ("#include expects \"FILENAME\" or <FILENAME>"); } Done: /* Free the allocated filename data */ SB_Done (&Filename); /* Clear the remaining line so the next input will come from the new * file (if open) */ ClearLine (); } static void DoPragma (void) /* Handle a #pragma line by converting the #pragma preprocessor directive into * the _Pragma() compiler operator. */ { /* Skip blanks following the #pragma directive */ SkipWhitespace (0); /* Copy the remainder of the line into MLine removing comments and ws */ SB_Clear (MLine); Pass1 (Line, MLine); /* Convert the directive into the operator */ SB_CopyStr (Line, "_Pragma ("); SB_Reset (MLine); Stringize (MLine, Line); SB_AppendChar (Line, ')'); /* Initialize reading from line */ SB_Reset (Line); InitLine (Line); } static void DoUndef (void) /* Process the #undef directive */ { ident Ident; SkipWhitespace (0); if (MacName (Ident)) { UndefineMacro (Ident); } } static void DoWarning (void) /* Print a warning */ { SkipWhitespace (0); if (CurC == '\0') { PPError ("Invalid #warning directive"); } else { PPWarning ("#warning: %s", SB_GetConstBuf (Line) + SB_GetIndex (Line)); } /* Clear the rest of line */ ClearLine (); } void Preprocess (void) /* Preprocess a line */ { int Skip; ident Directive; /* Create the output buffer if we don't already have one */ if (MLine == 0) { MLine = NewStrBuf (); } /* Skip white space at the beginning of the line */ SkipWhitespace (0); /* Check for stuff to skip */ Skip = 0; while (CurC == '\0' || CurC == '#' || Skip) { /* Check for preprocessor lines lines */ if (CurC == '#') { NextChar (); SkipWhitespace (0); if (CurC == '\0') { /* Ignore the empty preprocessor directive */ continue; } if (!IsSym (Directive)) { PPError ("Preprocessor directive expected"); ClearLine (); } else { switch (FindPPToken (Directive)) { case PP_DEFINE: if (!Skip) { DefineMacro (); } break; case PP_ELIF: if (IfIndex >= 0) { if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) { /* Handle as #else/#if combination */ if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) { Skip = !Skip; } IfStack[IfIndex] |= IFCOND_ELSE; Skip = DoIf (Skip); /* #elif doesn't need a terminator */ IfStack[IfIndex] &= ~IFCOND_NEEDTERM; } else { PPError ("Duplicate #else/#elif"); } } else { PPError ("Unexpected #elif"); } break; case PP_ELSE: if (IfIndex >= 0) { if ((IfStack[IfIndex] & IFCOND_ELSE) == 0) { if ((IfStack[IfIndex] & IFCOND_SKIP) == 0) { Skip = !Skip; } IfStack[IfIndex] |= IFCOND_ELSE; } else { PPError ("Duplicate #else"); } } else { PPError ("Unexpected `#else'"); } break; case PP_ENDIF: if (IfIndex >= 0) { /* Remove any clauses on top of stack that do not * need a terminating #endif. */ while (IfIndex >= 0 && (IfStack[IfIndex] & IFCOND_NEEDTERM) == 0) { --IfIndex; } /* Stack may not be empty here or something is wrong */ CHECK (IfIndex >= 0); /* Remove the clause that needs a terminator */ Skip = (IfStack[IfIndex--] & IFCOND_SKIP) != 0; } else { PPError ("Unexpected `#endif'"); } break; case PP_ERROR: if (!Skip) { DoError (); } break; case PP_IF: Skip = DoIf (Skip); break; case PP_IFDEF: Skip = DoIfDef (Skip, 1); break; case PP_IFNDEF: Skip = DoIfDef (Skip, 0); break; case PP_INCLUDE: if (!Skip) { DoInclude (); } break; case PP_LINE: /* Should do something in C99 at least, but we ignore it */ if (!Skip) { ClearLine (); } break; case PP_PRAGMA: if (!Skip) { DoPragma (); goto Done; } break; case PP_UNDEF: if (!Skip) { DoUndef (); } break; case PP_WARNING: /* #warning is a non standard extension */ if (IS_Get (&Standard) > STD_C99) { if (!Skip) { DoWarning (); } } else { if (!Skip) { PPError ("Preprocessor directive expected"); } ClearLine (); } break; default: if (!Skip) { PPError ("Preprocessor directive expected"); } ClearLine (); } } } if (NextLine () == 0) { if (IfIndex >= 0) { PPError ("`#endif' expected"); } return; } SkipWhitespace (0); } PreprocessLine (); Done: if (Verbosity > 1 && SB_NotEmpty (Line)) { printf ("%s(%u): %.*s\n", GetCurrentFile (), GetCurrentLine (), (int) SB_GetLen (Line), SB_GetConstBuf (Line)); } }
868
./cc65/src/cc65/typeconv.c
/*****************************************************************************/ /* */ /* typeconv.c */ /* */ /* Handle type conversions */ /* */ /* */ /* */ /* (C) 2002-2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "shift.h" /* cc65 */ #include "codegen.h" #include "datatype.h" #include "declare.h" #include "error.h" #include "expr.h" #include "loadexpr.h" #include "scanner.h" #include "typecmp.h" #include "typeconv.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void DoConversion (ExprDesc* Expr, const Type* NewType) /* Emit code to convert the given expression to a new type. */ { Type* OldType; unsigned OldSize; unsigned NewSize; /* Remember the old type */ OldType = Expr->Type; /* If we're converting to void, we're done. Note: This does also cover a * conversion void -> void. */ if (IsTypeVoid (NewType)) { ED_MakeRVal (Expr); /* Never an lvalue */ goto ExitPoint; } /* Don't allow casts from void to something else. */ if (IsTypeVoid (OldType)) { Error ("Cannot convert from `void' to something else"); goto ExitPoint; } /* Get the sizes of the types. Since we've excluded void types, checking * for known sizes makes sense here. */ OldSize = CheckedSizeOf (OldType); NewSize = CheckedSizeOf (NewType); /* lvalue? */ if (ED_IsLVal (Expr)) { /* We have an lvalue. If the new size is smaller than the new one, * we don't need to do anything. The compiler will generate code * to load only the portion of the value that is actually needed. * This works only on a little endian architecture, but that's * what we support. * If both sizes are equal, do also leave the value alone. * If the new size is larger, we must convert the value. */ if (NewSize > OldSize) { /* Load the value into the primary */ LoadExpr (CF_NONE, Expr); /* Emit typecast code */ g_typecast (TypeOf (NewType), TypeOf (OldType) | CF_FORCECHAR); /* Value is now in primary and an rvalue */ ED_MakeRValExpr (Expr); } } else if (ED_IsLocAbs (Expr)) { /* A cast of a constant numeric value to another type. Be sure * to handle sign extension correctly. */ /* Get the current and new size of the value */ unsigned OldBits = OldSize * 8; unsigned NewBits = NewSize * 8; /* Check if the new datatype will have a smaller range. If it * has a larger range, things are ok, since the value is * internally already represented by a long. */ if (NewBits <= OldBits) { /* Cut the value to the new size */ Expr->IVal &= (0xFFFFFFFFUL >> (32 - NewBits)); /* If the new type is signed, sign extend the value */ if (IsSignSigned (NewType)) { if (Expr->IVal & (0x01UL << (NewBits-1))) { /* Beware: Use the safe shift routine here. */ Expr->IVal |= shl_l (~0UL, NewBits); } } } } else { /* The value is not a constant. If the sizes of the types are * not equal, add conversion code. Be sure to convert chars * correctly. */ if (OldSize != NewSize) { /* Load the value into the primary */ LoadExpr (CF_NONE, Expr); /* Emit typecast code. */ g_typecast (TypeOf (NewType), TypeOf (OldType) | CF_FORCECHAR); /* Value is now a rvalue in the primary */ ED_MakeRValExpr (Expr); } } ExitPoint: /* The expression has always the new type */ ReplaceType (Expr, NewType); } void TypeConversion (ExprDesc* Expr, Type* NewType) /* Do an automatic conversion of the given expression to the new type. Output * warnings or errors where this automatic conversion is suspicious or * impossible. */ { #if 0 /* Debugging */ printf ("Expr:\n=======================================\n"); PrintExprDesc (stdout, Expr); printf ("Type:\n=======================================\n"); PrintType (stdout, NewType); printf ("\n"); PrintRawType (stdout, NewType); #endif /* First, do some type checking */ if (IsTypeVoid (NewType) || IsTypeVoid (Expr->Type)) { /* If one of the sides are of type void, output a more apropriate * error message. */ Error ("Illegal type"); } /* If Expr is a function, convert it to pointer to function */ if (IsTypeFunc(Expr->Type)) { Expr->Type = PointerTo (Expr->Type); } /* If both types are equal, no conversion is needed */ if (TypeCmp (Expr->Type, NewType) >= TC_EQUAL) { /* We're already done */ return; } /* Check for conversion problems */ if (IsClassInt (NewType)) { /* Handle conversions to int type */ if (IsClassPtr (Expr->Type)) { /* Pointer -> int conversion. Convert array to pointer */ if (IsTypeArray (Expr->Type)) { Expr->Type = ArrayToPtr (Expr->Type); } Warning ("Converting pointer to integer without a cast"); } else if (!IsClassInt (Expr->Type) && !IsClassFloat (Expr->Type)) { Error ("Incompatible types"); } } else if (IsClassFloat (NewType)) { if (!IsClassFloat (Expr->Type) && !IsClassInt (Expr->Type)) { Error ("Incompatible types"); } } else if (IsClassPtr (NewType)) { /* Handle conversions to pointer type */ if (IsClassPtr (Expr->Type)) { /* Convert array to pointer */ if (IsTypeArray (Expr->Type)) { Expr->Type = ArrayToPtr (Expr->Type); } /* Pointer to pointer assignment is valid, if: * - both point to the same types, or * - the rhs pointer is a void pointer, or * - the lhs pointer is a void pointer. */ if (!IsTypeVoid (Indirect (NewType)) && !IsTypeVoid (Indirect (Expr->Type))) { /* Compare the types */ switch (TypeCmp (NewType, Expr->Type)) { case TC_INCOMPATIBLE: Error ("Incompatible pointer types"); break; case TC_QUAL_DIFF: Error ("Pointer types differ in type qualifiers"); break; default: /* Ok */ break; } } } else if (IsClassInt (Expr->Type)) { /* Int to pointer assignment is valid only for constant zero */ if (!ED_IsConstAbsInt (Expr) || Expr->IVal != 0) { Warning ("Converting integer to pointer without a cast"); } } else { Error ("Incompatible types"); } } else { /* Invalid automatic conversion */ Error ("Incompatible types"); } /* Do the actual conversion */ DoConversion (Expr, NewType); } void TypeCast (ExprDesc* Expr) /* Handle an explicit cast. */ { Type NewType[MAXTYPELEN]; /* Skip the left paren */ NextToken (); /* Read the type */ ParseType (NewType); /* Closing paren */ ConsumeRParen (); /* Read the expression we have to cast */ hie10 (Expr); /* Convert functions and arrays to "pointer to" object */ Expr->Type = PtrConversion (Expr->Type); /* Convert the value. */ DoConversion (Expr, NewType); }
869
./cc65/src/cc65/coptstop.c
/*****************************************************************************/ /* */ /* coptstop.c */ /* */ /* Optimize operations that take operands via the stack */ /* */ /* */ /* */ /* (C) 2001-2009 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> /* common */ #include "chartype.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptstop.h" #include "error.h" /*****************************************************************************/ /* Load tracking data */ /*****************************************************************************/ /* LoadRegInfo flags set by DirectOp */ typedef enum { LI_NONE = 0x00, LI_DIRECT = 0x01, /* Direct op may be used */ LI_RELOAD_Y = 0x02, /* Reload index register Y */ LI_REMOVE = 0x04, /* Load may be removed */ LI_DUP_LOAD = 0x08, /* Duplicate load */ } LI_FLAGS; /* Structure that tells us how to load the lhs values */ typedef struct LoadRegInfo LoadRegInfo; struct LoadRegInfo { LI_FLAGS Flags; /* Tells us how to load */ int LoadIndex; /* Index of load insn, -1 if invalid */ CodeEntry* LoadEntry; /* The actual entry, 0 if invalid */ int XferIndex; /* Index of transfer insn */ CodeEntry* XferEntry; /* The actual transfer entry */ int Offs; /* Stack offset if data is on stack */ }; /* Now combined for both registers */ typedef struct LoadInfo LoadInfo; struct LoadInfo { LoadRegInfo A; /* Info for A register */ LoadRegInfo X; /* Info for X register */ LoadRegInfo Y; /* Info for Y register */ }; /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Flags for the functions */ typedef enum { OP_NONE = 0x00, /* Nothing special */ OP_A_KNOWN = 0x01, /* Value of A must be known */ OP_X_ZERO = 0x02, /* X must be zero */ OP_LHS_LOAD = 0x04, /* Must have load insns for LHS */ OP_LHS_LOAD_DIRECT = 0x0C, /* Must have direct load insn for LHS */ OP_RHS_LOAD = 0x10, /* Must have load insns for RHS */ OP_RHS_LOAD_DIRECT = 0x30, /* Must have direct load insn for RHS */ } OP_FLAGS; /* Structure forward decl */ typedef struct StackOpData StackOpData; /* Structure that describes an optimizer subfunction for a specific op */ typedef unsigned (*OptFunc) (StackOpData* D); typedef struct OptFuncDesc OptFuncDesc; struct OptFuncDesc { const char* Name; /* Name of the replaced runtime function */ OptFunc Func; /* Function pointer */ unsigned UnusedRegs; /* Regs that must not be used later */ OP_FLAGS Flags; /* Flags */ }; /* Structure that holds the needed data */ struct StackOpData { CodeSeg* Code; /* Pointer to code segment */ unsigned Flags; /* Flags to remember things */ /* Pointer to optimizer subfunction description */ const OptFuncDesc* OptFunc; /* ZP register usage inside the sequence */ unsigned UsedRegs; /* Register load information for lhs and rhs */ LoadInfo Lhs; LoadInfo Rhs; /* Several indices of insns in the code segment */ int PushIndex; /* Index of call to pushax in codeseg */ int OpIndex; /* Index of actual operation */ /* Pointers to insns in the code segment */ CodeEntry* PrevEntry; /* Entry before the call to pushax */ CodeEntry* PushEntry; /* Pointer to entry with call to pushax */ CodeEntry* OpEntry; /* Pointer to entry with op */ CodeEntry* NextEntry; /* Entry after the op */ const char* ZPLo; /* Lo byte of zero page loc to use */ const char* ZPHi; /* Hi byte of zero page loc to use */ unsigned IP; /* Insertion point used by some routines */ }; /*****************************************************************************/ /* Load tracking code */ /*****************************************************************************/ static void ClearLoadRegInfo (LoadRegInfo* RI) /* Clear a LoadRegInfo struct */ { RI->Flags = LI_NONE; RI->LoadIndex = -1; RI->XferIndex = -1; RI->Offs = 0; } static void FinalizeLoadRegInfo (LoadRegInfo* RI, CodeSeg* S) /* Prepare a LoadRegInfo struct for use */ { /* Get the entries */ if (RI->LoadIndex >= 0) { RI->LoadEntry = CS_GetEntry (S, RI->LoadIndex); } else { RI->LoadEntry = 0; } if (RI->XferIndex >= 0) { RI->XferEntry = CS_GetEntry (S, RI->XferIndex); } else { RI->XferEntry = 0; } } static void ClearLoadInfo (LoadInfo* LI) /* Clear a LoadInfo struct */ { ClearLoadRegInfo (&LI->A); ClearLoadRegInfo (&LI->X); ClearLoadRegInfo (&LI->Y); } static void AdjustLoadRegInfo (LoadRegInfo* RI, int Index, int Change) /* Adjust a load register info struct after deleting or inserting an entry * with a given index */ { CHECK (abs (Change) == 1); if (Change < 0) { /* Deletion */ if (Index < RI->LoadIndex) { --RI->LoadIndex; } else if (Index == RI->LoadIndex) { /* Has been removed */ RI->LoadIndex = -1; RI->LoadEntry = 0; } if (Index < RI->XferIndex) { --RI->XferIndex; } else if (Index == RI->XferIndex) { /* Has been removed */ RI->XferIndex = -1; RI->XferEntry = 0; } } else { /* Insertion */ if (Index <= RI->LoadIndex) { ++RI->LoadIndex; } if (Index <= RI->XferIndex) { ++RI->XferIndex; } } } static void FinalizeLoadInfo (LoadInfo* LI, CodeSeg* S) /* Prepare a LoadInfo struct for use */ { /* Get the entries */ FinalizeLoadRegInfo (&LI->A, S); FinalizeLoadRegInfo (&LI->X, S); FinalizeLoadRegInfo (&LI->Y, S); } static void AdjustLoadInfo (LoadInfo* LI, int Index, int Change) /* Adjust a load info struct after deleting entry with a given index */ { AdjustLoadRegInfo (&LI->A, Index, Change); AdjustLoadRegInfo (&LI->X, Index, Change); AdjustLoadRegInfo (&LI->Y, Index, Change); } static void TrackLoads (LoadInfo* LI, CodeEntry* E, int I) /* Track loads for a code entry */ { if (E->Info & OF_LOAD) { LoadRegInfo* RI = 0; /* Determine, which register was loaded */ if (E->Chg & REG_A) { RI = &LI->A; } else if (E->Chg & REG_X) { RI = &LI->X; } else if (E->Chg & REG_Y) { RI = &LI->Y; } CHECK (RI != 0); /* If we had a load or xfer op before, this is a duplicate load which * can cause problems if it encountered between the pushax and the op, * so remember it. */ if (RI->LoadIndex >= 0 || RI->XferIndex >= 0) { RI->Flags |= LI_DUP_LOAD; } /* Remember the load */ RI->LoadIndex = I; RI->XferIndex = -1; /* Set load flags */ RI->Flags &= ~(LI_DIRECT | LI_RELOAD_Y); if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS) { /* These insns are all ok and replaceable */ RI->Flags |= LI_DIRECT; } else if (E->AM == AM65_ZP_INDY && RegValIsKnown (E->RI->In.RegY) && strcmp (E->Arg, "sp") == 0) { /* A load from the stack with known offset is also ok, but in this * case we must reload the index register later. Please note that * a load indirect via other zero page locations is not ok, since * these locations may change between the push and the actual * operation. */ RI->Offs = (unsigned char) E->RI->In.RegY; RI->Flags |= (LI_DIRECT | LI_RELOAD_Y); } } else if (E->Info & OF_XFR) { /* Determine source and target of the transfer and handle the TSX insn */ LoadRegInfo* Src; LoadRegInfo* Tgt; switch (E->OPC) { case OP65_TAX: Src = &LI->A; Tgt = &LI->X; break; case OP65_TAY: Src = &LI->A; Tgt = &LI->Y; break; case OP65_TXA: Src = &LI->X; Tgt = &LI->A; break; case OP65_TYA: Src = &LI->Y; Tgt = &LI->A; break; case OP65_TSX: ClearLoadRegInfo (&LI->X); return; case OP65_TXS: return; default: Internal ("Unknown XFR insn in TrackLoads"); } /* If we had a load or xfer op before, this is a duplicate load which * can cause problems if it encountered between the pushax and the op, * so remember it. */ if (Tgt->LoadIndex >= 0 || Tgt->XferIndex >= 0) { Tgt->Flags |= LI_DUP_LOAD; } /* Transfer the data */ Tgt->LoadIndex = Src->LoadIndex; Tgt->XferIndex = I; Tgt->Offs = Src->Offs; Tgt->Flags &= ~(LI_DIRECT | LI_RELOAD_Y); Tgt->Flags |= Src->Flags & (LI_DIRECT | LI_RELOAD_Y); } else if (CE_IsCallTo (E, "ldaxysp") && RegValIsKnown (E->RI->In.RegY)) { /* If we had a load or xfer op before, this is a duplicate load which * can cause problems if it encountered between the pushax and the op, * so remember it for both registers involved. */ if (LI->A.LoadIndex >= 0 || LI->A.XferIndex >= 0) { LI->A.Flags |= LI_DUP_LOAD; } if (LI->X.LoadIndex >= 0 || LI->X.XferIndex >= 0) { LI->X.Flags |= LI_DUP_LOAD; } /* Both registers set, Y changed */ LI->A.LoadIndex = I; LI->A.XferIndex = -1; LI->A.Flags |= (LI_DIRECT | LI_RELOAD_Y); LI->A.Offs = (unsigned char) E->RI->In.RegY - 1; LI->X.LoadIndex = I; LI->X.XferIndex = -1; LI->X.Flags |= (LI_DIRECT | LI_RELOAD_Y); LI->X.Offs = (unsigned char) E->RI->In.RegY; ClearLoadRegInfo (&LI->Y); } else { if (E->Chg & REG_A) { ClearLoadRegInfo (&LI->A); } if (E->Chg & REG_X) { ClearLoadRegInfo (&LI->X); } if (E->Chg & REG_Y) { ClearLoadRegInfo (&LI->Y); } } } /*****************************************************************************/ /* Helpers */ /*****************************************************************************/ static void InsertEntry (StackOpData* D, CodeEntry* E, int Index) /* Insert a new entry. Depending on Index, D->PushIndex and D->OpIndex will * be adjusted by this function. */ { /* Insert the entry into the code segment */ CS_InsertEntry (D->Code, E, Index); /* Adjust register loads if necessary */ AdjustLoadInfo (&D->Lhs, Index, 1); AdjustLoadInfo (&D->Rhs, Index, 1); /* Adjust the indices if necessary */ if (D->PushEntry && Index <= D->PushIndex) { ++D->PushIndex; } if (D->OpEntry && Index <= D->OpIndex) { ++D->OpIndex; } } static void DelEntry (StackOpData* D, int Index) /* Delete an entry. Depending on Index, D->PushIndex and D->OpIndex will be * adjusted by this function, and PushEntry/OpEntry may get invalidated. */ { /* Delete the entry from the code segment */ CS_DelEntry (D->Code, Index); /* Adjust register loads if necessary */ AdjustLoadInfo (&D->Lhs, Index, -1); AdjustLoadInfo (&D->Rhs, Index, -1); /* Adjust the other indices if necessary */ if (Index < D->PushIndex) { --D->PushIndex; } else if (Index == D->PushIndex) { D->PushEntry = 0; } if (Index < D->OpIndex) { --D->OpIndex; } else if (Index == D->OpIndex) { D->OpEntry = 0; } } static void AdjustStackOffset (StackOpData* D, unsigned Offs) /* Adjust the offset for all stack accesses in the range PushIndex to OpIndex. * OpIndex is adjusted according to the insertions. */ { /* Walk over all entries */ int I = D->PushIndex + 1; while (I < D->OpIndex) { CodeEntry* E = CS_GetEntry (D->Code, I); int NeedCorrection = 0; if ((E->Use & REG_SP) != 0) { /* Check for some things that should not happen */ CHECK (E->AM == AM65_ZP_INDY || E->RI->In.RegY >= (short) Offs); CHECK (strcmp (E->Arg, "sp") == 0); /* We need to correct this one */ NeedCorrection = 1; } else if (CE_IsCallTo (E, "ldaxysp")) { /* We need to correct this one */ NeedCorrection = 1; } if (NeedCorrection) { /* Get the code entry before this one. If it's a LDY, adjust the * value. */ CodeEntry* P = CS_GetPrevEntry (D->Code, I); if (P && P->OPC == OP65_LDY && CE_IsConstImm (P)) { /* The Y load is just before the stack access, adjust it */ CE_SetNumArg (P, P->Num - Offs); } else { /* Insert a new load instruction before the stack access */ const char* Arg = MakeHexArg (E->RI->In.RegY - Offs); CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); InsertEntry (D, X, I++); } /* If we need the value of Y later, be sure to reload it */ if (RegYUsed (D->Code, I+1)) { const char* Arg = MakeHexArg (E->RI->In.RegY); CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI); InsertEntry (D, X, I+1); /* Skip this instruction in the next round */ ++I; } } /* Next entry */ ++I; } /* If we have rhs load insns that load from stack, we'll have to adjust * the offsets for these also. */ if (D->Rhs.A.Flags & LI_RELOAD_Y) { D->Rhs.A.Offs -= Offs; } if (D->Rhs.X.Flags & LI_RELOAD_Y) { D->Rhs.X.Offs -= Offs; } } static void AddStoreA (StackOpData* D) /* Add a store to zero page after the push insn */ { CodeEntry* X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->PushEntry->LI); InsertEntry (D, X, D->PushIndex+1); } static void AddStoreX (StackOpData* D) /* Add a store to zero page after the push insn */ { CodeEntry* X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI); InsertEntry (D, X, D->PushIndex+1); } static void ReplacePushByStore (StackOpData* D) /* Replace the call to the push subroutine by a store into the zero page * location (actually, the push is not replaced, because we need it for * later, but the name is still ok since the push will get removed at the * end of each routine). */ { /* Store the value into the zeropage instead of pushing it. Check high * byte first so that the store is later in A/X order. */ if ((D->Lhs.X.Flags & LI_DIRECT) == 0) { AddStoreX (D); } if ((D->Lhs.A.Flags & LI_DIRECT) == 0) { AddStoreA (D); } } static void AddOpLow (StackOpData* D, opc_t OPC, LoadInfo* LI) /* Add an op for the low byte of an operator. This function honours the * OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions. * All code is inserted at the current insertion point. */ { CodeEntry* X; if ((LI->A.Flags & LI_DIRECT) != 0) { /* Op with a variable location. If the location is on the stack, we * need to reload the Y register. */ if ((LI->A.Flags & LI_RELOAD_Y) == 0) { /* opc ... */ CodeEntry* LoadA = LI->A.LoadEntry; X = NewCodeEntry (OPC, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } else { /* ldy #offs */ const char* Arg = MakeHexArg (LI->A.Offs); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* opc (sp),y */ X = NewCodeEntry (OPC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } /* In both cases, we can remove the load */ LI->A.Flags |= LI_REMOVE; } else { /* Op with temp storage */ X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } } static void AddOpHigh (StackOpData* D, opc_t OPC, LoadInfo* LI, int KeepResult) /* Add an op for the high byte of an operator. Special cases (constant values * or similar) have to be checked separately, the function covers only the * generic case. Code is inserted at the insertion point. */ { CodeEntry* X; if (KeepResult) { /* pha */ X = NewCodeEntry (OP65_PHA, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } /* txa */ X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); if ((LI->X.Flags & LI_DIRECT) != 0) { if ((LI->X.Flags & LI_RELOAD_Y) == 0) { /* opc xxx */ CodeEntry* LoadX = LI->X.LoadEntry; X = NewCodeEntry (OPC, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } else { /* ldy #const */ const char* Arg = MakeHexArg (LI->X.Offs); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* opc (sp),y */ X = NewCodeEntry (OPC, AM65_ZP_INDY, "sp", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } /* In both cases, we can remove the load */ LI->X.Flags |= LI_REMOVE; } else { /* opc zphi */ X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } if (KeepResult) { /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* pla */ X = NewCodeEntry (OP65_PLA, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } } static void RemoveRegLoads (StackOpData* D, LoadInfo* LI) /* Remove register load insns */ { /* Both registers may be loaded with one insn, but DelEntry will in this * case clear the other one. */ if (LI->A.Flags & LI_REMOVE) { if (LI->A.LoadIndex >= 0) { DelEntry (D, LI->A.LoadIndex); } if (LI->A.XferIndex >= 0) { DelEntry (D, LI->A.XferIndex); } } if (LI->X.Flags & LI_REMOVE) { if (LI->X.LoadIndex >= 0) { DelEntry (D, LI->X.LoadIndex); } if (LI->X.XferIndex >= 0) { DelEntry (D, LI->X.XferIndex); } } } static void RemoveRemainders (StackOpData* D) /* Remove the code that is unnecessary after translation of the sequence */ { /* Remove the register loads for lhs and rhs */ RemoveRegLoads (D, &D->Lhs); RemoveRegLoads (D, &D->Rhs); /* Remove the push and the operator routine */ DelEntry (D, D->OpIndex); DelEntry (D, D->PushIndex); } static int IsRegVar (StackOpData* D) /* If the value pushed is that of a zeropage variable, replace ZPLo and ZPHi * in the given StackOpData struct by the variable and return true. Otherwise * leave D untouched and return false. */ { CodeEntry* LoadA = D->Lhs.A.LoadEntry; CodeEntry* LoadX = D->Lhs.X.LoadEntry; unsigned Len; /* Must have both load insns */ if (LoadA == 0 || LoadX == 0) { return 0; } /* Must be loads from zp */ if (LoadA->AM != AM65_ZP || LoadX->AM != AM65_ZP) { return 0; } /* Must be the same zp loc with high byte in X */ Len = strlen (LoadA->Arg); if (strncmp (LoadA->Arg, LoadX->Arg, Len) != 0 || strcmp (LoadX->Arg + Len, "+1") != 0) { return 0; } /* Use the zero page location directly */ D->ZPLo = LoadA->Arg; D->ZPHi = LoadX->Arg; return 1; } /*****************************************************************************/ /* Actual optimization functions */ /*****************************************************************************/ static unsigned Opt_toseqax_tosneax (StackOpData* D, const char* BoolTransformer) /* Optimize the toseqax and tosneax sequences. */ { CodeEntry* X; CodeLabel* L; /* Create a call to the boolean transformer function and a label for this * insn. This is needed for all variants. Other insns are inserted *before* * the call. */ X = NewCodeEntry (OP65_JSR, AM65_ABS, BoolTransformer, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex + 1); L = CS_GenLabel (D->Code, X); /* If the lhs is direct (but not stack relative), encode compares with lhs * effectively reverting the order (which doesn't matter for ==). */ if ((D->Lhs.A.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT && (D->Lhs.X.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT) { CodeEntry* LoadX = D->Lhs.X.LoadEntry; CodeEntry* LoadA = D->Lhs.A.LoadEntry; D->IP = D->OpIndex+1; /* cpx */ X = NewCodeEntry (OP65_CPX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* cmp */ X = NewCodeEntry (OP65_CMP, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Lhs load entries can be removed */ D->Lhs.X.Flags |= LI_REMOVE; D->Lhs.A.Flags |= LI_REMOVE; } else if ((D->Rhs.A.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT && (D->Rhs.X.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT) { CodeEntry* LoadX = D->Rhs.X.LoadEntry; CodeEntry* LoadA = D->Rhs.A.LoadEntry; D->IP = D->OpIndex+1; /* cpx */ X = NewCodeEntry (OP65_CPX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* cmp */ X = NewCodeEntry (OP65_CMP, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Rhs load entries can be removed */ D->Rhs.X.Flags |= LI_REMOVE; D->Rhs.A.Flags |= LI_REMOVE; } else if ((D->Rhs.A.Flags & LI_DIRECT) != 0 && (D->Rhs.X.Flags & LI_DIRECT) != 0) { D->IP = D->OpIndex+1; /* Add operand for low byte */ AddOpLow (D, OP65_CMP, &D->Rhs); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Add operand for high byte */ AddOpHigh (D, OP65_CMP, &D->Rhs, 0); } else { /* Save lhs into zeropage, then compare */ AddStoreX (D); AddStoreA (D); D->IP = D->OpIndex+1; /* cpx */ X = NewCodeEntry (OP65_CPX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* cmp */ X = NewCodeEntry (OP65_CMP, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } /* Remove the push and the call to the tosgeax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosshift (StackOpData* D, const char* Name) /* Optimize shift sequences. */ { CodeEntry* X; /* Store the value into the zeropage instead of pushing it */ ReplacePushByStore (D); /* If the lhs is direct (but not stack relative), we can just reload the * data later. */ if ((D->Lhs.A.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT && (D->Lhs.X.Flags & (LI_DIRECT | LI_RELOAD_Y)) == LI_DIRECT) { CodeEntry* LoadX = D->Lhs.X.LoadEntry; CodeEntry* LoadA = D->Lhs.A.LoadEntry; /* Inline the shift */ D->IP = D->OpIndex+1; /* tay */ X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* lda */ X = NewCodeEntry (OP65_LDA, LoadA->AM, LoadA->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* ldx */ X = NewCodeEntry (OP65_LDX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Lhs load entries can be removed */ D->Lhs.X.Flags |= LI_REMOVE; D->Lhs.A.Flags |= LI_REMOVE; } else { /* Save lhs into zeropage and reload later */ AddStoreX (D); AddStoreA (D); /* Be sure to setup IP after adding the stores, otherwise it will get * messed up. */ D->IP = D->OpIndex+1; /* tay */ X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* lda zp */ X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* ldx zp+1 */ X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } /* jsr shlaxy/aslaxy/whatever */ X = NewCodeEntry (OP65_JSR, AM65_ABS, Name, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the shift function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt___bzero (StackOpData* D) /* Optimize the __bzero sequence */ { CodeEntry* X; const char* Arg; CodeLabel* L; /* Check if we're using a register variable */ if (!IsRegVar (D)) { /* Store the value into the zeropage instead of pushing it */ AddStoreX (D); AddStoreA (D); } /* If the return value of __bzero is used, we have to add code to reload * a/x from the pointer variable. */ if (RegAXUsed (D->Code, D->OpIndex+1)) { X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+1); X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+2); } /* X is always zero, A contains the size of the data area to zero. * Note: A may be zero, in which case the operation is null op. */ if (D->OpEntry->RI->In.RegA != 0) { /* lda #$00 */ X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+1); /* The value of A is known */ if (D->OpEntry->RI->In.RegA <= 0x81) { /* Loop using the sign bit */ /* ldy #count-1 */ Arg = MakeHexArg (D->OpEntry->RI->In.RegA - 1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+2); /* L: sta (zp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+3); L = CS_GenLabel (D->Code, X); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+4); /* bpl L */ X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+5); } else { /* Loop using an explicit compare */ /* ldy #$00 */ X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+2); /* L: sta (zp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+3); L = CS_GenLabel (D->Code, X); /* iny */ X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+4); /* cpy #count */ Arg = MakeHexArg (D->OpEntry->RI->In.RegA); X = NewCodeEntry (OP65_CPY, AM65_IMM, Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+5); /* bne L */ X = NewCodeEntry (OP65_BNE, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+6); } } /* Remove the push and the call to the __bzero function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_staspidx (StackOpData* D) /* Optimize the staspidx sequence */ { CodeEntry* X; /* Check if we're using a register variable */ if (!IsRegVar (D)) { /* Store the value into the zeropage instead of pushing it */ AddStoreX (D); AddStoreA (D); } /* Replace the store subroutine call by a direct op */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+1); /* Remove the push and the call to the staspidx function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_staxspidx (StackOpData* D) /* Optimize the staxspidx sequence */ { CodeEntry* X; /* Check if we're using a register variable */ if (!IsRegVar (D)) { /* Store the value into the zeropage instead of pushing it */ AddStoreX (D); AddStoreA (D); } /* Inline the store */ /* sta (zp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+1); if (RegValIsKnown (D->OpEntry->RI->In.RegY)) { /* Value of Y is known */ const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegY + 1); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI); } else { X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI); } InsertEntry (D, X, D->OpIndex+2); if (RegValIsKnown (D->OpEntry->RI->In.RegX)) { /* Value of X is known */ const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX); X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI); } else { /* Value unknown */ X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI); } InsertEntry (D, X, D->OpIndex+3); /* sta (zp),y */ X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, D->ZPLo, 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+4); /* If we remove staxspidx, we must restore the Y register to what the * function would return. */ X = NewCodeEntry (OP65_LDY, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->OpIndex+5); /* Remove the push and the call to the staxspidx function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosaddax (StackOpData* D) /* Optimize the tosaddax sequence */ { CodeEntry* X; CodeEntry* N; /* We need the entry behind the add */ CHECK (D->NextEntry != 0); /* Check if the X register is known and zero when the add is done, and * if the add is followed by * * ldy #$00 * jsr ldauidx ; or ldaidx * * If this is true, the addition does actually add an offset to a pointer * before it is dereferenced. Since both subroutines take an offset in Y, * we can pass the offset (instead of #$00) and remove the addition * alltogether. */ if (D->OpEntry->RI->In.RegX == 0 && D->NextEntry->OPC == OP65_LDY && CE_IsKnownImm (D->NextEntry, 0) && !CE_HasLabel (D->NextEntry) && (N = CS_GetNextEntry (D->Code, D->OpIndex + 1)) != 0 && (CE_IsCallTo (N, "ldauidx") || CE_IsCallTo (N, "ldaidx"))) { int Signed = (strcmp (N->Arg, "ldaidx") == 0); /* Store the value into the zeropage instead of pushing it */ AddStoreX (D); AddStoreA (D); /* Replace the ldy by a tay. Be sure to create the new entry before * deleting the ldy, since we will reference the line info from this * insn. */ X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, D->NextEntry->LI); DelEntry (D, D->OpIndex + 1); InsertEntry (D, X, D->OpIndex + 1); /* Replace the call to ldaidx/ldauidx. Since X is already zero, and * the ptr is in the zero page location, we just need to load from * the pointer, and fix X in case of ldaidx. */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, D->ZPLo, 0, N->LI); DelEntry (D, D->OpIndex + 2); InsertEntry (D, X, D->OpIndex + 2); if (Signed) { CodeLabel* L; /* Add sign extension - N is unused now */ N = CS_GetNextEntry (D->Code, D->OpIndex + 2); CHECK (N != 0); L = CS_GenLabel (D->Code, N); X = NewCodeEntry (OP65_BPL, AM65_BRA, L->Name, L, X->LI); InsertEntry (D, X, D->OpIndex + 3); X = NewCodeEntry (OP65_DEX, AM65_IMP, 0, 0, X->LI); InsertEntry (D, X, D->OpIndex + 4); } } else { /* Store the value into the zeropage instead of pushing it */ ReplacePushByStore (D); /* Inline the add */ D->IP = D->OpIndex+1; /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Low byte */ AddOpLow (D, OP65_ADC, &D->Lhs); /* High byte */ if (D->PushEntry->RI->In.RegX == 0) { /* The high byte is the value in X plus the carry */ CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry); /* bcc L */ X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } else if (D->OpEntry->RI->In.RegX == 0 && (RegValIsKnown (D->PushEntry->RI->In.RegX) || (D->Lhs.X.Flags & LI_RELOAD_Y) == 0)) { /* The high byte is that of the first operand plus carry */ CodeLabel* L; if (RegValIsKnown (D->PushEntry->RI->In.RegX)) { /* Value of first op high byte is known */ const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI); } else { /* Value of first op high byte is unknown. Load from ZP or * original storage. */ if (D->Lhs.X.Flags & LI_DIRECT) { CodeEntry* LoadX = D->Lhs.X.LoadEntry; X = NewCodeEntry (OP65_LDX, LoadX->AM, LoadX->Arg, 0, D->OpEntry->LI); } else { X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI); } } InsertEntry (D, X, D->IP++); /* bcc label */ L = CS_GenLabel (D->Code, D->NextEntry); X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } else { /* High byte is unknown */ AddOpHigh (D, OP65_ADC, &D->Lhs, 1); } } /* Remove the push and the call to the tosaddax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosandax (StackOpData* D) /* Optimize the tosandax sequence */ { /* Store the value into the zeropage instead of pushing it */ ReplacePushByStore (D); /* Inline the and, low byte */ D->IP = D->OpIndex + 1; AddOpLow (D, OP65_AND, &D->Lhs); /* High byte */ AddOpHigh (D, OP65_AND, &D->Lhs, 1); /* Remove the push and the call to the tosandax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosaslax (StackOpData* D) /* Optimize the tosaslax sequence */ { return Opt_tosshift (D, "aslaxy"); } static unsigned Opt_tosasrax (StackOpData* D) /* Optimize the tosasrax sequence */ { return Opt_tosshift (D, "asraxy"); } static unsigned Opt_toseqax (StackOpData* D) /* Optimize the toseqax sequence */ { return Opt_toseqax_tosneax (D, "booleq"); } static unsigned Opt_tosgeax (StackOpData* D) /* Optimize the tosgeax sequence */ { CodeEntry* X; CodeLabel* L; /* Inline the sbc */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* Add code for low operand */ AddOpLow (D, OP65_CMP, &D->Rhs); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* eor #$80 */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$80", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); L = CS_GenLabel (D->Code, X); /* Insert a bvs L before the eor insn */ X = NewCodeEntry (OP65_BVS, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP - 2); ++D->IP; /* lda #$00 */ X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* rol a */ X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the tosgeax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosltax (StackOpData* D) /* Optimize the tosltax sequence */ { CodeEntry* X; CodeLabel* L; /* Inline the compare */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* Add code for low operand */ AddOpLow (D, OP65_CMP, &D->Rhs); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* eor #$80 */ X = NewCodeEntry (OP65_EOR, AM65_IMM, "$80", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); L = CS_GenLabel (D->Code, X); /* Insert a bvc L before the eor insn */ X = NewCodeEntry (OP65_BVC, AM65_BRA, L->Name, L, D->OpEntry->LI); InsertEntry (D, X, D->IP - 2); ++D->IP; /* lda #$00 */ X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* rol a */ X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the tosltax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosneax (StackOpData* D) /* Optimize the tosneax sequence */ { return Opt_toseqax_tosneax (D, "boolne"); } static unsigned Opt_tosorax (StackOpData* D) /* Optimize the tosorax sequence */ { /* Store the value into the zeropage instead of pushing it */ ReplacePushByStore (D); /* Inline the or, low byte */ D->IP = D->OpIndex + 1; AddOpLow (D, OP65_ORA, &D->Lhs); /* High byte */ AddOpHigh (D, OP65_ORA, &D->Lhs, 1); /* Remove the push and the call to the tosorax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosshlax (StackOpData* D) /* Optimize the tosshlax sequence */ { return Opt_tosshift (D, "shlaxy"); } static unsigned Opt_tosshrax (StackOpData* D) /* Optimize the tosshrax sequence */ { return Opt_tosshift (D, "shraxy"); } static unsigned Opt_tossubax (StackOpData* D) /* Optimize the tossubax sequence. Note: subtraction is not commutative! */ { CodeEntry* X; /* Inline the sbc */ D->IP = D->OpIndex+1; /* sec */ X = NewCodeEntry (OP65_SEC, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* Add code for low operand */ AddOpLow (D, OP65_SBC, &D->Rhs); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 1); /* Remove the push and the call to the tossubax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosugeax (StackOpData* D) /* Optimize the tosugeax sequence */ { CodeEntry* X; /* Inline the sbc */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* Add code for low operand */ AddOpLow (D, OP65_CMP, &D->Rhs); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* lda #$00 */ X = NewCodeEntry (OP65_LDA, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* rol a */ X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the tosugeax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosugtax (StackOpData* D) /* Optimize the tosugtax sequence */ { CodeEntry* X; /* Inline the sbc */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* sec */ X = NewCodeEntry (OP65_SEC, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Add code for low operand */ AddOpLow (D, OP65_SBC, &D->Rhs); /* We need the zero flag, so remember the immediate result */ X = NewCodeEntry (OP65_STA, AM65_ZP, "tmp1", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* Set Z flag */ X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Transform to boolean */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "boolugt", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the operator function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosuleax (StackOpData* D) /* Optimize the tosuleax sequence */ { CodeEntry* X; /* Inline the sbc */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* sec */ X = NewCodeEntry (OP65_SEC, AM65_IMP, 0, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Add code for low operand */ AddOpLow (D, OP65_SBC, &D->Rhs); /* We need the zero flag, so remember the immediate result */ X = NewCodeEntry (OP65_STA, AM65_ZP, "tmp1", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* Set Z flag */ X = NewCodeEntry (OP65_ORA, AM65_ZP, "tmp1", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Transform to boolean */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "boolule", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the operator function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosultax (StackOpData* D) /* Optimize the tosultax sequence */ { CodeEntry* X; /* Inline the sbc */ D->IP = D->OpIndex+1; /* Must be true because of OP_RHS_LOAD */ CHECK ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) != 0); /* Add code for low operand */ AddOpLow (D, OP65_CMP, &D->Rhs); /* Add code for high operand */ AddOpHigh (D, OP65_SBC, &D->Rhs, 0); /* Transform to boolean */ X = NewCodeEntry (OP65_JSR, AM65_ABS, "boolult", 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); /* Remove the push and the call to the operator function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } static unsigned Opt_tosxorax (StackOpData* D) /* Optimize the tosxorax sequence */ { CodeEntry* X; /* Store the value into the zeropage instead of pushing it */ ReplacePushByStore (D); /* Inline the xor, low byte */ D->IP = D->OpIndex + 1; AddOpLow (D, OP65_EOR, &D->Lhs); /* High byte */ if (RegValIsKnown (D->PushEntry->RI->In.RegX) && RegValIsKnown (D->OpEntry->RI->In.RegX)) { /* Both values known, precalculate the result */ const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX); X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI); InsertEntry (D, X, D->IP++); } else if (D->PushEntry->RI->In.RegX != 0) { /* High byte is unknown */ AddOpHigh (D, OP65_EOR, &D->Lhs, 1); } /* Remove the push and the call to the tosandax function */ RemoveRemainders (D); /* We changed the sequence */ return 1; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static const OptFuncDesc FuncTable[] = { { "__bzero", Opt___bzero, REG_NONE, OP_X_ZERO | OP_A_KNOWN }, { "staspidx", Opt_staspidx, REG_NONE, OP_NONE }, { "staxspidx", Opt_staxspidx, REG_AX, OP_NONE }, { "tosaddax", Opt_tosaddax, REG_NONE, OP_NONE }, { "tosandax", Opt_tosandax, REG_NONE, OP_NONE }, { "tosaslax", Opt_tosaslax, REG_NONE, OP_NONE }, { "tosasrax", Opt_tosasrax, REG_NONE, OP_NONE }, { "toseqax", Opt_toseqax, REG_NONE, OP_NONE }, { "tosgeax", Opt_tosgeax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosltax", Opt_tosltax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosneax", Opt_tosneax, REG_NONE, OP_NONE }, { "tosorax", Opt_tosorax, REG_NONE, OP_NONE }, { "tosshlax", Opt_tosshlax, REG_NONE, OP_NONE }, { "tosshrax", Opt_tosshrax, REG_NONE, OP_NONE }, { "tossubax", Opt_tossubax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosugeax", Opt_tosugeax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosugtax", Opt_tosugtax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosuleax", Opt_tosuleax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosultax", Opt_tosultax, REG_NONE, OP_RHS_LOAD_DIRECT }, { "tosxorax", Opt_tosxorax, REG_NONE, OP_NONE }, }; #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0])) static int CmpFunc (const void* Key, const void* Func) /* Compare function for bsearch */ { return strcmp (Key, ((const OptFuncDesc*) Func)->Name); } static const OptFuncDesc* FindFunc (const char* Name) /* Find the function with the given name. Return a pointer to the table entry * or NULL if the function was not found. */ { return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc); } static int CmpHarmless (const void* Key, const void* Entry) /* Compare function for bsearch */ { return strcmp (Key, *(const char**)Entry); } static int HarmlessCall (const char* Name) /* Check if this is a call to a harmless subroutine that will not interrupt * the pushax/op sequence when encountered. */ { static const char* Tab[] = { "aslax1", "aslax2", "aslax3", "aslax4", "aslaxy", "asrax1", "asrax2", "asrax3", "asrax4", "asraxy", "bnegax", "complax", "decax1", "decax2", "decax3", "decax4", "decax5", "decax6", "decax7", "decax8", "decaxy", "incax1", "incax2", "incax3", "incax4", "incax5", "incax6", "incax7", "incax8", "incaxy", "ldaxidx", "ldaxysp", "negax", "shlax1", "shlax2", "shlax3", "shlax4", "shlaxy", "shrax1", "shrax2", "shrax3", "shrax4", "shraxy", }; void* R = bsearch (Name, Tab, sizeof (Tab) / sizeof (Tab[0]), sizeof (Tab[0]), CmpHarmless); return (R != 0); } static void ResetStackOpData (StackOpData* Data) /* Reset the given data structure */ { Data->OptFunc = 0; Data->UsedRegs = REG_NONE; ClearLoadInfo (&Data->Lhs); ClearLoadInfo (&Data->Rhs); Data->PushIndex = -1; Data->OpIndex = -1; } static int PreCondOk (StackOpData* D) /* Check if the preconditions for a call to the optimizer subfunction are * satisfied. As a side effect, this function will also choose the zero page * register to use. */ { /* Check the flags */ unsigned UnusedRegs = D->OptFunc->UnusedRegs; if (UnusedRegs != REG_NONE && (GetRegInfo (D->Code, D->OpIndex+1, UnusedRegs) & UnusedRegs) != 0) { /* Cannot optimize */ return 0; } if ((D->OptFunc->Flags & OP_A_KNOWN) != 0 && RegValIsUnknown (D->OpEntry->RI->In.RegA)) { /* Cannot optimize */ return 0; } if ((D->OptFunc->Flags & OP_X_ZERO) != 0 && D->OpEntry->RI->In.RegX != 0) { /* Cannot optimize */ return 0; } if ((D->OptFunc->Flags & OP_LHS_LOAD) != 0) { if (D->Lhs.A.LoadIndex < 0 || D->Lhs.X.LoadIndex < 0) { /* Cannot optimize */ return 0; } else if ((D->OptFunc->Flags & OP_LHS_LOAD_DIRECT) != 0) { if ((D->Lhs.A.Flags & D->Lhs.X.Flags & LI_DIRECT) == 0) { /* Cannot optimize */ return 0; } } } if ((D->OptFunc->Flags & OP_RHS_LOAD) != 0) { if (D->Rhs.A.LoadIndex < 0 || D->Rhs.X.LoadIndex < 0) { /* Cannot optimize */ return 0; } else if ((D->OptFunc->Flags & OP_RHS_LOAD_DIRECT) != 0) { if ((D->Rhs.A.Flags & D->Rhs.X.Flags & LI_DIRECT) == 0) { /* Cannot optimize */ return 0; } } } if ((D->Rhs.A.Flags | D->Rhs.X.Flags) & LI_DUP_LOAD) { /* Cannot optimize */ return 0; } /* Determine the zero page locations to use */ if ((D->UsedRegs & REG_PTR1) == REG_NONE) { D->ZPLo = "ptr1"; D->ZPHi = "ptr1+1"; } else if ((D->UsedRegs & REG_SREG) == REG_NONE) { D->ZPLo = "sreg"; D->ZPHi = "sreg+1"; } else if ((D->UsedRegs & REG_PTR2) == REG_NONE) { D->ZPLo = "ptr2"; D->ZPHi = "ptr2+1"; } else { /* No registers available */ return 0; } /* Determine if we have a basic block */ return CS_IsBasicBlock (D->Code, D->PushIndex, D->OpIndex); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptStackOps (CodeSeg* S) /* Optimize operations that take operands via the stack */ { unsigned Changes = 0; /* Number of changes in one run */ StackOpData Data; int I; int OldEntryCount; /* Old number of entries */ unsigned UsedRegs = 0; /* Registers used */ unsigned ChangedRegs = 0;/* Registers changed */ enum { Initialize, Search, FoundPush, FoundOp } State = Initialize; /* Remember the code segment in the info struct */ Data.Code = S; /* Look for a call to pushax followed by a call to some other function * that takes it's first argument on the stack, and the second argument * in the primary register. * It depends on the code between the two if we can handle/transform the * sequence, so check this code for the following list of things: * * - the range must be a basic block (one entry, one exit) * - there may not be accesses to local variables with unknown * offsets (because we have to adjust these offsets). * - no subroutine calls * - no jump labels * * Since we need a zero page register later, do also check the * intermediate code for zero page use. */ I = 0; while (I < (int)CS_GetEntryCount (S)) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Actions depend on state */ switch (State) { case Initialize: ResetStackOpData (&Data); UsedRegs = ChangedRegs = REG_NONE; State = Search; /* FALLTHROUGH */ case Search: /* While searching, track register load insns, so we can tell * what is in a register once pushax is encountered. */ if (CE_HasLabel (E)) { /* Currently we don't track across branches */ ClearLoadInfo (&Data.Lhs); } if (CE_IsCallTo (E, "pushax")) { Data.PushIndex = I; State = FoundPush; } else { /* Track load insns */ TrackLoads (&Data.Lhs, E, I); } break; case FoundPush: /* We' found a pushax before. Search for a stack op that may * follow and in the meantime, track zeropage usage and check * for code that will disable us from translating the sequence. */ if (CE_HasLabel (E)) { /* Currently we don't track across branches */ ClearLoadInfo (&Data.Rhs); } if (E->OPC == OP65_JSR) { /* Subroutine call: Check if this is one of the functions, * we're going to replace. */ Data.OptFunc = FindFunc (E->Arg); if (Data.OptFunc) { /* Remember the op index and go on */ Data.OpIndex = I; Data.OpEntry = E; State = FoundOp; break; } else if (!HarmlessCall (E->Arg)) { /* A call to an unkown subroutine: We need to start * over after the last pushax. Note: This will also * happen if we encounter a call to pushax! */ I = Data.PushIndex; State = Initialize; break; } else { /* Track register usage */ Data.UsedRegs |= (E->Use | E->Chg); TrackLoads (&Data.Rhs, E, I); } } else if (E->Info & OF_STORE && (E->Chg & REG_ZP) == 0) { /* Too dangerous - there may be a change of a variable * within the sequence. */ I = Data.PushIndex; State = Initialize; break; } else if ((E->Use & REG_SP) != 0 && (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) || E->RI->In.RegY < 2)) { /* If we are using the stack, and we don't have "indirect Y" * addressing mode, or the value of Y is unknown, or less * than two, we cannot cope with this piece of code. Having * an unknown value of Y means that we cannot correct the * stack offset, while having an offset less than two means * that the code works with the value on stack which is to * be removed. */ I = Data.PushIndex; State = Initialize; break; } else { /* Other stuff: Track register usage */ Data.UsedRegs |= (E->Use | E->Chg); TrackLoads (&Data.Rhs, E, I); } /* If the registers from the push (A/X) are used before they're * changed, we cannot change the sequence, because this would * with a high probability change the register contents. */ UsedRegs |= E->Use; if ((UsedRegs & ~ChangedRegs) & REG_AX) { I = Data.PushIndex; State = Initialize; break; } ChangedRegs |= E->Chg; break; case FoundOp: /* Track zero page location usage beyond this point */ Data.UsedRegs |= GetRegInfo (S, I, REG_SREG | REG_PTR1 | REG_PTR2); /* Finalize the load info */ FinalizeLoadInfo (&Data.Lhs, S); FinalizeLoadInfo (&Data.Rhs, S); /* If the Lhs loads do load from zeropage, we have to include * them into UsedRegs registers used. The Rhs loads have already * been tracked. */ if (Data.Lhs.A.LoadEntry && Data.Lhs.A.LoadEntry->AM == AM65_ZP) { Data.UsedRegs |= Data.Lhs.A.LoadEntry->Use; } if (Data.Lhs.X.LoadEntry && Data.Lhs.X.LoadEntry->AM == AM65_ZP) { Data.UsedRegs |= Data.Lhs.X.LoadEntry->Use; } /* Check the preconditions. If they aren't ok, reset the insn * pointer to the pushax and start over. We will loose part of * load tracking but at least a/x has probably lost between * pushax and here and will be tracked again when restarting. */ if (!PreCondOk (&Data)) { I = Data.PushIndex; State = Initialize; break; } /* Prepare the remainder of the data structure. */ Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex); Data.PushEntry = CS_GetEntry (S, Data.PushIndex); Data.OpEntry = CS_GetEntry (S, Data.OpIndex); Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex); /* Remember the current number of code lines */ OldEntryCount = CS_GetEntryCount (S); /* Adjust stack offsets to account for the upcoming removal */ AdjustStackOffset (&Data, 2); /* Regenerate register info, since AdjustStackOffset changed * the code */ CS_GenRegInfo (S); /* Call the optimizer function */ Changes += Data.OptFunc->Func (&Data); /* Since the function may have added or deleted entries, * correct the index. */ I += CS_GetEntryCount (S) - OldEntryCount; /* Regenerate register info */ CS_GenRegInfo (S); /* Done */ State = Initialize; continue; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
870
./cc65/src/cc65/loop.c
/*****************************************************************************/ /* */ /* loop.c */ /* */ /* Loop management */ /* */ /* */ /* */ /* (C) 1998-2004 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "xmalloc.h" /* cc65 */ #include "error.h" #include "loop.h" #include "stackptr.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* The root */ static LoopDesc* LoopStack = 0; /*****************************************************************************/ /* Code */ /*****************************************************************************/ LoopDesc* AddLoop (unsigned BreakLabel, unsigned ContinueLabel) /* Create and add a new loop descriptor. */ { /* Allocate a new struct */ LoopDesc* L = xmalloc (sizeof (LoopDesc)); /* Fill in the data */ L->StackPtr = StackPtr; L->BreakLabel = BreakLabel; L->ContinueLabel = ContinueLabel; /* Insert it into the list */ L->Next = LoopStack; LoopStack = L; /* Return a pointer to the struct */ return L; } LoopDesc* CurrentLoop (void) /* Return a pointer to the descriptor of the current loop */ { return LoopStack; } void DelLoop (void) /* Remove the current loop */ { LoopDesc* L = LoopStack; CHECK (L != 0); LoopStack = LoopStack->Next; xfree (L); }
871
./cc65/src/cc65/macrotab.c
/*****************************************************************************/ /* */ /* macrotab.h */ /* */ /* Preprocessor macro table for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> /* common */ #include "hashfunc.h" #include "xmalloc.h" /* cc65 */ #include "error.h" #include "macrotab.h" /*****************************************************************************/ /* data */ /*****************************************************************************/ /* The macro hash table */ #define MACRO_TAB_SIZE 211 static Macro* MacroTab[MACRO_TAB_SIZE]; /*****************************************************************************/ /* code */ /*****************************************************************************/ Macro* NewMacro (const char* Name) /* Allocate a macro structure with the given name. The structure is not * inserted into the macro table. */ { /* Get the length of the macro name */ unsigned Len = strlen(Name); /* Allocate the structure */ Macro* M = (Macro*) xmalloc (sizeof(Macro) + Len); /* Initialize the data */ M->Next = 0; M->Expanding = 0; M->ArgCount = -1; /* Flag: Not a function like macro */ M->MaxArgs = 0; InitCollection (&M->FormalArgs); SB_Init (&M->Replacement); M->Variadic = 0; memcpy (M->Name, Name, Len+1); /* Return the new macro */ return M; } void FreeMacro (Macro* M) /* Delete a macro definition. The function will NOT remove the macro from the * table, use UndefineMacro for that. */ { unsigned I; for (I = 0; I < CollCount (&M->FormalArgs); ++I) { xfree (CollAtUnchecked (&M->FormalArgs, I)); } DoneCollection (&M->FormalArgs); SB_Done (&M->Replacement); xfree (M); } void DefineNumericMacro (const char* Name, long Val) /* Define a macro for a numeric constant */ { char Buf[64]; /* Make a string from the number */ sprintf (Buf, "%ld", Val); /* Handle as text macro */ DefineTextMacro (Name, Buf); } void DefineTextMacro (const char* Name, const char* Val) /* Define a macro for a textual constant */ { /* Create a new macro */ Macro* M = NewMacro (Name); /* Set the value as replacement text */ SB_CopyStr (&M->Replacement, Val); /* Insert the macro into the macro table */ InsertMacro (M); } void InsertMacro (Macro* M) /* Insert the given macro into the macro table. */ { /* Get the hash value of the macro name */ unsigned Hash = HashStr (M->Name) % MACRO_TAB_SIZE; /* Insert the macro */ M->Next = MacroTab[Hash]; MacroTab[Hash] = M; } int UndefineMacro (const char* Name) /* Search for the macro with the given name and remove it from the macro * table if it exists. Return 1 if a macro was found and deleted, return * 0 otherwise. */ { /* Get the hash value of the macro name */ unsigned Hash = HashStr (Name) % MACRO_TAB_SIZE; /* Search the hash chain */ Macro* L = 0; Macro* M = MacroTab[Hash]; while (M) { if (strcmp (M->Name, Name) == 0) { /* Found it */ if (L == 0) { /* First in chain */ MacroTab[Hash] = M->Next; } else { L->Next = M->Next; } /* Delete the macro */ FreeMacro (M); /* Done */ return 1; } /* Next macro */ L = M; M = M->Next; } /* Not found */ return 0; } Macro* FindMacro (const char* Name) /* Find a macro with the given name. Return the macro definition or NULL */ { /* Get the hash value of the macro name */ unsigned Hash = HashStr (Name) % MACRO_TAB_SIZE; /* Search the hash chain */ Macro* M = MacroTab[Hash]; while (M) { if (strcmp (M->Name, Name) == 0) { /* Found it */ return M; } /* Next macro */ M = M->Next; } /* Not found */ return 0; } int FindMacroArg (Macro* M, const char* Arg) /* Search for a formal macro argument. If found, return the index of the * argument. If the argument was not found, return -1. */ { unsigned I; for (I = 0; I < CollCount (&M->FormalArgs); ++I) { if (strcmp (CollAtUnchecked (&M->FormalArgs, I), Arg) == 0) { /* Found */ return I; } } /* Not found */ return -1; } void AddMacroArg (Macro* M, const char* Arg) /* Add a formal macro argument. */ { /* Check if we have a duplicate macro argument, but add it anyway. * Beware: Don't use FindMacroArg here, since the actual argument array * may not be initialized. */ unsigned I; for (I = 0; I < CollCount (&M->FormalArgs); ++I) { if (strcmp (CollAtUnchecked (&M->FormalArgs, I), Arg) == 0) { /* Found */ Error ("Duplicate macro parameter: `%s'", Arg); break; } } /* Add the new argument */ CollAppend (&M->FormalArgs, xstrdup (Arg)); ++M->ArgCount; } int MacroCmp (const Macro* M1, const Macro* M2) /* Compare two macros and return zero if both are identical. */ { int I; /* Argument count must be identical */ if (M1->ArgCount != M2->ArgCount) { return 1; } /* Compare the arguments */ for (I = 0; I < M1->ArgCount; ++I) { if (strcmp (CollConstAt (&M1->FormalArgs, I), CollConstAt (&M2->FormalArgs, I)) != 0) { return 1; } } /* Compare the replacement */ return SB_Compare (&M1->Replacement, &M2->Replacement); } void PrintMacroStats (FILE* F) /* Print macro statistics to the given text file. */ { unsigned I; Macro* M; fprintf (F, "\n\nMacro Hash Table Summary\n"); for (I = 0; I < MACRO_TAB_SIZE; ++I) { fprintf (F, "%3u : ", I); M = MacroTab [I]; if (M) { while (M) { fprintf (F, "%s ", M->Name); M = M->Next; } fprintf (F, "\n"); } else { fprintf (F, "empty\n"); } } }
872
./cc65/src/cc65/coptstore.c
/*****************************************************************************/ /* */ /* coptstore.c */ /* */ /* Optimize stores */ /* */ /* */ /* */ /* (C) 2002-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptstore.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void InsertStore (CodeSeg* S, unsigned* IP, LineInfo* LI) { CodeEntry* X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, "sp", 0, LI); CS_InsertEntry (S, X, (*IP)++); } unsigned OptStore1 (CodeSeg* S) /* Search for the sequence * * ldy #n * jsr staxysp * ldy #n+1 * jsr ldaxysp * * and remove the useless load. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CE_IsConstImm (L[0]) && L[0]->Num < 0xFF && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 3) && CE_IsCallTo (L[1], "staxysp") && L[2]->OPC == OP65_LDY && CE_IsKnownImm (L[2], L[0]->Num + 1) && CE_IsCallTo (L[3], "ldaxysp")) { /* Register has already the correct value, remove the loads */ CS_DelEntries (S, I+2, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptStore2 (CodeSeg* S) /* Search for a call to staxysp. If the ax register is not used later, and * the value is constant, just use the A register and store directly into the * stack. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Get the input registers */ const RegInfo* RI = E->RI; /* Check for the call */ if (CE_IsCallTo (E, "staxysp") && RegValIsKnown (RI->In.RegA) && RegValIsKnown (RI->In.RegX) && RegValIsKnown (RI->In.RegY) && !RegAXUsed (S, I+1)) { /* Get the register values */ unsigned char A = (unsigned char) RI->In.RegA; unsigned char X = (unsigned char) RI->In.RegX; unsigned char Y = (unsigned char) RI->In.RegY; /* Setup other variables */ CodeEntry* N; unsigned IP = I + 1; /* Insertion point */ /* Replace the store. We will not remove the loads, since this is * too complex and will be done by other optimizer steps. */ N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (A), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); /* Check if we can store one of the other bytes */ if (A != X) { N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (X), 0, E->LI); CS_InsertEntry (S, N, IP++); } N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+1), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); /* Remove the call */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptStore3 (CodeSeg* S) /* Search for a call to steaxysp. If the eax register is not used later, and * the value is constant, just use the A register and store directly into the * stack. */ { unsigned I; unsigned Changes = 0; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { /* Get next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Get the input registers */ const RegInfo* RI = E->RI; /* Check for the call */ if (CE_IsCallTo (E, "steaxysp") && RegValIsKnown (RI->In.RegA) && RegValIsKnown (RI->In.RegX) && RegValIsKnown (RI->In.RegY) && RegValIsKnown (RI->In.SRegLo) && RegValIsKnown (RI->In.SRegHi) && !RegEAXUsed (S, I+1)) { /* Get the register values */ unsigned char A = (unsigned char) RI->In.RegA; unsigned char X = (unsigned char) RI->In.RegX; unsigned char Y = (unsigned char) RI->In.RegY; unsigned char L = (unsigned char) RI->In.SRegLo; unsigned char H = (unsigned char) RI->In.SRegHi; /* Setup other variables */ unsigned Done = 0; CodeEntry* N; unsigned IP = I + 1; /* Insertion point */ /* Replace the store. We will not remove the loads, since this is * too complex and will be done by other optimizer steps. */ N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (A), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x01; /* Check if we can store one of the other bytes */ if (A == X && (Done & 0x02) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+1), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x02; } if (A == L && (Done & 0x04) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+2), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x04; } if (A == H && (Done & 0x08) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+3), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x08; } /* Store the second byte */ if ((Done & 0x02) == 0) { N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (X), 0, E->LI); CS_InsertEntry (S, N, IP++); N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+1), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x02; } /* Check if we can store one of the other bytes */ if (X == L && (Done & 0x04) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+2), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x04; } if (X == H && (Done & 0x08) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+3), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x08; } /* Store the third byte */ if ((Done & 0x04) == 0) { N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (L), 0, E->LI); CS_InsertEntry (S, N, IP++); N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+2), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x04; } /* Check if we can store one of the other bytes */ if (L == H && (Done & 0x08) == 0) { N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+3), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x08; } /* Store the fourth byte */ if ((Done & 0x08) == 0) { N = NewCodeEntry (OP65_LDA, AM65_IMM, MakeHexArg (H), 0, E->LI); CS_InsertEntry (S, N, IP++); N = NewCodeEntry (OP65_LDY, AM65_IMM, MakeHexArg (Y+3), 0, E->LI); CS_InsertEntry (S, N, IP++); InsertStore (S, &IP, E->LI); Done |= 0x08; } /* Remove the call */ CS_DelEntry (S, I); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptStore4 (CodeSeg* S) /* Search for the sequence * * sta xx * stx yy * lda xx * ldx yy * * and remove the useless load, provided that the next insn doesn't use flags * from the load. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_STA && (L[0]->AM == AM65_ABS || L[0]->AM == AM65_ZP) && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 4) && L[1]->OPC == OP65_STX && L[1]->AM == L[0]->AM && L[2]->OPC == OP65_LDA && L[2]->AM == L[0]->AM && L[3]->OPC == OP65_LDX && L[3]->AM == L[1]->AM && strcmp (L[0]->Arg, L[2]->Arg) == 0 && strcmp (L[1]->Arg, L[3]->Arg) == 0 && !CE_UseLoadFlags (L[4])) { /* Register has already the correct value, remove the loads */ CS_DelEntries (S, I+2, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptStore5 (CodeSeg* S) /* Search for the sequence * * lda foo * ldx bar * sta something * stx something-else * * and replace it by * * lda foo * sta something * lda bar * sta something-else * * if X is not used later. This replacement doesn't save any cycles or bytes, * but it keeps the value of X, which may be reused later. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && !CS_RangeHasLabel (S, I+1, 3) && CS_GetEntries (S, L+1, I+1, 3) && L[1]->OPC == OP65_LDX && L[2]->OPC == OP65_STA && L[3]->OPC == OP65_STX && !RegXUsed (S, I+4)) { CodeEntry* X; /* Insert the code after the sequence */ X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+4); X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+5); /* Delete the old code */ CS_DelEntry (S, I+3); CS_DelEntry (S, I+1); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
873
./cc65/src/cc65/coptptrload.c
/*****************************************************************************/ /* */ /* coptptrload.c */ /* */ /* Optimize loads through pointers */ /* */ /* */ /* */ /* (C) 2001-2009 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "xmalloc.h" /* cc65 */ #include "codeent.h" #include "codeinfo.h" #include "coptptrload.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned OptPtrLoad1 (CodeSeg* S) /* Search for the sequence: * * clc * adc xxx * tay * txa * adc yyy * tax * tya * ldy #$00 * jsr ldauidx * * and replace it by: * * sta ptr1 * txa * clc * adc yyy * sta ptr1+1 * ldy xxx * ldx #$00 * lda (ptr1),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[9]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_CLC && CS_GetEntries (S, L+1, I+1, 8) && L[1]->OPC == OP65_ADC && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP || L[1]->AM == AM65_IMM) && L[2]->OPC == OP65_TAY && L[3]->OPC == OP65_TXA && L[4]->OPC == OP65_ADC && L[5]->OPC == OP65_TAX && L[6]->OPC == OP65_TYA && L[7]->OPC == OP65_LDY && CE_IsKnownImm (L[7], 0) && CE_IsCallTo (L[8], "ldauidx") && !CS_RangeHasLabel (S, I+1, 8)) { CodeEntry* X; CodeEntry* P; /* Track the insertion point */ unsigned IP = I+9; /* sta ptr1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[2]->LI); CS_InsertEntry (S, X, IP++); /* If the instruction before the clc is a ldx, replace the * txa by an lda with the same location of the ldx. Otherwise * transfer the value in X to A. */ if ((P = CS_GetPrevEntry (S, I)) != 0 && P->OPC == OP65_LDX && !CE_HasLabel (P)) { X = NewCodeEntry (OP65_LDA, P->AM, P->Arg, 0, P->LI); } else { X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, L[3]->LI); } CS_InsertEntry (S, X, IP++); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* adc yyy */ X = NewCodeEntry (OP65_ADC, L[4]->AM, L[4]->Arg, 0, L[4]->LI); CS_InsertEntry (S, X, IP++); /* sta ptr1+1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1+1", 0, L[5]->LI); CS_InsertEntry (S, X, IP++); /* ldy xxx */ X = NewCodeEntry (OP65_LDY, L[1]->AM, L[1]->Arg, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[8]->LI); CS_InsertEntry (S, X, IP++); /* Remove the old instructions */ CS_DelEntries (S, I, 9); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad2 (CodeSeg* S) /* Search for the sequence: * * adc xxx * pha * txa * iny * adc yyy * tax * pla * ldy * jsr ldauidx * * and replace it by: * * adc xxx * sta ptr1 * txa * iny * adc yyy * sta ptr1+1 * ldy * ldx #$00 * lda (ptr1),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[9]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_ADC && CS_GetEntries (S, L+1, I+1, 8) && L[1]->OPC == OP65_PHA && L[2]->OPC == OP65_TXA && L[3]->OPC == OP65_INY && L[4]->OPC == OP65_ADC && L[5]->OPC == OP65_TAX && L[6]->OPC == OP65_PLA && L[7]->OPC == OP65_LDY && CE_IsCallTo (L[8], "ldauidx") && !CS_RangeHasLabel (S, I+1, 8)) { CodeEntry* X; /* Store the low byte and remove the PHA instead */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+1); /* Store the high byte */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1+1", 0, L[4]->LI); CS_InsertEntry (S, X, I+6); /* Load high and low byte */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[6]->LI); CS_InsertEntry (S, X, I+10); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[6]->LI); CS_InsertEntry (S, X, I+11); /* Delete the old code */ CS_DelEntry (S, I+12); /* jsr ldauidx */ CS_DelEntry (S, I+8); /* pla */ CS_DelEntry (S, I+7); /* tax */ CS_DelEntry (S, I+2); /* pha */ /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad3 (CodeSeg* S) /* Search for the sequence: * * lda #<(label+0) * ldx #>(label+0) * clc * adc xxx * bcc L * inx * L: ldy #$00 * jsr ldauidx * * and replace it by: * * ldy xxx * ldx #$00 * lda label,y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[8]; unsigned Len; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && L[0]->AM == AM65_IMM && CS_GetEntries (S, L+1, I+1, 7) && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_IMM && L[2]->OPC == OP65_CLC && L[3]->OPC == OP65_ADC && (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP) && (L[4]->OPC == OP65_BCC || L[4]->OPC == OP65_JCC) && L[4]->JumpTo != 0 && L[4]->JumpTo->Owner == L[6] && L[5]->OPC == OP65_INX && L[6]->OPC == OP65_LDY && CE_IsKnownImm (L[6], 0) && CE_IsCallTo (L[7], "ldauidx") && !CS_RangeHasLabel (S, I+1, 5) && !CE_HasLabel (L[7]) && /* Check the label last because this is quite costly */ (Len = strlen (L[0]->Arg)) > 3 && L[0]->Arg[0] == '<' && L[0]->Arg[1] == '(' && strlen (L[1]->Arg) == Len && L[1]->Arg[0] == '>' && memcmp (L[0]->Arg+1, L[1]->Arg+1, Len-1) == 0) { CodeEntry* X; char* Label; /* We will create all the new stuff behind the current one so * we keep the line references. */ X = NewCodeEntry (OP65_LDY, L[3]->AM, L[3]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+8); X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[0]->LI); CS_InsertEntry (S, X, I+9); Label = memcpy (xmalloc (Len-2), L[0]->Arg+2, Len-3); Label[Len-3] = '\0'; X = NewCodeEntry (OP65_LDA, AM65_ABSY, Label, 0, L[0]->LI); CS_InsertEntry (S, X, I+10); xfree (Label); /* Remove the old code */ CS_DelEntries (S, I, 8); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad4 (CodeSeg* S) /* Search for the sequence: * * lda #<(label+0) * ldx #>(label+0) * ldy #$xx * clc * adc (sp),y * bcc L * inx * L: ldy #$00 * jsr ldauidx * * and replace it by: * * ldy #$xx * lda (sp),y * tay * ldx #$00 * lda label,y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[9]; unsigned Len; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && L[0]->AM == AM65_IMM && CS_GetEntries (S, L+1, I+1, 8) && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_IMM && !CE_HasLabel (L[1]) && L[2]->OPC == OP65_LDY && CE_IsConstImm (L[2]) && !CE_HasLabel (L[2]) && L[3]->OPC == OP65_CLC && !CE_HasLabel (L[3]) && L[4]->OPC == OP65_ADC && L[4]->AM == AM65_ZP_INDY && !CE_HasLabel (L[4]) && (L[5]->OPC == OP65_BCC || L[5]->OPC == OP65_JCC) && L[5]->JumpTo != 0 && L[5]->JumpTo->Owner == L[7] && !CE_HasLabel (L[5]) && L[6]->OPC == OP65_INX && !CE_HasLabel (L[6]) && L[7]->OPC == OP65_LDY && CE_IsKnownImm (L[7], 0) && CE_IsCallTo (L[8], "ldauidx") && !CE_HasLabel (L[8]) && /* Check the label last because this is quite costly */ (Len = strlen (L[0]->Arg)) > 3 && L[0]->Arg[0] == '<' && L[0]->Arg[1] == '(' && strlen (L[1]->Arg) == Len && L[1]->Arg[0] == '>' && memcmp (L[0]->Arg+1, L[1]->Arg+1, Len-1) == 0) { CodeEntry* X; char* Label; /* Add the lda */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[4]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+3); /* Add the tay */ X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); /* Add the ldx */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[0]->LI); CS_InsertEntry (S, X, I+5); /* Add the lda */ Label = memcpy (xmalloc (Len-2), L[0]->Arg+2, Len-3); Label[Len-3] = '\0'; X = NewCodeEntry (OP65_LDA, AM65_ABSY, Label, 0, L[0]->LI); CS_InsertEntry (S, X, I+6); xfree (Label); /* Remove the old code */ CS_DelEntries (S, I, 2); CS_DelEntries (S, I+5, 6); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad5 (CodeSeg* S) /* Search for the sequence: * * jsr pushax * ldx #$00 * lda yyy * jsr tosaddax * ldy #$00 * jsr ldauidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy yyy * ldx #$00 * lda (ptr1),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[6]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "pushax") && CS_GetEntries (S, L+1, I+1, 5) && L[1]->OPC == OP65_LDX && CE_IsKnownImm (L[1], 0) && L[2]->OPC == OP65_LDA && (L[2]->AM == AM65_ABS || L[2]->AM == AM65_ZP || L[2]->AM == AM65_IMM) && CE_IsCallTo (L[3], "tosaddax") && L[4]->OPC == OP65_LDY && CE_IsKnownImm (L[4], 0) && CE_IsCallTo (L[5], "ldauidx") && !CS_RangeHasLabel (S, I+1, 5)) { CodeEntry* X; /* sta ptr1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+6); /* stx ptr1+1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI); CS_InsertEntry (S, X, I+7); /* ldy yyy */ X = NewCodeEntry (OP65_LDY, L[2]->AM, L[2]->Arg, 0, L[2]->LI); CS_InsertEntry (S, X, I+8); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[5]->LI); CS_InsertEntry (S, X, I+9); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[5]->LI); CS_InsertEntry (S, X, I+10); /* Remove the old code */ CS_DelEntries (S, I, 6); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad6 (CodeSeg* S) /* Search for the sequence: * * jsr pushax * ldy #xxx * ldx #$00 * lda (sp),y * jsr tosaddax * ldy #$00 * jsr ldauidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy #xxx-2 * lda (sp),y * tay * ldx #$00 * lda (ptr1),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[7]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (CE_IsCallTo (L[0], "pushax") && CS_GetEntries (S, L+1, I+1, 6) && L[1]->OPC == OP65_LDY && CE_IsConstImm (L[1]) && L[1]->Num >= 2 && L[2]->OPC == OP65_LDX && CE_IsKnownImm (L[2], 0) && L[3]->OPC == OP65_LDA && L[3]->AM == AM65_ZP_INDY && CE_IsCallTo (L[4], "tosaddax") && L[5]->OPC == OP65_LDY && CE_IsKnownImm (L[5], 0) && CE_IsCallTo (L[6], "ldauidx") && !CS_RangeHasLabel (S, I+1, 6) && !RegYUsed (S, I+7)) { CodeEntry* X; const char* Arg; /* sta ptr1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+7); /* stx ptr1+1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI); CS_InsertEntry (S, X, I+8); /* ldy #xxx-2 */ Arg = MakeHexArg (L[1]->Num - 2); X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[1]->LI); CS_InsertEntry (S, X, I+9); /* lda (sp),y */ X = NewCodeEntry (OP65_LDA, L[3]->AM, L[3]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+10); /* tay */ X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+11); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[5]->LI); CS_InsertEntry (S, X, I+12); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[6]->LI); CS_InsertEntry (S, X, I+13); /* Remove the old code */ CS_DelEntries (S, I, 7); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad7 (CodeSeg* S) /* Search for the sequence: * * jsr aslax1/shlax1 * clc * adc xxx * tay * txa * adc yyy * tax * tya * ldy zzz * jsr ldaxidx * * and replace it by: * * stx tmp1 * asl a * rol tmp1 * clc * adc xxx * sta ptr1 * lda tmp1 * adc yyy * sta ptr1+1 * ldy zzz * lda (ptr1),y * tax * dey * lda (ptr1),y */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[10]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_JSR && (strcmp (L[0]->Arg, "aslax1") == 0 || strcmp (L[0]->Arg, "shlax1") == 0) && CS_GetEntries (S, L+1, I+1, 9) && L[1]->OPC == OP65_CLC && L[2]->OPC == OP65_ADC && L[3]->OPC == OP65_TAY && L[4]->OPC == OP65_TXA && L[5]->OPC == OP65_ADC && L[6]->OPC == OP65_TAX && L[7]->OPC == OP65_TYA && L[8]->OPC == OP65_LDY && CE_IsCallTo (L[9], "ldaxidx") && !CS_RangeHasLabel (S, I+1, 9)) { CodeEntry* X; /* Track the insertion point */ unsigned IP = I + 10; /* If X is zero on entry to aslax1, we can generate: * * asl a * bcc L1 * inx * L1: clc * * instead of the code above. "lda tmp1" needs to be changed * to "txa" in this case. */ int ShortCode = (L[0]->RI->In.RegX == 0); if (ShortCode) { CodeLabel* Lab; /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* Generate clc first, since we need the label */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, IP); /* Get the label */ Lab = CS_GenLabel (S, X); /* bcc Lab */ X = NewCodeEntry (OP65_BCC, AM65_BRA, Lab->Name, Lab, L[0]->LI); CS_InsertEntry (S, X, IP++); /* inx */ X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* Skip the clc insn */ ++IP; } else { /* stx tmp1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* asl a */ X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* rol tmp1 */ X = NewCodeEntry (OP65_ROL, AM65_ZP, "tmp1", 0, L[0]->LI); CS_InsertEntry (S, X, IP++); /* clc */ X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, IP++); } /* adc xxx */ X = NewCodeEntry (L[2]->OPC, L[2]->AM, L[2]->Arg, 0, L[2]->LI); CS_InsertEntry (S, X, IP++); /* sta ptr1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[9]->LI); CS_InsertEntry (S, X, IP++); if (ShortCode) { /* txa */ X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, L[4]->LI); } else { /* lda tmp1 */ X = NewCodeEntry (OP65_LDA, AM65_ZP, "tmp1", 0, L[4]->LI); } CS_InsertEntry (S, X, IP++); /* adc xxx */ X = NewCodeEntry (L[5]->OPC, L[5]->AM, L[5]->Arg, 0, L[5]->LI); CS_InsertEntry (S, X, IP++); /* sta ptr1+1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1+1", 0, L[9]->LI); CS_InsertEntry (S, X, IP++); /* ldy zzz */ X = NewCodeEntry (L[8]->OPC, L[8]->AM, L[8]->Arg, 0, L[8]->LI); CS_InsertEntry (S, X, IP++); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[9]->LI); CS_InsertEntry (S, X, IP++); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[9]->LI); CS_InsertEntry (S, X, IP++); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[9]->LI); CS_InsertEntry (S, X, IP++); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[9]->LI); CS_InsertEntry (S, X, IP++); /* Remove the old code */ CS_DelEntries (S, I, 10); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad11 (CodeSeg* S) /* Search for the sequence: * * clc * adc xxx * bcc L * inx * L: ldy #$00 * jsr ldauidx * * and replace it by: * * ldy xxx * sta ptr1 * stx ptr1+1 * ldx #$00 * lda (ptr1),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[6]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_CLC && CS_GetEntries (S, L+1, I+1, 5) && L[1]->OPC == OP65_ADC && (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP || L[1]->AM == AM65_IMM) && (L[2]->OPC == OP65_BCC || L[2]->OPC == OP65_JCC) && L[2]->JumpTo != 0 && L[2]->JumpTo->Owner == L[4] && L[3]->OPC == OP65_INX && L[4]->OPC == OP65_LDY && CE_IsKnownImm (L[4], 0) && CE_IsCallTo (L[5], "ldauidx") && !CS_RangeHasLabel (S, I+1, 3) && !CE_HasLabel (L[5])) { CodeEntry* X; /* We will create all the new stuff behind the current one so * we keep the line references. */ X = NewCodeEntry (OP65_LDY, L[1]->AM, L[1]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+6); /* sta ptr1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+7); /* stx ptr1+1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI); CS_InsertEntry (S, X, I+8); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[0]->LI); CS_InsertEntry (S, X, I+9); X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+10); /* Remove the old code */ CS_DelEntries (S, I, 6); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad12 (CodeSeg* S) /* Search for the sequence: * * lda regbank+n * ldx regbank+n+1 * sta regsave * stx regsave+1 * clc * adc #$01 * bcc L0005 * inx * L: sta regbank+n * stx regbank+n+1 * lda regsave * ldx regsave+1 * ldy #$00 * jsr ldauidx * * and replace it by: * * ldy #$00 * ldx #$00 * lda (regbank+n),y * inc regbank+n * bne L1 * inc regbank+n+1 * L1: tay <- only if flags are used * * This function must execute before OptPtrLoad7! * */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[15]; unsigned Len; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && L[0]->AM == AM65_ZP && strncmp (L[0]->Arg, "regbank+", 8) == 0 && (Len = strlen (L[0]->Arg)) > 0 && CS_GetEntries (S, L+1, I+1, 14) && !CS_RangeHasLabel (S, I+1, 7) && !CS_RangeHasLabel (S, I+9, 5) && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_ZP && strncmp (L[1]->Arg, L[0]->Arg, Len) == 0 && strcmp (L[1]->Arg+Len, "+1") == 0 && L[2]->OPC == OP65_STA && L[2]->AM == AM65_ZP && strcmp (L[2]->Arg, "regsave") == 0 && L[3]->OPC == OP65_STX && L[3]->AM == AM65_ZP && strcmp (L[3]->Arg, "regsave+1") == 0 && L[4]->OPC == OP65_CLC && L[5]->OPC == OP65_ADC && CE_IsKnownImm (L[5], 1) && L[6]->OPC == OP65_BCC && L[6]->JumpTo != 0 && L[6]->JumpTo->Owner == L[8] && L[7]->OPC == OP65_INX && L[8]->OPC == OP65_STA && L[8]->AM == AM65_ZP && strcmp (L[8]->Arg, L[0]->Arg) == 0 && L[9]->OPC == OP65_STX && L[9]->AM == AM65_ZP && strcmp (L[9]->Arg, L[1]->Arg) == 0 && L[10]->OPC == OP65_LDA && L[10]->AM == AM65_ZP && strcmp (L[10]->Arg, "regsave") == 0 && L[11]->OPC == OP65_LDX && L[11]->AM == AM65_ZP && strcmp (L[11]->Arg, "regsave+1") == 0 && L[12]->OPC == OP65_LDY && CE_IsConstImm (L[12]) && CE_IsCallTo (L[13], "ldauidx")) { CodeEntry* X; CodeLabel* Label; /* Check if the instruction following the sequence uses the flags * set by the load. If so, insert a test of the value in the * accumulator. */ if (CE_UseLoadFlags (L[14])) { X = NewCodeEntry (OP65_TAY, AM65_IMP, 0, 0, L[13]->LI); CS_InsertEntry (S, X, I+14); } /* Attach a label to L[14]. This may be either the just inserted * instruction, or the one following the sequence. */ Label = CS_GenLabel (S, L[14]); /* ldy #$xx */ X = NewCodeEntry (OP65_LDY, AM65_IMM, L[12]->Arg, 0, L[12]->LI); CS_InsertEntry (S, X, I+14); /* ldx #$xx */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[13]->LI); CS_InsertEntry (S, X, I+15); /* lda (regbank+n),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[0]->Arg, 0, L[13]->LI); CS_InsertEntry (S, X, I+16); /* inc regbank+n */ X = NewCodeEntry (OP65_INC, AM65_ZP, L[0]->Arg, 0, L[5]->LI); CS_InsertEntry (S, X, I+17); /* bne ... */ X = NewCodeEntry (OP65_BNE, AM65_BRA, Label->Name, Label, L[6]->LI); CS_InsertEntry (S, X, I+18); /* inc regbank+n+1 */ X = NewCodeEntry (OP65_INC, AM65_ZP, L[1]->Arg, 0, L[7]->LI); CS_InsertEntry (S, X, I+19); /* Delete the old code */ CS_DelEntries (S, I, 14); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad13 (CodeSeg* S) /* Search for the sequence: * * lda zp * ldx zp+1 * ldy xx * jsr ldauidx * * and replace it by: * * ldy xx * ldx #$00 * lda (zp),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[4]; unsigned Len; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && L[0]->AM == AM65_ZP && CS_GetEntries (S, L+1, I+1, 3) && !CS_RangeHasLabel (S, I+1, 3) && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_ZP && (Len = strlen (L[0]->Arg)) > 0 && strncmp (L[0]->Arg, L[1]->Arg, Len) == 0 && strcmp (L[1]->Arg + Len, "+1") == 0 && L[2]->OPC == OP65_LDY && CE_IsCallTo (L[3], "ldauidx")) { CodeEntry* X; /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI); CS_InsertEntry (S, X, I+3); /* lda (zp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[0]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+4); /* Remove the old code */ CS_DelEntry (S, I+5); CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad14 (CodeSeg* S) /* Search for the sequence: * * lda zp * ldx zp+1 * (anything that doesn't change a/x) * ldy xx * jsr ldauidx * * and replace it by: * * lda zp * ldx zp+1 * (anything that doesn't change a/x) * ldy xx * ldx #$00 * lda (zp),y * */ { unsigned Changes = 0; unsigned I; /* Walk over the entries */ I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; unsigned Len; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDA && L[0]->AM == AM65_ZP && CS_GetEntries (S, L+1, I+1, 4) && !CS_RangeHasLabel (S, I+1, 4) && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_ZP && (Len = strlen (L[0]->Arg)) > 0 && strncmp (L[0]->Arg, L[1]->Arg, Len) == 0 && strcmp (L[1]->Arg + Len, "+1") == 0 && (L[2]->Chg & REG_AX) == 0 && L[3]->OPC == OP65_LDY && CE_IsCallTo (L[4], "ldauidx")) { CodeEntry* X; /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI); CS_InsertEntry (S, X, I+5); /* lda (zp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[0]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+6); /* Remove the old code */ CS_DelEntry (S, I+4); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad15 (CodeSeg* S) /* Search for the sequence: * * lda zp * ldx zp+1 * jsr pushax <- optional * ldy xx * jsr ldaxidx * * and replace it by: * * lda zp <- only if * ldx zp+1 <- call to * jsr pushax <- pushax present * ldy xx * lda (zp),y * tax * dey * lda (zp),y */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[5]; unsigned Len; /* Check for the start of the sequence */ if (CS_GetEntries (S, L, I, 3) && L[0]->OPC == OP65_LDA && L[0]->AM == AM65_ZP && L[1]->OPC == OP65_LDX && L[1]->AM == AM65_ZP && !CS_RangeHasLabel (S, I+1, 2) && (Len = strlen (L[0]->Arg)) > 0 && strncmp (L[0]->Arg, L[1]->Arg, Len) == 0 && strcmp (L[1]->Arg + Len, "+1") == 0) { unsigned PushAX = CE_IsCallTo (L[2], "pushax"); /* Check for the remainder of the sequence */ if (CS_GetEntries (S, L+3, I+3, 1 + PushAX) && !CS_RangeHasLabel (S, I+3, 1 + PushAX) && L[2+PushAX]->OPC == OP65_LDY && CE_IsCallTo (L[3+PushAX], "ldaxidx")) { CodeEntry* X; /* lda (zp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[0]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+PushAX+4); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+PushAX+5); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[3]->LI); CS_InsertEntry (S, X, I+PushAX+6); /* lda (zp),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, L[0]->Arg, 0, L[3]->LI); CS_InsertEntry (S, X, I+PushAX+7); /* Remove the old code */ CS_DelEntry (S, I+PushAX+3); if (!PushAX) { CS_DelEntries (S, I, 2); } /* Remember, we had changes */ ++Changes; } } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad16 (CodeSeg* S) /* Search for the sequence * * ldy ... * jsr ldauidx * * and replace it by: * * stx ptr1+1 * sta ptr1 * ldy ... * ldx #$00 * lda (ptr1),y * * This step must be executed *after* OptPtrLoad1! */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CS_GetEntries (S, L+1, I+1, 1) && CE_IsCallTo (L[1], "ldauidx") && !CE_HasLabel (L[1])) { CodeEntry* X; /* stx ptr1+1 */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[1]->LI); CS_InsertEntry (S, X, I+2); /* sta ptr1 */ X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[1]->LI); CS_InsertEntry (S, X, I+3); /* ldy ... */ X = NewCodeEntry (L[0]->OPC, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); /* ldx #$00 */ X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[1]->LI); CS_InsertEntry (S, X, I+5); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[1]->LI); CS_InsertEntry (S, X, I+6); /* Delete the old code */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; } unsigned OptPtrLoad17 (CodeSeg* S) /* Search for the sequence * * ldy ... * jsr ldaxidx * * and replace it by: * * sta ptr1 * stx ptr1+1 * ldy ... * lda (ptr1),y * tax * dey * lda (ptr1),y * * This step must be executed *after* OptPtrLoad9! While code size increases * by more than 200%, inlining will greatly improve visibility for the * optimizer, so often part of the code gets improved later. So we will mark * the step with less than 200% so it gets executed when -Oi is in effect. */ { unsigned Changes = 0; /* Walk over the entries */ unsigned I = 0; while (I < CS_GetEntryCount (S)) { CodeEntry* L[2]; /* Get next entry */ L[0] = CS_GetEntry (S, I); /* Check for the sequence */ if (L[0]->OPC == OP65_LDY && CS_GetEntries (S, L+1, I+1, 1) && CE_IsCallTo (L[1], "ldaxidx") && !CE_HasLabel (L[1])) { CodeEntry* X; /* Store the high byte */ X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI); CS_InsertEntry (S, X, I+2); /* Store the low byte */ X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI); CS_InsertEntry (S, X, I+3); /* ldy ... */ X = NewCodeEntry (L[0]->OPC, L[0]->AM, L[0]->Arg, 0, L[0]->LI); CS_InsertEntry (S, X, I+4); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[1]->LI); CS_InsertEntry (S, X, I+5); /* tax */ X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, I+6); /* dey */ X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[1]->LI); CS_InsertEntry (S, X, I+7); /* lda (ptr1),y */ X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "ptr1", 0, L[1]->LI); CS_InsertEntry (S, X, I+8); /* Delete original sequence */ CS_DelEntries (S, I, 2); /* Remember, we had changes */ ++Changes; } /* Next entry */ ++I; } /* Return the number of changes made */ return Changes; }
874
./cc65/src/cc65/codelab.c
/*****************************************************************************/ /* */ /* codelab.c */ /* */ /* Code label structure */ /* */ /* */ /* */ /* (C) 2001-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "xmalloc.h" /* cc65 */ #include "codeent.h" #include "codelab.h" #include "output.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ CodeLabel* NewCodeLabel (const char* Name, unsigned Hash) /* Create a new code label, initialize and return it */ { /* Allocate memory */ CodeLabel* L = xmalloc (sizeof (CodeLabel)); /* Initialize the fields */ L->Next = 0; L->Name = xstrdup (Name); L->Hash = Hash; L->Owner = 0; InitCollection (&L->JumpFrom); /* Return the new label */ return L; } void FreeCodeLabel (CodeLabel* L) /* Free the given code label */ { /* Free the name */ xfree (L->Name); /* Free the collection */ DoneCollection (&L->JumpFrom); /* Delete the struct */ xfree (L); } void CL_AddRef (CodeLabel* L, struct CodeEntry* E) /* Let the CodeEntry E reference the label L */ { /* The insn at E jumps to this label */ E->JumpTo = L; /* Replace the code entry argument with the name of the new label */ CE_SetArg (E, L->Name); /* Remember that in the label */ CollAppend (&L->JumpFrom, E); } void CL_MoveRefs (CodeLabel* OldLabel, CodeLabel* NewLabel) /* Move all references to OldLabel to point to NewLabel. OldLabel will have no * more references on return. */ { /* Walk through all instructions referencing the old label */ unsigned Count = CL_GetRefCount (OldLabel); while (Count--) { /* Get the instruction that references the old label */ CodeEntry* E = CL_GetRef (OldLabel, Count); /* Change the reference to the new label */ CHECK (E->JumpTo == OldLabel); CL_AddRef (NewLabel, E); } /* There are no more references to the old label */ CollDeleteAll (&OldLabel->JumpFrom); } void CL_Output (const CodeLabel* L) /* Output the code label to the output file */ { WriteOutput ("%s:", L->Name); if (strlen (L->Name) > 6) { /* Label is too long, add a linefeed */ WriteOutput ("\n"); } }
875
./cc65/src/cc65/codeseg.c
/*****************************************************************************/ /* */ /* codeseg.c */ /* */ /* Code segment structure */ /* */ /* */ /* */ /* (C) 2001-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <ctype.h> /* common */ #include "chartype.h" #include "check.h" #include "debugflag.h" #include "global.h" #include "hashfunc.h" #include "strbuf.h" #include "strutil.h" #include "xmalloc.h" /* cc65 */ #include "asmlabel.h" #include "codeent.h" #include "codeinfo.h" #include "codeseg.h" #include "datatype.h" #include "error.h" #include "global.h" #include "ident.h" #include "output.h" #include "symentry.h" /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static void CS_PrintFunctionHeader (const CodeSeg* S) /* Print a comment with the function signature to the output file */ { /* Get the associated function */ const SymEntry* Func = S->Func; /* If this is a global code segment, do nothing */ if (Func) { WriteOutput ("; ---------------------------------------------------------------\n" "; "); PrintFuncSig (OutputFile, Func->Name, Func->Type); WriteOutput ("\n" "; ---------------------------------------------------------------\n" "\n"); } } static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E) /* Move all labels from the label pool to the given entry and remove them * from the pool. */ { /* Transfer the labels if we have any */ unsigned I; unsigned LabelCount = CollCount (&S->Labels); for (I = 0; I < LabelCount; ++I) { /* Get the label */ CodeLabel* L = CollAt (&S->Labels, I); /* Attach it to the entry */ CE_AttachLabel (E, L); } /* Delete the transfered labels */ CollDeleteAll (&S->Labels); } static void CS_MoveLabelsToPool (CodeSeg* S, CodeEntry* E) /* Move the labels of the code entry E to the label pool of the code segment */ { unsigned LabelCount = CE_GetLabelCount (E); while (LabelCount--) { CodeLabel* L = CE_GetLabel (E, LabelCount); L->Owner = 0; CollAppend (&S->Labels, L); } CollDeleteAll (&E->Labels); } static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash) /* Find the label with the given name. Return the label or NULL if not found */ { /* Get the first hash chain entry */ CodeLabel* L = S->LabelHash[Hash]; /* Search the list */ while (L) { if (strcmp (Name, L->Name) == 0) { /* Found */ break; } L = L->Next; } return L; } static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash) /* Create a new label and insert it into the label hash table */ { /* Create a new label */ CodeLabel* L = NewCodeLabel (Name, Hash); /* Enter the label into the hash table */ L->Next = S->LabelHash[L->Hash]; S->LabelHash[L->Hash] = L; /* Return the new label */ return L; } static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L) /* Remove the given code label from the hash list */ { /* Get the first entry in the hash chain */ CodeLabel* List = S->LabelHash[L->Hash]; CHECK (List != 0); /* First, remove the label from the hash chain */ if (List == L) { /* First entry in hash chain */ S->LabelHash[L->Hash] = L->Next; } else { /* Must search through the chain */ while (List->Next != L) { /* If we've reached the end of the chain, something is *really* wrong */ CHECK (List->Next != 0); /* Next entry */ List = List->Next; } /* The next entry is the one, we have been searching for */ List->Next = L->Next; } } /*****************************************************************************/ /* Functions for parsing instructions */ /*****************************************************************************/ static const char* SkipSpace (const char* S) /* Skip white space and return an updated pointer */ { while (IsSpace (*S)) { ++S; } return S; } static const char* ReadToken (const char* L, const char* Term, char* Buf, unsigned BufSize) /* Read the next token into Buf, return the updated line pointer. The * token is terminated by one of the characters given in term. */ { /* Read/copy the token */ unsigned I = 0; unsigned ParenCount = 0; while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) { if (I < BufSize-1) { Buf[I] = *L; } else if (I == BufSize-1) { /* Cannot store this character, this is an input error (maybe * identifier too long or similar). */ Error ("ASM code error: syntax error"); } ++I; if (*L == ')') { --ParenCount; } else if (*L == '(') { ++ParenCount; } ++L; } /* Terminate the buffer contents */ Buf[I] = '\0'; /* Return the updated line pointer */ return L; } static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L) /* Parse an instruction nnd generate a code entry from it. If the line contains * errors, output an error message and return NULL. * For simplicity, we don't accept the broad range of input a "real" assembler * does. The instruction and the argument are expected to be separated by * white space, for example. */ { char Mnemo[IDENTSIZE+10]; const OPCDesc* OPC; am_t AM = 0; /* Initialize to keep gcc silent */ char Arg[IDENTSIZE+10]; char Reg; CodeEntry* E; CodeLabel* Label; /* Read the first token and skip white space after it */ L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo))); /* Check if we have a label */ if (*L == ':') { /* Skip the colon and following white space */ L = SkipSpace (L+1); /* Add the label */ CS_AddLabel (S, Mnemo); /* If we have reached end of line, bail out, otherwise a mnemonic * may follow. */ if (*L == '\0') { return 0; } L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo))); } /* Try to find the opcode description for the mnemonic */ OPC = FindOP65 (Mnemo); /* If we didn't find the opcode, print an error and bail out */ if (OPC == 0) { Error ("ASM code error: %s is not a valid mnemonic", Mnemo); return 0; } /* Get the addressing mode */ Arg[0] = '\0'; switch (*L) { case '\0': /* Implicit or accu */ if (OPC->Info & OF_NOIMP) { AM = AM65_ACC; } else { AM = AM65_IMP; } break; case '#': /* Immidiate */ StrCopy (Arg, sizeof (Arg), L+1); AM = AM65_IMM; break; case '(': /* Indirect */ L = ReadToken (L+1, ",)", Arg, sizeof (Arg)); /* Check for errors */ if (*L == '\0') { Error ("ASM code error: syntax error"); return 0; } /* Check the different indirect modes */ if (*L == ',') { /* Expect zp x indirect */ L = SkipSpace (L+1); if (toupper (*L) != 'X') { Error ("ASM code error: `X' expected"); return 0; } L = SkipSpace (L+1); if (*L != ')') { Error ("ASM code error: `)' expected"); return 0; } L = SkipSpace (L+1); if (*L != '\0') { Error ("ASM code error: syntax error"); return 0; } AM = AM65_ZPX_IND; } else if (*L == ')') { /* zp indirect or zp indirect, y */ L = SkipSpace (L+1); if (*L == ',') { L = SkipSpace (L+1); if (toupper (*L) != 'Y') { Error ("ASM code error: `Y' expected"); return 0; } L = SkipSpace (L+1); if (*L != '\0') { Error ("ASM code error: syntax error"); return 0; } AM = AM65_ZP_INDY; } else if (*L == '\0') { AM = AM65_ZP_IND; } else { Error ("ASM code error: syntax error"); return 0; } } break; case 'a': case 'A': /* Accumulator? */ if (L[1] == '\0') { AM = AM65_ACC; break; } /* FALLTHROUGH */ default: /* Absolute, maybe indexed */ L = ReadToken (L, ",", Arg, sizeof (Arg)); if (*L == '\0') { /* Absolute, zeropage or branch */ if ((OPC->Info & OF_BRA) != 0) { /* Branch */ AM = AM65_BRA; } else if (GetZPInfo(Arg) != 0) { AM = AM65_ZP; } else { /* Check for subroutine call to local label */ if ((OPC->Info & OF_CALL) && IsLocalLabelName (Arg)) { Error ("ASM code error: " "Cannot use local label `%s' in subroutine call", Arg); } AM = AM65_ABS; } } else if (*L == ',') { /* Indexed */ L = SkipSpace (L+1); if (*L == '\0') { Error ("ASM code error: syntax error"); return 0; } else { Reg = toupper (*L); L = SkipSpace (L+1); if (Reg == 'X') { if (GetZPInfo(Arg) != 0) { AM = AM65_ZPX; } else { AM = AM65_ABSX; } } else if (Reg == 'Y') { AM = AM65_ABSY; } else { Error ("ASM code error: syntax error"); return 0; } if (*L != '\0') { Error ("ASM code error: syntax error"); return 0; } } } break; } /* If the instruction is a branch, check for the label and generate it * if it does not exist. This may lead to unused labels (if the label * is actually an external one) which are removed by the CS_MergeLabels * function later. */ Label = 0; if (AM == AM65_BRA) { /* Generate the hash over the label, then search for the label */ unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE; Label = CS_FindLabel (S, Arg, Hash); /* If we don't have the label, it's a forward ref - create it */ if (Label == 0) { /* Generate a new label */ Label = CS_NewCodeLabel (S, Arg, Hash); } } /* We do now have the addressing mode in AM. Allocate a new CodeEntry * structure and initialize it. */ E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI); /* Return the new code entry */ return E; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func) /* Create a new code segment, initialize and return it */ { unsigned I; const Type* RetType; /* Allocate memory */ CodeSeg* S = xmalloc (sizeof (CodeSeg)); /* Initialize the fields */ S->SegName = xstrdup (SegName); S->Func = Func; InitCollection (&S->Entries); InitCollection (&S->Labels); for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) { S->LabelHash[I] = 0; } /* If we have a function given, get the return type of the function. * Assume ANY return type besides void will use the A and X registers. */ if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) { if (SizeOf (RetType) == SizeOf (type_long)) { S->ExitRegs = REG_EAX; } else { S->ExitRegs = REG_AX; } } else { S->ExitRegs = REG_NONE; } /* Copy the global optimization settings */ S->Optimize = (unsigned char) IS_Get (&Optimize); S->CodeSizeFactor = (unsigned) IS_Get (&CodeSizeFactor); /* Return the new struct */ return S; } void CS_AddEntry (CodeSeg* S, struct CodeEntry* E) /* Add an entry to the given code segment */ { /* Transfer the labels if we have any */ CS_MoveLabelsToEntry (S, E); /* Add the entry to the list of code entries in this segment */ CollAppend (&S->Entries, E); } void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap) /* Add a line to the given code segment */ { const char* L; CodeEntry* E; char Token[IDENTSIZE+10]; /* Format the line */ StrBuf Buf = STATIC_STRBUF_INITIALIZER; SB_VPrintf (&Buf, Format, ap); /* Skip whitespace */ L = SkipSpace (SB_GetConstBuf (&Buf)); /* Check which type of instruction we have */ E = 0; /* Assume no insn created */ switch (*L) { case '\0': /* Empty line, just ignore it */ break; case ';': /* Comment or hint, ignore it for now */ break; case '.': /* Control instruction */ ReadToken (L, " \t", Token, sizeof (Token)); Error ("ASM code error: Pseudo instruction `%s' not supported", Token); break; default: E = ParseInsn (S, LI, L); break; } /* If we have a code entry, transfer the labels and insert it */ if (E) { CS_AddEntry (S, E); } /* Cleanup the string buffer */ SB_Done (&Buf); } void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...) /* Add a line to the given code segment */ { va_list ap; va_start (ap, Format); CS_AddVLine (S, LI, Format, ap); va_end (ap); } void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index) /* Insert the code entry at the index given. Following code entries will be * moved to slots with higher indices. */ { /* Insert the entry into the collection */ CollInsert (&S->Entries, E, Index); } void CS_DelEntry (CodeSeg* S, unsigned Index) /* Delete an entry from the code segment. This includes moving any associated * labels, removing references to labels and even removing the referenced labels * if the reference count drops to zero. * Note: Labels are moved forward if possible, that is, they are moved to the * next insn (not the preceeding one). */ { /* Get the code entry for the given index */ CodeEntry* E = CS_GetEntry (S, Index); /* If the entry has a labels, we have to move this label to the next insn. * If there is no next insn, move the label into the code segement label * pool. The operation is further complicated by the fact that the next * insn may already have a label. In that case change all reference to * this label and delete the label instead of moving it. */ unsigned Count = CE_GetLabelCount (E); if (Count > 0) { /* The instruction has labels attached. Check if there is a next * instruction. */ if (Index == CS_GetEntryCount (S)-1) { /* No next instruction, move to the codeseg label pool */ CS_MoveLabelsToPool (S, E); } else { /* There is a next insn, get it */ CodeEntry* N = CS_GetEntry (S, Index+1); /* Move labels to the next entry */ CS_MoveLabels (S, E, N); } } /* If this insn references a label, remove the reference. And, if the * the reference count for this label drops to zero, remove this label. */ if (E->JumpTo) { /* Remove the reference */ CS_RemoveLabelRef (S, E); } /* Delete the pointer to the insn */ CollDelete (&S->Entries, Index); /* Delete the instruction itself */ FreeCodeEntry (E); } void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count) /* Delete a range of code entries. This includes removing references to labels, * labels attached to the entries and so on. */ { /* Start deleting the entries from the rear, because this involves less * memory moving. */ while (Count--) { CS_DelEntry (S, Start + Count); } } void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos) /* Move a range of entries from one position to another. Start is the index * of the first entry to move, Count is the number of entries and NewPos is * the index of the target entry. The entry with the index Start will later * have the index NewPos. All entries with indices NewPos and above are * moved to higher indices. If the code block is moved to the end of the * current code, and if pending labels exist, these labels will get attached * to the first instruction of the moved block (the first one after the * current code end) */ { /* Transparently handle an empty range */ if (Count == 0) { return; } /* If NewPos is at the end of the code segment, move any labels from the * label pool to the first instruction of the moved range. */ if (NewPos == CS_GetEntryCount (S)) { CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start)); } /* Move the code block to the destination */ CollMoveMultiple (&S->Entries, Start, Count, NewPos); } struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index) /* Get the code entry preceeding the one with the index Index. If there is no * preceeding code entry, return NULL. */ { if (Index == 0) { /* This is the first entry */ return 0; } else { /* Previous entry available */ return CollAtUnchecked (&S->Entries, Index-1); } } struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index) /* Get the code entry following the one with the index Index. If there is no * following code entry, return NULL. */ { if (Index >= CollCount (&S->Entries)-1) { /* This is the last entry */ return 0; } else { /* Code entries left */ return CollAtUnchecked (&S->Entries, Index+1); } } int CS_GetEntries (CodeSeg* S, struct CodeEntry** List, unsigned Start, unsigned Count) /* Get Count code entries into List starting at index start. Return true if * we got the lines, return false if not enough lines were available. */ { /* Check if enough entries are available */ if (Start + Count > CollCount (&S->Entries)) { return 0; } /* Copy the entries */ while (Count--) { *List++ = CollAtUnchecked (&S->Entries, Start++); } /* We have the entries */ return 1; } unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E) /* Return the index of a code entry */ { int Index = CollIndex (&S->Entries, E); CHECK (Index >= 0); return Index; } int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count) /* Return true if any of the code entries in the given range has a label * attached. If the code segment does not span the given range, check the * possible span instead. */ { unsigned EntryCount = CS_GetEntryCount(S); /* Adjust count. We expect at least Start to be valid. */ CHECK (Start < EntryCount); if (Start + Count > EntryCount) { Count = EntryCount - Start; } /* Check each entry. Since we have validated the index above, we may * use the unchecked access function in the loop which is faster. */ while (Count--) { const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++); if (CE_HasLabel (E)) { return 1; } } /* No label in the complete range */ return 0; } CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name) /* Add a code label for the next instruction to follow */ { /* Calculate the hash from the name */ unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE; /* Try to find the code label if it does already exist */ CodeLabel* L = CS_FindLabel (S, Name, Hash); /* Did we find it? */ if (L) { /* We found it - be sure it does not already have an owner */ if (L->Owner) { Error ("ASM label `%s' is already defined", Name); return L; } } else { /* Not found - create a new one */ L = CS_NewCodeLabel (S, Name, Hash); } /* Safety. This call is quite costly, but safety is better */ if (CollIndex (&S->Labels, L) >= 0) { Error ("ASM label `%s' is already defined", Name); return L; } /* We do now have a valid label. Remember it for later */ CollAppend (&S->Labels, L); /* Return the label */ return L; } CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E) /* If the code entry E does already have a label, return it. Otherwise * create a new label, attach it to E and return it. */ { CodeLabel* L; if (CE_HasLabel (E)) { /* Get the label from this entry */ L = CE_GetLabel (E, 0); } else { /* Get a new name */ const char* Name = LocalLabelName (GetLocalLabel ()); /* Generate the hash over the name */ unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE; /* Create a new label */ L = CS_NewCodeLabel (S, Name, Hash); /* Attach this label to the code entry */ CE_AttachLabel (E, L); } /* Return the label */ return L; } void CS_DelLabel (CodeSeg* S, CodeLabel* L) /* Remove references from this label and delete it. */ { unsigned Count, I; /* First, remove the label from the hash chain */ CS_RemoveLabelFromHash (S, L); /* Remove references from insns jumping to this label */ Count = CollCount (&L->JumpFrom); for (I = 0; I < Count; ++I) { /* Get the insn referencing this label */ CodeEntry* E = CollAt (&L->JumpFrom, I); /* Remove the reference */ CE_ClearJumpTo (E); } CollDeleteAll (&L->JumpFrom); /* Remove the reference to the owning instruction if it has one. The * function may be called for a label without an owner when deleting * unfinished parts of the code. This is unfortunate since it allows * errors to slip through. */ if (L->Owner) { CollDeleteItem (&L->Owner->Labels, L); } /* All references removed, delete the label itself */ FreeCodeLabel (L); } void CS_MergeLabels (CodeSeg* S) /* Merge code labels. That means: For each instruction, remove all labels but * one and adjust references accordingly. */ { unsigned I; unsigned J; /* First, remove all labels from the label symbol table that don't have an * owner (this means that they are actually external labels but we didn't * know that previously since they may have also been forward references). */ for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) { /* Get the first label in this hash chain */ CodeLabel** L = &S->LabelHash[I]; while (*L) { if ((*L)->Owner == 0) { /* The label does not have an owner, remove it from the chain */ CodeLabel* X = *L; *L = X->Next; /* Cleanup any entries jumping to this label */ for (J = 0; J < CL_GetRefCount (X); ++J) { /* Get the entry referencing this label */ CodeEntry* E = CL_GetRef (X, J); /* And remove the reference. Do NOT call CE_ClearJumpTo * here, because this will also clear the label name, * which is not what we want. */ E->JumpTo = 0; } /* Print some debugging output */ if (Debug) { printf ("Removing unused global label `%s'", X->Name); } /* And free the label */ FreeCodeLabel (X); } else { /* Label is owned, point to next code label pointer */ L = &((*L)->Next); } } } /* Walk over all code entries */ for (I = 0; I < CS_GetEntryCount (S); ++I) { CodeLabel* RefLab; unsigned J; /* Get a pointer to the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* If this entry has zero labels, continue with the next one */ unsigned LabelCount = CE_GetLabelCount (E); if (LabelCount == 0) { continue; } /* We have at least one label. Use the first one as reference label. */ RefLab = CE_GetLabel (E, 0); /* Walk through the remaining labels and change references to these * labels to a reference to the one and only label. Delete the labels * that are no longer used. To increase performance, walk backwards * through the list. */ for (J = LabelCount-1; J >= 1; --J) { /* Get the next label */ CodeLabel* L = CE_GetLabel (E, J); /* Move all references from this label to the reference label */ CL_MoveRefs (L, RefLab); /* Remove the label completely. */ CS_DelLabel (S, L); } /* The reference label is the only remaining label. Check if there * are any references to this label, and delete it if this is not * the case. */ if (CollCount (&RefLab->JumpFrom) == 0) { /* Delete the label */ CS_DelLabel (S, RefLab); } } } void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New) /* Move all labels from Old to New. The routine will move the labels itself * if New does not have any labels, and move references if there is at least * a label for new. If references are moved, the old label is deleted * afterwards. */ { /* Get the number of labels to move */ unsigned OldLabelCount = CE_GetLabelCount (Old); /* Does the new entry have itself a label? */ if (CE_HasLabel (New)) { /* The new entry does already have a label - move references */ CodeLabel* NewLabel = CE_GetLabel (New, 0); while (OldLabelCount--) { /* Get the next label */ CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount); /* Move references */ CL_MoveRefs (OldLabel, NewLabel); /* Delete the label */ CS_DelLabel (S, OldLabel); } } else { /* The new entry does not have a label, just move them */ while (OldLabelCount--) { /* Move the label to the new entry */ CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New); } } } void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E) /* Remove the reference between E and the label it jumps to. The reference * will be removed on both sides and E->JumpTo will be 0 after that. If * the reference was the only one for the label, the label will get * deleted. */ { /* Get a pointer to the label and make sure it exists */ CodeLabel* L = E->JumpTo; CHECK (L != 0); /* Delete the entry from the label */ CollDeleteItem (&L->JumpFrom, E); /* The entry jumps no longer to L */ CE_ClearJumpTo (E); /* If there are no more references, delete the label */ if (CollCount (&L->JumpFrom) == 0) { CS_DelLabel (S, L); } } void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L) /* Change the reference of E to L instead of the current one. If this * was the only reference to the old label, the old label will get * deleted. */ { /* Get the old label */ CodeLabel* OldLabel = E->JumpTo; /* Be sure that code entry references a label */ PRECONDITION (OldLabel != 0); /* Remove the reference to our label */ CS_RemoveLabelRef (S, E); /* Use the new label */ CL_AddRef (L, E); } void CS_DelCodeRange (CodeSeg* S, unsigned First, unsigned Last) /* Delete all entries between first and last, both inclusive. The function * can only handle basic blocks (First is the only entry, Last the only exit) * and no open labels. It will call FAIL if any of these preconditions are * violated. */ { unsigned I; CodeEntry* FirstEntry; /* Do some sanity checks */ CHECK (First <= Last && Last < CS_GetEntryCount (S)); /* If Last is actually the last insn, call CS_DelCodeAfter instead, which * is more flexible in this case. */ if (Last == CS_GetEntryCount (S) - 1) { CS_DelCodeAfter (S, First); return; } /* Get the first entry and check if it has any labels. If it has, move * them to the insn following Last. If Last is the last insn of the code * segment, make them ownerless and move them to the label pool. */ FirstEntry = CS_GetEntry (S, First); if (CE_HasLabel (FirstEntry)) { /* Get the entry following last */ CodeEntry* FollowingEntry = CS_GetNextEntry (S, Last); if (FollowingEntry) { /* There is an entry after Last - move the labels */ CS_MoveLabels (S, FirstEntry, FollowingEntry); } else { /* Move the labels to the pool and clear the owner pointer */ CS_MoveLabelsToPool (S, FirstEntry); } } /* First pass: Delete all references to labels. If the reference count * for a label drops to zero, delete it. */ for (I = Last; I >= First; --I) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this entry has a label reference */ if (E->JumpTo) { /* If the label is a label in the label pool, this is an error */ CodeLabel* L = E->JumpTo; CHECK (CollIndex (&S->Labels, L) < 0); /* Remove the reference to the label */ CS_RemoveLabelRef (S, E); } } /* Second pass: Delete the instructions. If a label attached to an * instruction still has references, it must be references from outside * the deleted area, which is an error. */ for (I = Last; I >= First; --I) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this entry has a label attached */ CHECK (!CE_HasLabel (E)); /* Delete the pointer to the entry */ CollDelete (&S->Entries, I); /* Delete the entry itself */ FreeCodeEntry (E); } } void CS_DelCodeAfter (CodeSeg* S, unsigned Last) /* Delete all entries including the given one */ { /* Get the number of entries in this segment */ unsigned Count = CS_GetEntryCount (S); /* First pass: Delete all references to labels. If the reference count * for a label drops to zero, delete it. */ unsigned C = Count; while (Last < C--) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, C); /* Check if this entry has a label reference */ if (E->JumpTo) { /* If the label is a label in the label pool and this is the last * reference to the label, remove the label from the pool. */ CodeLabel* L = E->JumpTo; int Index = CollIndex (&S->Labels, L); if (Index >= 0 && CollCount (&L->JumpFrom) == 1) { /* Delete it from the pool */ CollDelete (&S->Labels, Index); } /* Remove the reference to the label */ CS_RemoveLabelRef (S, E); } } /* Second pass: Delete the instructions. If a label attached to an * instruction still has references, it must be references from outside * the deleted area. Don't delete the label in this case, just make it * ownerless and move it to the label pool. */ C = Count; while (Last < C--) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, C); /* Check if this entry has a label attached */ if (CE_HasLabel (E)) { /* Move the labels to the pool and clear the owner pointer */ CS_MoveLabelsToPool (S, E); } /* Delete the pointer to the entry */ CollDelete (&S->Entries, C); /* Delete the entry itself */ FreeCodeEntry (E); } } void CS_ResetMarks (CodeSeg* S, unsigned First, unsigned Last) /* Remove all user marks from the entries in the given range */ { while (First <= Last) { CE_ResetMark (CS_GetEntry (S, First++)); } } int CS_IsBasicBlock (CodeSeg* S, unsigned First, unsigned Last) /* Check if the given code segment range is a basic block. That is, check if * First is the only entrance and Last is the only exit. This means that no * jump/branch inside the block may jump to an insn below First or after(!) * Last, and that no insn may jump into this block from the outside. */ { unsigned I; /* Don't accept invalid ranges */ CHECK (First <= Last); /* First pass: Walk over the range and remove all marks from the entries */ CS_ResetMarks (S, First, Last); /* Second pass: Walk over the range checking all labels. Note: There may be * label on the first insn which is ok. */ I = First + 1; while (I <= Last) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this entry has one or more labels, if so, check which * entries jump to this label. */ unsigned LabelCount = CE_GetLabelCount (E); unsigned LabelIndex; for (LabelIndex = 0; LabelIndex < LabelCount; ++LabelIndex) { /* Get this label */ CodeLabel* L = CE_GetLabel (E, LabelIndex); /* Walk over all entries that jump to this label. Check for each * of the entries if it is out of the range. */ unsigned RefCount = CL_GetRefCount (L); unsigned RefIndex; for (RefIndex = 0; RefIndex < RefCount; ++RefIndex) { /* Get the code entry that jumps here */ CodeEntry* Ref = CL_GetRef (L, RefIndex); /* Walk over out complete range and check if we find the * refering entry. This is cheaper than using CS_GetEntryIndex, * because CS_GetEntryIndex will search the complete code * segment and not just our range. */ unsigned J; for (J = First; J <= Last; ++J) { if (Ref == CS_GetEntry (S, J)) { break; } } if (J > Last) { /* We did not find the entry. This means that the jump to * out code segment entry E came from outside the range, * which in turn means that the given range is not a basic * block. */ CS_ResetMarks (S, First, Last); return 0; } /* If we come here, we found the entry. Mark it, so we know * that the branch to the label is in range. */ CE_SetMark (Ref); } } /* Next entry */ ++I; } /* Third pass: Walk again over the range and check all branches. If we * find a branch that is not marked, its target is not inside the range * (since we checked all the labels in the range before). */ I = First; while (I <= Last) { /* Get the next entry */ CodeEntry* E = CS_GetEntry (S, I); /* Check if this is a branch and if so, if it has a mark */ if (E->Info & (OF_UBRA | OF_CBRA)) { if (!CE_HasMark (E)) { /* No mark means not a basic block. Before bailing out, be sure * to remove the marks from the remaining entries. */ CS_ResetMarks (S, I+1, Last); return 0; } /* Remove the mark */ CE_ResetMark (E); } /* Next entry */ ++I; } /* Done - this is a basic block */ return 1; } void CS_OutputPrologue (const CodeSeg* S) /* If the given code segment is a code segment for a function, output the * assembler prologue into the file. That is: Output a comment header, switch * to the correct segment and enter the local function scope. If the code * segment is global, do nothing. */ { /* Get the function associated with the code segment */ SymEntry* Func = S->Func; /* If the code segment is associated with a function, print a function * header and enter a local scope. Be sure to switch to the correct * segment before outputing the function label. */ if (Func) { /* Get the function descriptor */ CS_PrintFunctionHeader (S); WriteOutput (".segment\t\"%s\"\n\n.proc\t_%s", S->SegName, Func->Name); if (IsQualNear (Func->Type)) { WriteOutput (": near"); } else if (IsQualFar (Func->Type)) { WriteOutput (": far"); } WriteOutput ("\n\n"); } } void CS_OutputEpilogue (const CodeSeg* S) /* If the given code segment is a code segment for a function, output the * assembler epilogue into the file. That is: Close the local function scope. */ { if (S->Func) { WriteOutput ("\n.endproc\n\n"); } } void CS_Output (CodeSeg* S) /* Output the code segment data to the output file */ { unsigned I; const LineInfo* LI; /* Get the number of entries in this segment */ unsigned Count = CS_GetEntryCount (S); /* If the code segment is empty, bail out here */ if (Count == 0) { return; } /* Generate register info */ CS_GenRegInfo (S); /* Output the segment directive */ WriteOutput (".segment\t\"%s\"\n\n", S->SegName); /* Output all entries, prepended by the line information if it has changed */ LI = 0; for (I = 0; I < Count; ++I) { /* Get the next entry */ const CodeEntry* E = CollConstAt (&S->Entries, I); /* Check if the line info has changed. If so, output the source line * if the option is enabled and output debug line info if the debug * option is enabled. */ if (E->LI != LI) { /* Line info has changed, remember the new line info */ LI = E->LI; /* Add the source line as a comment. Beware: When line continuation * was used, the line may contain newlines. */ if (AddSource) { const char* L = LI->Line; WriteOutput (";\n; "); while (*L) { const char* N = strchr (L, '\n'); if (N) { /* We have a newline, just write the first part */ WriteOutput ("%.*s\n; ", (int) (N - L), L); L = N+1; } else { /* No Newline, write as is */ WriteOutput ("%s\n", L); break; } } WriteOutput (";\n"); } /* Add line debug info */ if (DebugInfo) { WriteOutput ("\t.dbg\tline, \"%s\", %u\n", GetInputName (LI), GetInputLine (LI)); } } /* Output the code */ CE_Output (E); } /* If debug info is enabled, terminate the last line number information */ if (DebugInfo) { WriteOutput ("\t.dbg\tline\n"); } /* Free register info */ CS_FreeRegInfo (S); } void CS_FreeRegInfo (CodeSeg* S) /* Free register infos for all instructions */ { unsigned I; for (I = 0; I < CS_GetEntryCount (S); ++I) { CE_FreeRegInfo (CS_GetEntry(S, I)); } } void CS_GenRegInfo (CodeSeg* S) /* Generate register infos for all instructions */ { unsigned I; RegContents Regs; /* Initial register contents */ RegContents* CurrentRegs; /* Current register contents */ int WasJump; /* True if last insn was a jump */ int Done; /* All runs done flag */ /* Be sure to delete all register infos */ CS_FreeRegInfo (S); /* We may need two runs to get back references right */ do { /* Assume we're done after this run */ Done = 1; /* On entry, the register contents are unknown */ RC_Invalidate (&Regs); CurrentRegs = &Regs; /* Walk over all insns and note just the changes from one insn to the * next one. */ WasJump = 0; for (I = 0; I < CS_GetEntryCount (S); ++I) { CodeEntry* P; /* Get the next instruction */ CodeEntry* E = CollAtUnchecked (&S->Entries, I); /* If the instruction has a label, we need some special handling */ unsigned LabelCount = CE_GetLabelCount (E); if (LabelCount > 0) { /* Loop over all entry points that jump here. If these entry * points already have register info, check if all values are * known and identical. If all values are identical, and the * preceeding instruction was not an unconditional branch, check * if the register value on exit of the preceeding instruction * is also identical. If all these values are identical, the * value of a register is known, otherwise it is unknown. */ CodeLabel* Label = CE_GetLabel (E, 0); unsigned Entry; if (WasJump) { /* Preceeding insn was an unconditional branch */ CodeEntry* J = CL_GetRef(Label, 0); if (J->RI) { Regs = J->RI->Out2; } else { RC_Invalidate (&Regs); } Entry = 1; } else { Regs = *CurrentRegs; Entry = 0; } while (Entry < CL_GetRefCount (Label)) { /* Get this entry */ CodeEntry* J = CL_GetRef (Label, Entry); if (J->RI == 0) { /* No register info for this entry. This means that the * instruction that jumps here is at higher addresses and * the jump is a backward jump. We need a second run to * get the register info right in this case. Until then, * assume unknown register contents. */ Done = 0; RC_Invalidate (&Regs); break; } if (J->RI->Out2.RegA != Regs.RegA) { Regs.RegA = UNKNOWN_REGVAL; } if (J->RI->Out2.RegX != Regs.RegX) { Regs.RegX = UNKNOWN_REGVAL; } if (J->RI->Out2.RegY != Regs.RegY) { Regs.RegY = UNKNOWN_REGVAL; } if (J->RI->Out2.SRegLo != Regs.SRegLo) { Regs.SRegLo = UNKNOWN_REGVAL; } if (J->RI->Out2.SRegHi != Regs.SRegHi) { Regs.SRegHi = UNKNOWN_REGVAL; } if (J->RI->Out2.Tmp1 != Regs.Tmp1) { Regs.Tmp1 = UNKNOWN_REGVAL; } ++Entry; } /* Use this register info */ CurrentRegs = &Regs; } /* Generate register info for this instruction */ CE_GenRegInfo (E, CurrentRegs); /* Remember for the next insn if this insn was an uncondition branch */ WasJump = (E->Info & OF_UBRA) != 0; /* Output registers for this insn are input for the next */ CurrentRegs = &E->RI->Out; /* If this insn is a branch on zero flag, we may have more info on * register contents for one of both flow directions, but only if * there is a previous instruction. */ if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) { /* Get the branch condition */ bc_t BC = GetBranchCond (E->OPC); /* Check the previous instruction */ switch (P->OPC) { case OP65_ADC: case OP65_AND: case OP65_DEA: case OP65_EOR: case OP65_INA: case OP65_LDA: case OP65_ORA: case OP65_PLA: case OP65_SBC: /* A is zero in one execution flow direction */ if (BC == BC_EQ) { E->RI->Out2.RegA = 0; } else { E->RI->Out.RegA = 0; } break; case OP65_CMP: /* If this is an immidiate compare, the A register has * the value of the compare later. */ if (CE_IsConstImm (P)) { if (BC == BC_EQ) { E->RI->Out2.RegA = (unsigned char)P->Num; } else { E->RI->Out.RegA = (unsigned char)P->Num; } } break; case OP65_CPX: /* If this is an immidiate compare, the X register has * the value of the compare later. */ if (CE_IsConstImm (P)) { if (BC == BC_EQ) { E->RI->Out2.RegX = (unsigned char)P->Num; } else { E->RI->Out.RegX = (unsigned char)P->Num; } } break; case OP65_CPY: /* If this is an immidiate compare, the Y register has * the value of the compare later. */ if (CE_IsConstImm (P)) { if (BC == BC_EQ) { E->RI->Out2.RegY = (unsigned char)P->Num; } else { E->RI->Out.RegY = (unsigned char)P->Num; } } break; case OP65_DEX: case OP65_INX: case OP65_LDX: case OP65_PLX: /* X is zero in one execution flow direction */ if (BC == BC_EQ) { E->RI->Out2.RegX = 0; } else { E->RI->Out.RegX = 0; } break; case OP65_DEY: case OP65_INY: case OP65_LDY: case OP65_PLY: /* X is zero in one execution flow direction */ if (BC == BC_EQ) { E->RI->Out2.RegY = 0; } else { E->RI->Out.RegY = 0; } break; case OP65_TAX: case OP65_TXA: /* If the branch is a beq, both A and X are zero at the * branch target, otherwise they are zero at the next * insn. */ if (BC == BC_EQ) { E->RI->Out2.RegA = E->RI->Out2.RegX = 0; } else { E->RI->Out.RegA = E->RI->Out.RegX = 0; } break; case OP65_TAY: case OP65_TYA: /* If the branch is a beq, both A and Y are zero at the * branch target, otherwise they are zero at the next * insn. */ if (BC == BC_EQ) { E->RI->Out2.RegA = E->RI->Out2.RegY = 0; } else { E->RI->Out.RegA = E->RI->Out.RegY = 0; } break; default: break; } } } } while (!Done); }
876
./cc65/src/cc65/casenode.c
/*****************************************************************************/ /* */ /* casenode.c */ /* */ /* Node for the tree that is generated for a switch statement */ /* */ /* */ /* */ /* (C) 2001 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <limits.h> /* common */ #include "coll.h" #include "xmalloc.h" /* cc65 */ #include "asmlabel.h" #include "error.h" #include "casenode.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ CaseNode* NewCaseNode (unsigned char Value) /* Create and initialize a new CaseNode */ { /* Allocate memory */ CaseNode* N = xmalloc (sizeof (CaseNode)); /* Initialize the fields */ N->Value = Value; N->Label = 0; N->Nodes = 0; /* Return the new node */ return N; } void FreeCaseNode (CaseNode* N) /* Delete a case node plus all sub nodes */ { if (N->Nodes) { FreeCaseNodeColl (N->Nodes); } xfree (N); } void FreeCaseNodeColl (Collection* Nodes) /* Free a collection of case nodes */ { unsigned I; for (I = 0; I < CollCount (Nodes); ++I) { FreeCaseNode (CollAtUnchecked (Nodes, I)); } FreeCollection (Nodes); } int SearchCaseNode (const Collection* Nodes, unsigned char Key, int* Index) /* Search for a node in the given collection. If the node has been found, * set Index to the index of the node and return true. If the node was not * found, set Index the the insertion position of the node and return * false. */ { /* Do a binary search */ int First = 0; int Last = CollCount (Nodes) - 1; int S = 0; while (First <= Last) { /* Set current to mid of range */ int Current = (Last + First) / 2; /* Get the entry from this position */ const CaseNode* N = CollConstAt (Nodes, Current); /* Compare the values */ if (N->Value < Key) { First = Current + 1; } else { Last = Current - 1; if (N->Value == Key) { /* Found. We cannot have duplicates, so end the search here. */ S = 1; First = Current; } } } *Index = First; return S; } unsigned InsertCaseValue (Collection* Nodes, unsigned long Val, unsigned Depth) /* Insert a new case value into a CaseNode tree with the given depth. Return * the code label for the value. */ { CaseNode* N = 0; unsigned CaseLabel = GetLocalLabel (); /* Code label */ while (Depth--) { int Index; /* Get the key */ unsigned char Key = (Val >> (Depth * CHAR_BIT)) & 0xFF; /* Search for the node in the collection */ if (SearchCaseNode (Nodes, Key, &Index) == 0) { /* Node not found - insert one */ N = NewCaseNode (Key); CollInsert (Nodes, N, Index); /* If this is not the last round, create the collection for * the subnodes, otherwise get a label for the code. */ if (Depth > 0) { N->Nodes = NewCollection (); } else { N->Label = CaseLabel; } } else { /* Node found, get it */ N = CollAt (Nodes, Index); /* If this is the last round and we found a node, we have a * duplicate case label in a switch. */ if (Depth == 0) { Error ("Duplicate case label"); } } /* Get the collection from the node for the next round. */ Nodes = N->Nodes; } /* Return the label of the node we found/created */ return CaseLabel; }
877
./cc65/src/cc65/asmcode.c
/*****************************************************************************/ /* */ /* asmcode.c */ /* */ /* Assembler output code handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" /* cc65 */ #include "asmcode.h" #include "codeseg.h" #include "dataseg.h" #include "segments.h" #include "stackptr.h" #include "symtab.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ void GetCodePos (CodeMark* M) /* Get a marker pointing to the current output position */ { M->Pos = CS_GetEntryCount (CS->Code); M->SP = StackPtr; } void RemoveCodeRange (const CodeMark* Start, const CodeMark* End) /* Remove all code between two code markers */ { /* Nothing to do if the range is empty */ if (Start->Pos == End->Pos) { return; } /* Delete the range */ CS_DelCodeRange (CS->Code, Start->Pos, End->Pos-1); } void RemoveCode (const CodeMark* M) /* Remove all code after the given code marker */ { CS_DelCodeAfter (CS->Code, M->Pos); StackPtr = M->SP; } void MoveCode (const CodeMark* Start, const CodeMark* End, const CodeMark* Target) /* Move the code between Start (inclusive) and End (exclusive) to * (before) Target. The code marks aren't updated. */ { CS_MoveEntries (CS->Code, Start->Pos, End->Pos - Start->Pos, Target->Pos); } int CodeRangeIsEmpty (const CodeMark* Start, const CodeMark* End) /* Return true if the given code range is empty (no code between Start and End) */ { int Empty; PRECONDITION (Start->Pos <= End->Pos); Empty = (Start->Pos == End->Pos); if (Empty) { /* Safety */ CHECK (Start->SP == End->SP); } return Empty; } void WriteAsmOutput (void) /* Write the final assembler output to the output file */ { SymTable* SymTab; SymEntry* Entry; /* Output the global data segment */ CHECK (!HaveGlobalCode ()); OutputSegments (CS); /* Output all global or referenced functions */ SymTab = GetGlobalSymTab (); Entry = SymTab->SymHead; while (Entry) { if (SymIsOutputFunc (Entry)) { /* Function which is defined and referenced or extern */ OutputSegments (Entry->V.F.Seg); } Entry = Entry->NextSym; } }
878
./cc65/src/cc65/codegen.c
/*****************************************************************************/ /* */ /* codegen.c */ /* */ /* 6502 code generator */ /* */ /* */ /* */ /* (C) 1998-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <string.h> #include <stdarg.h> /* common */ #include "check.h" #include "cpu.h" #include "strbuf.h" #include "xmalloc.h" #include "xsprintf.h" #include "version.h" /* cc65 */ #include "asmcode.h" #include "asmlabel.h" #include "casenode.h" #include "codeseg.h" #include "dataseg.h" #include "error.h" #include "global.h" #include "segments.h" #include "stackptr.h" #include "textseg.h" #include "util.h" #include "codegen.h" /*****************************************************************************/ /* Helpers */ /*****************************************************************************/ static void typeerror (unsigned type) /* Print an error message about an invalid operand type */ { /* Special handling for floats here: */ if ((type & CF_TYPEMASK) == CF_FLOAT) { Fatal ("Floating point type is currently unsupported"); } else { Internal ("Invalid type in CF flags: %04X, type = %u", type, type & CF_TYPEMASK); } } static void CheckLocalOffs (unsigned Offs) /* Check the offset into the stack for 8bit range */ { if (Offs >= 256) { /* Too many local vars */ Error ("Too many local variables"); } } static const char* GetLabelName (unsigned Flags, unsigned long Label, long Offs) { static char Buf [256]; /* Label name */ /* Create the correct label name */ switch (Flags & CF_ADDRMASK) { case CF_STATIC: /* Static memory cell */ if (Offs) { xsprintf (Buf, sizeof (Buf), "%s%+ld", LocalLabelName (Label), Offs); } else { xsprintf (Buf, sizeof (Buf), "%s", LocalLabelName (Label)); } break; case CF_EXTERNAL: /* External label */ if (Offs) { xsprintf (Buf, sizeof (Buf), "_%s%+ld", (char*) Label, Offs); } else { xsprintf (Buf, sizeof (Buf), "_%s", (char*) Label); } break; case CF_ABSOLUTE: /* Absolute address */ xsprintf (Buf, sizeof (Buf), "$%04X", (int)((Label+Offs) & 0xFFFF)); break; case CF_REGVAR: /* Variable in register bank */ xsprintf (Buf, sizeof (Buf), "regbank+%u", (unsigned)((Label+Offs) & 0xFFFF)); break; default: Internal ("Invalid address flags: %04X", Flags); } /* Return a pointer to the static buffer */ return Buf; } /*****************************************************************************/ /* Pre- and postamble */ /*****************************************************************************/ void g_preamble (void) /* Generate the assembler code preamble */ { /* Identify the compiler version */ AddTextLine (";"); AddTextLine ("; File generated by cc65 v %s", GetVersionAsString ()); AddTextLine (";"); /* Insert some object file options */ AddTextLine ("\t.fopt\t\tcompiler,\"cc65 v %s\"", GetVersionAsString ()); /* If we're producing code for some other CPU, switch the command set */ switch (CPU) { case CPU_6502: AddTextLine ("\t.setcpu\t\t\"6502\""); break; case CPU_6502X: AddTextLine ("\t.setcpu\t\t\"6502X\""); break; case CPU_65SC02: AddTextLine ("\t.setcpu\t\t\"65SC02\""); break; case CPU_65C02: AddTextLine ("\t.setcpu\t\t\"65C02\""); break; case CPU_65816: AddTextLine ("\t.setcpu\t\t\"65816\""); break; case CPU_HUC6280: AddTextLine ("\t.setcpu\t\t\"HUC6280\""); break; default: Internal ("Unknown CPU: %d", CPU); } /* Use smart mode */ AddTextLine ("\t.smart\t\ton"); /* Allow auto import for runtime library routines */ AddTextLine ("\t.autoimport\ton"); /* Switch the assembler into case sensitive mode */ AddTextLine ("\t.case\t\ton"); /* Tell the assembler if we want to generate debug info */ AddTextLine ("\t.debuginfo\t%s", (DebugInfo != 0)? "on" : "off"); /* Import zero page variables */ AddTextLine ("\t.importzp\tsp, sreg, regsave, regbank"); AddTextLine ("\t.importzp\ttmp1, tmp2, tmp3, tmp4, ptr1, ptr2, ptr3, ptr4"); /* Define long branch macros */ AddTextLine ("\t.macpack\tlongbranch"); } void g_fileinfo (const char* Name, unsigned long Size, unsigned long MTime) /* If debug info is enabled, place a file info into the source */ { if (DebugInfo) { /* We have to place this into the global text segment, so it will * appear before all .dbg line statements. */ TS_AddLine (GS->Text, "\t.dbg\t\tfile, \"%s\", %lu, %lu", Name, Size, MTime); } } /*****************************************************************************/ /* Segment support */ /*****************************************************************************/ void g_userodata (void) /* Switch to the read only data segment */ { UseDataSeg (SEG_RODATA); } void g_usedata (void) /* Switch to the data segment */ { UseDataSeg (SEG_DATA); } void g_usebss (void) /* Switch to the bss segment */ { UseDataSeg (SEG_BSS); } void g_segname (segment_t Seg) /* Emit the name of a segment if necessary */ { /* Emit a segment directive for the data style segments */ DataSeg* S; switch (Seg) { case SEG_RODATA: S = CS->ROData; break; case SEG_DATA: S = CS->Data; break; case SEG_BSS: S = CS->BSS; break; default: S = 0; break; } if (S) { DS_AddLine (S, ".segment\t\"%s\"", GetSegName (Seg)); } } /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned sizeofarg (unsigned flags) /* Return the size of a function argument type that is encoded in flags */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: return (flags & CF_FORCECHAR)? 1 : 2; case CF_INT: return 2; case CF_LONG: return 4; case CF_FLOAT: return 4; default: typeerror (flags); /* NOTREACHED */ return 2; } } int pop (unsigned flags) /* Pop an argument of the given size */ { return StackPtr += sizeofarg (flags); } int push (unsigned flags) /* Push an argument of the given size */ { return StackPtr -= sizeofarg (flags); } static unsigned MakeByteOffs (unsigned Flags, unsigned Offs) /* The value in Offs is an offset to an address in a/x. Make sure, an object * of the type given in Flags can be loaded or stored into this address by * adding part of the offset to the address in ax, so that the remaining * offset fits into an index register. Return the remaining offset. */ { /* If the offset is too large for a byte register, add the high byte * of the offset to the primary. Beware: We need a special correction * if the offset in the low byte will overflow in the operation. */ unsigned O = Offs & ~0xFFU; if ((Offs & 0xFF) > 256 - sizeofarg (Flags)) { /* We need to add the low byte also */ O += Offs & 0xFF; } /* Do the correction if we need one */ if (O != 0) { g_inc (CF_INT | CF_CONST, O); Offs -= O; } /* Return the new offset */ return Offs; } /*****************************************************************************/ /* Functions handling local labels */ /*****************************************************************************/ void g_defcodelabel (unsigned label) /* Define a local code label */ { CS_AddLabel (CS->Code, LocalLabelName (label)); } void g_defdatalabel (unsigned label) /* Define a local data label */ { AddDataLine ("%s:", LocalLabelName (label)); } void g_aliasdatalabel (unsigned label, unsigned baselabel, long offs) /* Define label as a local alias for baselabel+offs */ { /* We need an intermediate buffer here since LocalLabelName uses a * static buffer which changes with each call. */ StrBuf L = AUTO_STRBUF_INITIALIZER; SB_AppendStr (&L, LocalLabelName (label)); SB_Terminate (&L); AddDataLine ("%s\t:=\t%s+%ld", SB_GetConstBuf (&L), LocalLabelName (baselabel), offs); SB_Done (&L); } /*****************************************************************************/ /* Functions handling global labels */ /*****************************************************************************/ void g_defgloblabel (const char* Name) /* Define a global label with the given name */ { /* Global labels are always data labels */ AddDataLine ("_%s:", Name); } void g_defexport (const char* Name, int ZP) /* Export the given label */ { if (ZP) { AddTextLine ("\t.exportzp\t_%s", Name); } else { AddTextLine ("\t.export\t\t_%s", Name); } } void g_defimport (const char* Name, int ZP) /* Import the given label */ { if (ZP) { AddTextLine ("\t.importzp\t_%s", Name); } else { AddTextLine ("\t.import\t\t_%s", Name); } } void g_importstartup (void) /* Forced import of the startup module */ { AddTextLine ("\t.forceimport\t__STARTUP__"); } void g_importmainargs (void) /* Forced import of a special symbol that handles arguments to main */ { AddTextLine ("\t.forceimport\tinitmainargs"); } /*****************************************************************************/ /* Function entry and exit */ /*****************************************************************************/ /* Remember the argument size of a function. The variable is set by g_enter * and used by g_leave. If the functions gets its argument size by the caller * (variable param list or function without prototype), g_enter will set the * value to -1. */ static int funcargs; void g_enter (unsigned flags, unsigned argsize) /* Function prologue */ { if ((flags & CF_FIXARGC) != 0) { /* Just remember the argument size for the leave */ funcargs = argsize; } else { funcargs = -1; AddCodeLine ("jsr enter"); } } void g_leave (void) /* Function epilogue */ { /* How many bytes of locals do we have to drop? */ unsigned ToDrop = (unsigned) -StackPtr; /* If we didn't have a variable argument list, don't call leave */ if (funcargs >= 0) { /* Drop stackframe if needed */ g_drop (ToDrop + funcargs); } else if (StackPtr != 0) { /* We've a stack frame to drop */ if (ToDrop > 255) { g_drop (ToDrop); /* Inlines the code */ AddCodeLine ("jsr leave"); } else { AddCodeLine ("ldy #$%02X", ToDrop); AddCodeLine ("jsr leavey"); } } else { /* Nothing to drop */ AddCodeLine ("jsr leave"); } /* Add the final rts */ AddCodeLine ("rts"); } /*****************************************************************************/ /* Register variables */ /*****************************************************************************/ void g_swap_regvars (int StackOffs, int RegOffs, unsigned Bytes) /* Swap a register variable with a location on the stack */ { /* Calculate the actual stack offset and check it */ StackOffs -= StackPtr; CheckLocalOffs (StackOffs); /* Generate code */ AddCodeLine ("ldy #$%02X", StackOffs & 0xFF); if (Bytes == 1) { if (IS_Get (&CodeSizeFactor) < 165) { AddCodeLine ("ldx #$%02X", RegOffs & 0xFF); AddCodeLine ("jsr regswap1"); } else { AddCodeLine ("lda (sp),y"); AddCodeLine ("ldx regbank%+d", RegOffs); AddCodeLine ("sta regbank%+d", RegOffs); AddCodeLine ("txa"); AddCodeLine ("sta (sp),y"); } } else if (Bytes == 2) { AddCodeLine ("ldx #$%02X", RegOffs & 0xFF); AddCodeLine ("jsr regswap2"); } else { AddCodeLine ("ldx #$%02X", RegOffs & 0xFF); AddCodeLine ("lda #$%02X", Bytes & 0xFF); AddCodeLine ("jsr regswap"); } } void g_save_regvars (int RegOffs, unsigned Bytes) /* Save register variables */ { /* Don't loop for up to two bytes */ if (Bytes == 1) { AddCodeLine ("lda regbank%+d", RegOffs); AddCodeLine ("jsr pusha"); } else if (Bytes == 2) { AddCodeLine ("lda regbank%+d", RegOffs); AddCodeLine ("ldx regbank%+d", RegOffs+1); AddCodeLine ("jsr pushax"); } else { /* More than two bytes - loop */ unsigned Label = GetLocalLabel (); g_space (Bytes); AddCodeLine ("ldy #$%02X", (unsigned char) (Bytes - 1)); AddCodeLine ("ldx #$%02X", (unsigned char) Bytes); g_defcodelabel (Label); AddCodeLine ("lda regbank%+d,x", RegOffs-1); AddCodeLine ("sta (sp),y"); AddCodeLine ("dey"); AddCodeLine ("dex"); AddCodeLine ("bne %s", LocalLabelName (Label)); } /* We pushed stuff, correct the stack pointer */ StackPtr -= Bytes; } void g_restore_regvars (int StackOffs, int RegOffs, unsigned Bytes) /* Restore register variables */ { /* Calculate the actual stack offset and check it */ StackOffs -= StackPtr; CheckLocalOffs (StackOffs); /* Don't loop for up to two bytes */ if (Bytes == 1) { AddCodeLine ("ldy #$%02X", StackOffs); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs); } else if (Bytes == 2) { AddCodeLine ("ldy #$%02X", StackOffs); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs+1); } else if (Bytes == 3 && IS_Get (&CodeSizeFactor) >= 133) { AddCodeLine ("ldy #$%02X", StackOffs); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs+1); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d", RegOffs+2); } else if (StackOffs <= RegOffs) { /* More bytes, but the relation between the register offset in the * register bank and the stack offset allows us to generate short * code that uses just one index register. */ unsigned Label = GetLocalLabel (); AddCodeLine ("ldy #$%02X", StackOffs); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d,y", RegOffs - StackOffs); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", StackOffs + Bytes); AddCodeLine ("bne %s", LocalLabelName (Label)); } else { /* Ok, this is the generic code. We need to save X because the * caller will only save A. */ unsigned Label = GetLocalLabel (); AddCodeLine ("stx tmp1"); AddCodeLine ("ldy #$%02X", (unsigned char) (StackOffs + Bytes - 1)); AddCodeLine ("ldx #$%02X", (unsigned char) (Bytes - 1)); g_defcodelabel (Label); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta regbank%+d,x", RegOffs); AddCodeLine ("dey"); AddCodeLine ("dex"); AddCodeLine ("bpl %s", LocalLabelName (Label)); AddCodeLine ("ldx tmp1"); } } /*****************************************************************************/ /* Fetching memory cells */ /*****************************************************************************/ void g_getimmed (unsigned Flags, unsigned long Val, long Offs) /* Load a constant into the primary register */ { unsigned char B1, B2, B3, B4; unsigned Done; if ((Flags & CF_CONST) != 0) { /* Numeric constant */ switch (Flags & CF_TYPEMASK) { case CF_CHAR: if ((Flags & CF_FORCECHAR) != 0) { AddCodeLine ("lda #$%02X", (unsigned char) Val); break; } /* FALL THROUGH */ case CF_INT: AddCodeLine ("ldx #$%02X", (unsigned char) (Val >> 8)); AddCodeLine ("lda #$%02X", (unsigned char) Val); break; case CF_LONG: /* Split the value into 4 bytes */ B1 = (unsigned char) (Val >> 0); B2 = (unsigned char) (Val >> 8); B3 = (unsigned char) (Val >> 16); B4 = (unsigned char) (Val >> 24); /* Remember which bytes are done */ Done = 0; /* Load the value */ AddCodeLine ("ldx #$%02X", B2); Done |= 0x02; if (B2 == B3) { AddCodeLine ("stx sreg"); Done |= 0x04; } if (B2 == B4) { AddCodeLine ("stx sreg+1"); Done |= 0x08; } if ((Done & 0x04) == 0 && B1 != B3) { AddCodeLine ("lda #$%02X", B3); AddCodeLine ("sta sreg"); Done |= 0x04; } if ((Done & 0x08) == 0 && B1 != B4) { AddCodeLine ("lda #$%02X", B4); AddCodeLine ("sta sreg+1"); Done |= 0x08; } AddCodeLine ("lda #$%02X", B1); Done |= 0x01; if ((Done & 0x04) == 0) { CHECK (B1 == B3); AddCodeLine ("sta sreg"); } if ((Done & 0x08) == 0) { CHECK (B1 == B4); AddCodeLine ("sta sreg+1"); } break; default: typeerror (Flags); break; } } else { /* Some sort of label */ const char* Label = GetLabelName (Flags, Val, Offs); /* Load the address into the primary */ AddCodeLine ("lda #<(%s)", Label); AddCodeLine ("ldx #>(%s)", Label); } } void g_getstatic (unsigned flags, unsigned long label, long offs) /* Fetch an static memory cell into the primary register */ { /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); /* Check the size and generate the correct load operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if ((flags & CF_FORCECHAR) || (flags & CF_TEST)) { AddCodeLine ("lda %s", lbuf); /* load A from the label */ } else { AddCodeLine ("ldx #$00"); AddCodeLine ("lda %s", lbuf); /* load A from the label */ if (!(flags & CF_UNSIGNED)) { /* Must sign extend */ unsigned L = GetLocalLabel (); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } } break; case CF_INT: AddCodeLine ("lda %s", lbuf); if (flags & CF_TEST) { AddCodeLine ("ora %s+1", lbuf); } else { AddCodeLine ("ldx %s+1", lbuf); } break; case CF_LONG: if (flags & CF_TEST) { AddCodeLine ("lda %s+3", lbuf); AddCodeLine ("ora %s+2", lbuf); AddCodeLine ("ora %s+1", lbuf); AddCodeLine ("ora %s+0", lbuf); } else { AddCodeLine ("lda %s+3", lbuf); AddCodeLine ("sta sreg+1"); AddCodeLine ("lda %s+2", lbuf); AddCodeLine ("sta sreg"); AddCodeLine ("ldx %s+1", lbuf); AddCodeLine ("lda %s", lbuf); } break; default: typeerror (flags); } } void g_getlocal (unsigned Flags, int Offs) /* Fetch specified local object (local var). */ { Offs -= StackPtr; switch (Flags & CF_TYPEMASK) { case CF_CHAR: CheckLocalOffs (Offs); if ((Flags & CF_FORCECHAR) || (Flags & CF_TEST)) { AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("lda (sp),y"); } else { AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("ldx #$00"); AddCodeLine ("lda (sp),y"); if ((Flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } } break; case CF_INT: CheckLocalOffs (Offs + 1); AddCodeLine ("ldy #$%02X", (unsigned char) (Offs+1)); if (Flags & CF_TEST) { AddCodeLine ("lda (sp),y"); AddCodeLine ("dey"); AddCodeLine ("ora (sp),y"); } else { AddCodeLine ("jsr ldaxysp"); } break; case CF_LONG: CheckLocalOffs (Offs + 3); AddCodeLine ("ldy #$%02X", (unsigned char) (Offs+3)); AddCodeLine ("jsr ldeaxysp"); if (Flags & CF_TEST) { g_test (Flags); } break; default: typeerror (Flags); } } void g_getind (unsigned Flags, unsigned Offs) /* Fetch the specified object type indirect through the primary register * into the primary register */ { /* If the offset is greater than 255, add the part that is > 255 to * the primary. This way we get an easy addition and use the low byte * as the offset */ Offs = MakeByteOffs (Flags, Offs); /* Handle the indirect fetch */ switch (Flags & CF_TYPEMASK) { case CF_CHAR: /* Character sized */ AddCodeLine ("ldy #$%02X", Offs); if (Flags & CF_UNSIGNED) { AddCodeLine ("jsr ldauidx"); } else { AddCodeLine ("jsr ldaidx"); } break; case CF_INT: if (Flags & CF_TEST) { AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); AddCodeLine ("lda (ptr1),y"); AddCodeLine ("iny"); AddCodeLine ("ora (ptr1),y"); } else { AddCodeLine ("ldy #$%02X", Offs+1); AddCodeLine ("jsr ldaxidx"); } break; case CF_LONG: AddCodeLine ("ldy #$%02X", Offs+3); AddCodeLine ("jsr ldeaxidx"); if (Flags & CF_TEST) { g_test (Flags); } break; default: typeerror (Flags); } } void g_leasp (int Offs) /* Fetch the address of the specified symbol into the primary register */ { unsigned char Lo, Hi; /* Calculate the offset relative to sp */ Offs -= StackPtr; /* Get low and high byte */ Lo = (unsigned char) Offs; Hi = (unsigned char) (Offs >> 8); /* Generate code */ if (Lo == 0) { if (Hi <= 3) { AddCodeLine ("lda sp"); AddCodeLine ("ldx sp+1"); while (Hi--) { AddCodeLine ("inx"); } } else { AddCodeLine ("lda sp+1"); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", Hi); AddCodeLine ("tax"); AddCodeLine ("lda sp"); } } else if (Hi == 0) { /* 8 bit offset */ if (IS_Get (&CodeSizeFactor) < 200) { /* 8 bit offset with subroutine call */ AddCodeLine ("lda #$%02X", Lo); AddCodeLine ("jsr leaa0sp"); } else { /* 8 bit offset inlined */ unsigned L = GetLocalLabel (); AddCodeLine ("lda sp"); AddCodeLine ("ldx sp+1"); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", Lo); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); } } else if (IS_Get (&CodeSizeFactor) < 170) { /* Full 16 bit offset with subroutine call */ AddCodeLine ("lda #$%02X", Lo); AddCodeLine ("ldx #$%02X", Hi); AddCodeLine ("jsr leaaxsp"); } else { /* Full 16 bit offset inlined */ AddCodeLine ("lda sp"); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", Lo); AddCodeLine ("pha"); AddCodeLine ("lda sp+1"); AddCodeLine ("adc #$%02X", Hi); AddCodeLine ("tax"); AddCodeLine ("pla"); } } void g_leavariadic (int Offs) /* Fetch the address of a parameter in a variadic function into the primary * register */ { unsigned ArgSizeOffs; /* Calculate the offset relative to sp */ Offs -= StackPtr; /* Get the offset of the parameter which is stored at sp+0 on function * entry and check if this offset is reachable with a byte offset. */ CHECK (StackPtr <= 0); ArgSizeOffs = -StackPtr; CheckLocalOffs (ArgSizeOffs); /* Get the size of all parameters. */ AddCodeLine ("ldy #$%02X", ArgSizeOffs); AddCodeLine ("lda (sp),y"); /* Add the value of the stackpointer */ if (IS_Get (&CodeSizeFactor) > 250) { unsigned L = GetLocalLabel(); AddCodeLine ("ldx sp+1"); AddCodeLine ("clc"); AddCodeLine ("adc sp"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); } else { AddCodeLine ("ldx #$00"); AddCodeLine ("jsr leaaxsp"); } /* Add the offset to the primary */ if (Offs > 0) { g_inc (CF_INT | CF_CONST, Offs); } else if (Offs < 0) { g_dec (CF_INT | CF_CONST, -Offs); } } /*****************************************************************************/ /* Store into memory */ /*****************************************************************************/ void g_putstatic (unsigned flags, unsigned long label, long offs) /* Store the primary register into the specified static memory cell */ { /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); /* Check the size and generate the correct store operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: AddCodeLine ("sta %s", lbuf); break; case CF_INT: AddCodeLine ("sta %s", lbuf); AddCodeLine ("stx %s+1", lbuf); break; case CF_LONG: AddCodeLine ("sta %s", lbuf); AddCodeLine ("stx %s+1", lbuf); AddCodeLine ("ldy sreg"); AddCodeLine ("sty %s+2", lbuf); AddCodeLine ("ldy sreg+1"); AddCodeLine ("sty %s+3", lbuf); break; default: typeerror (flags); } } void g_putlocal (unsigned Flags, int Offs, long Val) /* Put data into local object. */ { Offs -= StackPtr; CheckLocalOffs (Offs); switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_CONST) { AddCodeLine ("lda #$%02X", (unsigned char) Val); } AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("sta (sp),y"); break; case CF_INT: if (Flags & CF_CONST) { AddCodeLine ("ldy #$%02X", Offs+1); AddCodeLine ("lda #$%02X", (unsigned char) (Val >> 8)); AddCodeLine ("sta (sp),y"); if ((Flags & CF_NOKEEP) == 0) { /* Place high byte into X */ AddCodeLine ("tax"); } if ((Val & 0xFF) == Offs+1) { /* The value we need is already in Y */ AddCodeLine ("tya"); AddCodeLine ("dey"); } else { AddCodeLine ("dey"); AddCodeLine ("lda #$%02X", (unsigned char) Val); } AddCodeLine ("sta (sp),y"); } else { AddCodeLine ("ldy #$%02X", Offs); if ((Flags & CF_NOKEEP) == 0 || IS_Get (&CodeSizeFactor) < 160) { AddCodeLine ("jsr staxysp"); } else { AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("txa"); AddCodeLine ("sta (sp),y"); } } break; case CF_LONG: if (Flags & CF_CONST) { g_getimmed (Flags, Val, 0); } AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("jsr steaxysp"); break; default: typeerror (Flags); } } void g_putind (unsigned Flags, unsigned Offs) /* Store the specified object type in the primary register at the address * on the top of the stack */ { /* We can handle offsets below $100 directly, larger offsets must be added * to the address. Since a/x is in use, best code is achieved by adding * just the high byte. Be sure to check if the low byte will overflow while * while storing. */ if ((Offs & 0xFF) > 256 - sizeofarg (Flags | CF_FORCECHAR)) { /* Overflow - we need to add the low byte also */ AddCodeLine ("ldy #$00"); AddCodeLine ("clc"); AddCodeLine ("pha"); AddCodeLine ("lda #$%02X", Offs & 0xFF); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("lda #$%02X", (Offs >> 8) & 0xFF); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); AddCodeLine ("pla"); /* Complete address is on stack, new offset is zero */ Offs = 0; } else if ((Offs & 0xFF00) != 0) { /* We can just add the high byte */ AddCodeLine ("ldy #$01"); AddCodeLine ("clc"); AddCodeLine ("pha"); AddCodeLine ("lda #$%02X", (Offs >> 8) & 0xFF); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); AddCodeLine ("pla"); /* Offset is now just the low byte */ Offs &= 0x00FF; } /* Check the size and determine operation */ AddCodeLine ("ldy #$%02X", Offs); switch (Flags & CF_TYPEMASK) { case CF_CHAR: AddCodeLine ("jsr staspidx"); break; case CF_INT: AddCodeLine ("jsr staxspidx"); break; case CF_LONG: AddCodeLine ("jsr steaxspidx"); break; default: typeerror (Flags); } /* Pop the argument which is always a pointer */ pop (CF_PTR); } /*****************************************************************************/ /* type conversion and similiar stuff */ /*****************************************************************************/ void g_toslong (unsigned flags) /* Make sure, the value on TOS is a long. Convert if necessary */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: case CF_INT: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr tosulong"); } else { AddCodeLine ("jsr toslong"); } push (CF_INT); break; case CF_LONG: break; default: typeerror (flags); } } void g_tosint (unsigned flags) /* Make sure, the value on TOS is an int. Convert if necessary */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: case CF_INT: break; case CF_LONG: AddCodeLine ("jsr tosint"); pop (CF_INT); break; default: typeerror (flags); } } void g_regint (unsigned Flags) /* Make sure, the value in the primary register an int. Convert if necessary */ { unsigned L; switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_FORCECHAR) { /* Conversion is from char */ if (Flags & CF_UNSIGNED) { AddCodeLine ("ldx #$00"); } else { L = GetLocalLabel(); AddCodeLine ("ldx #$00"); AddCodeLine ("cmp #$80"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } } /* FALLTHROUGH */ case CF_INT: case CF_LONG: break; default: typeerror (Flags); } } void g_reglong (unsigned Flags) /* Make sure, the value in the primary register a long. Convert if necessary */ { unsigned L; switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_FORCECHAR) { /* Conversion is from char */ if (Flags & CF_UNSIGNED) { if (IS_Get (&CodeSizeFactor) >= 200) { AddCodeLine ("ldx #$00"); AddCodeLine ("stx sreg"); AddCodeLine ("stx sreg+1"); } else { AddCodeLine ("jsr aulong"); } } else { if (IS_Get (&CodeSizeFactor) >= 366) { L = GetLocalLabel(); AddCodeLine ("ldx #$00"); AddCodeLine ("cmp #$80"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); AddCodeLine ("stx sreg"); AddCodeLine ("stx sreg+1"); } else { AddCodeLine ("jsr along"); } } } /* FALLTHROUGH */ case CF_INT: if (Flags & CF_UNSIGNED) { if (IS_Get (&CodeSizeFactor) >= 200) { AddCodeLine ("ldy #$00"); AddCodeLine ("sty sreg"); AddCodeLine ("sty sreg+1"); } else { AddCodeLine ("jsr axulong"); } } else { AddCodeLine ("jsr axlong"); } break; case CF_LONG: break; default: typeerror (Flags); } } unsigned g_typeadjust (unsigned lhs, unsigned rhs) /* Adjust the integer operands before doing a binary operation. lhs is a flags * value, that corresponds to the value on TOS, rhs corresponds to the value * in (e)ax. The return value is the the flags value for the resulting type. */ { unsigned ltype, rtype; unsigned result; /* Get the type spec from the flags */ ltype = lhs & CF_TYPEMASK; rtype = rhs & CF_TYPEMASK; /* Check if a conversion is needed */ if (ltype == CF_LONG && rtype != CF_LONG && (rhs & CF_CONST) == 0) { /* We must promote the primary register to long */ g_reglong (rhs); /* Get the new rhs type */ rhs = (rhs & ~CF_TYPEMASK) | CF_LONG; rtype = CF_LONG; } else if (ltype != CF_LONG && (lhs & CF_CONST) == 0 && rtype == CF_LONG) { /* We must promote the lhs to long */ if (lhs & CF_REG) { g_reglong (lhs); } else { g_toslong (lhs); } /* Get the new rhs type */ lhs = (lhs & ~CF_TYPEMASK) | CF_LONG; ltype = CF_LONG; } /* Determine the result type for the operation: * - The result is const if both operands are const. * - The result is unsigned if one of the operands is unsigned. * - The result is long if one of the operands is long. * - Otherwise the result is int sized. */ result = (lhs & CF_CONST) & (rhs & CF_CONST); result |= (lhs & CF_UNSIGNED) | (rhs & CF_UNSIGNED); if (rtype == CF_LONG || ltype == CF_LONG) { result |= CF_LONG; } else { result |= CF_INT; } return result; } unsigned g_typecast (unsigned lhs, unsigned rhs) /* Cast the value in the primary register to the operand size that is flagged * by the lhs value. Return the result value. */ { unsigned ltype, rtype; /* Get the type spec from the flags */ ltype = lhs & CF_TYPEMASK; rtype = rhs & CF_TYPEMASK; /* Check if a conversion is needed */ if ((rhs & CF_CONST) == 0) { if (ltype == CF_LONG && rtype != CF_LONG) { /* We must promote the primary register to long */ g_reglong (rhs); } else if (ltype == CF_INT && rtype != CF_INT) { /* We must promote the primary register to int */ g_regint (rhs); } } /* Do not need any other action. If the left type is int, and the primary * register is long, it will be automagically truncated. If the right hand * side is const, it is not located in the primary register and handled by * the expression parser code. */ /* Result is const if the right hand side was const */ lhs |= (rhs & CF_CONST); /* The resulting type is that of the left hand side (that's why you called * this function :-) */ return lhs; } void g_scale (unsigned flags, long val) /* Scale the value in the primary register by the given value. If val is positive, * scale up, is val is negative, scale down. This function is used to scale * the operands or results of pointer arithmetic by the size of the type, the * pointer points to. */ { int p2; /* Value may not be zero */ if (val == 0) { Internal ("Data type has no size"); } else if (val > 0) { /* Scale up */ if ((p2 = PowerOf2 (val)) > 0 && p2 <= 4) { /* Factor is 2, 4, 8 and 16, use special function */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { while (p2--) { AddCodeLine ("asl a"); } break; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shlax%d", p2); } else { AddCodeLine ("jsr aslax%d", p2); } break; case CF_LONG: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shleax%d", p2); } else { AddCodeLine ("jsr asleax%d", p2); } break; default: typeerror (flags); } } else if (val != 1) { /* Use a multiplication instead */ g_mul (flags | CF_CONST, val); } } else { /* Scale down */ val = -val; if ((p2 = PowerOf2 (val)) > 0 && p2 <= 4) { /* Factor is 2, 4, 8 and 16 use special function */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if (flags & CF_UNSIGNED) { while (p2--) { AddCodeLine ("lsr a"); } break; } else if (p2 <= 2) { AddCodeLine ("cmp #$80"); AddCodeLine ("ror a"); break; } } /* FALLTHROUGH */ case CF_INT: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr lsrax%d", p2); } else { AddCodeLine ("jsr asrax%d", p2); } break; case CF_LONG: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr lsreax%d", p2); } else { AddCodeLine ("jsr asreax%d", p2); } break; default: typeerror (flags); } } else if (val != 1) { /* Use a division instead */ g_div (flags | CF_CONST, val); } } } /*****************************************************************************/ /* Adds and subs of variables fix a fixed address */ /*****************************************************************************/ void g_addlocal (unsigned flags, int offs) /* Add a local variable to ax */ { unsigned L; /* Correct the offset and check it */ offs -= StackPtr; CheckLocalOffs (offs); switch (flags & CF_TYPEMASK) { case CF_CHAR: L = GetLocalLabel(); AddCodeLine ("ldy #$%02X", offs & 0xFF); AddCodeLine ("clc"); AddCodeLine ("adc (sp),y"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); break; case CF_INT: AddCodeLine ("ldy #$%02X", offs & 0xFF); AddCodeLine ("clc"); AddCodeLine ("adc (sp),y"); AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("iny"); AddCodeLine ("adc (sp),y"); AddCodeLine ("tax"); AddCodeLine ("pla"); break; case CF_LONG: /* Do it the old way */ g_push (flags, 0); g_getlocal (flags, offs); g_add (flags, 0); break; default: typeerror (flags); } } void g_addstatic (unsigned flags, unsigned long label, long offs) /* Add a static variable to ax */ { unsigned L; /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); switch (flags & CF_TYPEMASK) { case CF_CHAR: L = GetLocalLabel(); AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); break; case CF_INT: AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("tay"); AddCodeLine ("txa"); AddCodeLine ("adc %s+1", lbuf); AddCodeLine ("tax"); AddCodeLine ("tya"); break; case CF_LONG: /* Do it the old way */ g_push (flags, 0); g_getstatic (flags, label, offs); g_add (flags, 0); break; default: typeerror (flags); } } /*****************************************************************************/ /* Special op= functions */ /*****************************************************************************/ void g_addeqstatic (unsigned flags, unsigned long label, long offs, unsigned long val) /* Emit += for a static variable */ { /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("ldx #$00"); if (flags & CF_CONST) { if (val == 1) { AddCodeLine ("inc %s", lbuf); AddCodeLine ("lda %s", lbuf); } else { AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); } } else { AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); } if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } break; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_CONST) { if (val == 1) { unsigned L = GetLocalLabel (); AddCodeLine ("inc %s", lbuf); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("inc %s+1", lbuf); g_defcodelabel (L); AddCodeLine ("lda %s", lbuf); /* Hmmm... */ AddCodeLine ("ldx %s+1", lbuf); } else { AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); if (val < 0x100) { unsigned L = GetLocalLabel (); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inc %s+1", lbuf); g_defcodelabel (L); AddCodeLine ("ldx %s+1", lbuf); } else { AddCodeLine ("lda #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("adc %s+1", lbuf); AddCodeLine ("sta %s+1", lbuf); AddCodeLine ("tax"); AddCodeLine ("lda %s", lbuf); } } } else { AddCodeLine ("clc"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); AddCodeLine ("txa"); AddCodeLine ("adc %s+1", lbuf); AddCodeLine ("sta %s+1", lbuf); AddCodeLine ("tax"); AddCodeLine ("lda %s", lbuf); } break; case CF_LONG: if (flags & CF_CONST) { if (val < 0x100) { AddCodeLine ("ldy #<(%s)", lbuf); AddCodeLine ("sty ptr1"); AddCodeLine ("ldy #>(%s)", lbuf); if (val == 1) { AddCodeLine ("jsr laddeq1"); } else { AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("jsr laddeqa"); } } else { g_getstatic (flags, label, offs); g_inc (flags, val); g_putstatic (flags, label, offs); } } else { AddCodeLine ("ldy #<(%s)", lbuf); AddCodeLine ("sty ptr1"); AddCodeLine ("ldy #>(%s)", lbuf); AddCodeLine ("jsr laddeq"); } break; default: typeerror (flags); } } void g_addeqlocal (unsigned flags, int Offs, unsigned long val) /* Emit += for a local variable */ { /* Calculate the true offset, check it, load it into Y */ Offs -= StackPtr; CheckLocalOffs (Offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("ldx #$00"); if (flags & CF_CONST) { AddCodeLine ("clc"); AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); } else { AddCodeLine ("clc"); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); } if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } break; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("ldy #$%02X", Offs); if (flags & CF_CONST) { if (IS_Get (&CodeSizeFactor) >= 400) { AddCodeLine ("clc"); AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("lda #$%02X", (int) ((val >> 8) & 0xFF)); AddCodeLine ("adc (sp),y"); AddCodeLine ("sta (sp),y"); AddCodeLine ("tax"); AddCodeLine ("dey"); AddCodeLine ("lda (sp),y"); } else { g_getimmed (flags, val, 0); AddCodeLine ("jsr addeqysp"); } } else { AddCodeLine ("jsr addeqysp"); } break; case CF_LONG: if (flags & CF_CONST) { g_getimmed (flags, val, 0); } AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("jsr laddeqysp"); break; default: typeerror (flags); } } void g_addeqind (unsigned flags, unsigned offs, unsigned long val) /* Emit += for the location with address in ax */ { /* If the offset is too large for a byte register, add the high byte * of the offset to the primary. Beware: We need a special correction * if the offset in the low byte will overflow in the operation. */ offs = MakeByteOffs (flags, offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); AddCodeLine ("ldy #$%02X", offs); AddCodeLine ("ldx #$00"); AddCodeLine ("lda #$%02X", (int)(val & 0xFF)); AddCodeLine ("clc"); AddCodeLine ("adc (ptr1),y"); AddCodeLine ("sta (ptr1),y"); break; case CF_INT: case CF_LONG: AddCodeLine ("jsr pushax"); /* Push the address */ push (CF_PTR); /* Correct the internal sp */ g_getind (flags, offs); /* Fetch the value */ g_inc (flags, val); /* Increment value in primary */ g_putind (flags, offs); /* Store the value back */ break; default: typeerror (flags); } } void g_subeqstatic (unsigned flags, unsigned long label, long offs, unsigned long val) /* Emit -= for a static variable */ { /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("ldx #$00"); if (flags & CF_CONST) { if (val == 1) { AddCodeLine ("dec %s", lbuf); AddCodeLine ("lda %s", lbuf); } else { AddCodeLine ("lda %s", lbuf); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (int)(val & 0xFF)); AddCodeLine ("sta %s", lbuf); } } else { AddCodeLine ("eor #$FF"); AddCodeLine ("sec"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); } if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } break; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_CONST) { AddCodeLine ("lda %s", lbuf); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); AddCodeLine ("sta %s", lbuf); if (val < 0x100) { unsigned L = GetLocalLabel (); AddCodeLine ("bcs %s", LocalLabelName (L)); AddCodeLine ("dec %s+1", lbuf); g_defcodelabel (L); AddCodeLine ("ldx %s+1", lbuf); } else { AddCodeLine ("lda %s+1", lbuf); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("sta %s+1", lbuf); AddCodeLine ("tax"); AddCodeLine ("lda %s", lbuf); } } else { AddCodeLine ("eor #$FF"); AddCodeLine ("sec"); AddCodeLine ("adc %s", lbuf); AddCodeLine ("sta %s", lbuf); AddCodeLine ("txa"); AddCodeLine ("eor #$FF"); AddCodeLine ("adc %s+1", lbuf); AddCodeLine ("sta %s+1", lbuf); AddCodeLine ("tax"); AddCodeLine ("lda %s", lbuf); } break; case CF_LONG: if (flags & CF_CONST) { if (val < 0x100) { AddCodeLine ("ldy #<(%s)", lbuf); AddCodeLine ("sty ptr1"); AddCodeLine ("ldy #>(%s)", lbuf); AddCodeLine ("lda #$%02X", (unsigned char)val); AddCodeLine ("jsr lsubeqa"); } else { g_getstatic (flags, label, offs); g_dec (flags, val); g_putstatic (flags, label, offs); } } else { AddCodeLine ("ldy #<(%s)", lbuf); AddCodeLine ("sty ptr1"); AddCodeLine ("ldy #>(%s)", lbuf); AddCodeLine ("jsr lsubeq"); } break; default: typeerror (flags); } } void g_subeqlocal (unsigned flags, int Offs, unsigned long val) /* Emit -= for a local variable */ { /* Calculate the true offset, check it, load it into Y */ Offs -= StackPtr; CheckLocalOffs (Offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("ldx #$00"); if (flags & CF_CONST) { AddCodeLine ("lda (sp),y"); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); } else { AddCodeLine ("eor #$FF"); AddCodeLine ("sec"); AddCodeLine ("adc (sp),y"); } AddCodeLine ("sta (sp),y"); if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } break; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_CONST) { g_getimmed (flags, val, 0); } AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("jsr subeqysp"); break; case CF_LONG: if (flags & CF_CONST) { g_getimmed (flags, val, 0); } AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("jsr lsubeqysp"); break; default: typeerror (flags); } } void g_subeqind (unsigned flags, unsigned offs, unsigned long val) /* Emit -= for the location with address in ax */ { /* If the offset is too large for a byte register, add the high byte * of the offset to the primary. Beware: We need a special correction * if the offset in the low byte will overflow in the operation. */ offs = MakeByteOffs (flags, offs); /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: AddCodeLine ("sta ptr1"); AddCodeLine ("stx ptr1+1"); AddCodeLine ("ldy #$%02X", offs); AddCodeLine ("ldx #$00"); AddCodeLine ("lda (ptr1),y"); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); AddCodeLine ("sta (ptr1),y"); break; case CF_INT: case CF_LONG: AddCodeLine ("jsr pushax"); /* Push the address */ push (CF_PTR); /* Correct the internal sp */ g_getind (flags, offs); /* Fetch the value */ g_dec (flags, val); /* Increment value in primary */ g_putind (flags, offs); /* Store the value back */ break; default: typeerror (flags); } } /*****************************************************************************/ /* Add a variable address to the value in ax */ /*****************************************************************************/ void g_addaddr_local (unsigned flags attribute ((unused)), int offs) /* Add the address of a local variable to ax */ { unsigned L = 0; /* Add the offset */ offs -= StackPtr; if (offs != 0) { /* We cannot address more then 256 bytes of locals anyway */ L = GetLocalLabel(); CheckLocalOffs (offs); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", offs & 0xFF); /* Do also skip the CLC insn below */ AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); } /* Add the current stackpointer value */ AddCodeLine ("clc"); if (L != 0) { /* Label was used above */ g_defcodelabel (L); } AddCodeLine ("adc sp"); AddCodeLine ("tay"); AddCodeLine ("txa"); AddCodeLine ("adc sp+1"); AddCodeLine ("tax"); AddCodeLine ("tya"); } void g_addaddr_static (unsigned flags, unsigned long label, long offs) /* Add the address of a static variable to ax */ { /* Create the correct label name */ const char* lbuf = GetLabelName (flags, label, offs); /* Add the address to the current ax value */ AddCodeLine ("clc"); AddCodeLine ("adc #<(%s)", lbuf); AddCodeLine ("tay"); AddCodeLine ("txa"); AddCodeLine ("adc #>(%s)", lbuf); AddCodeLine ("tax"); AddCodeLine ("tya"); } /*****************************************************************************/ /* */ /*****************************************************************************/ void g_save (unsigned flags) /* Copy primary register to hold register. */ { /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("pha"); break; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("sta regsave"); AddCodeLine ("stx regsave+1"); break; case CF_LONG: AddCodeLine ("jsr saveeax"); break; default: typeerror (flags); } } void g_restore (unsigned flags) /* Copy hold register to primary. */ { /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("pla"); break; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("lda regsave"); AddCodeLine ("ldx regsave+1"); break; case CF_LONG: AddCodeLine ("jsr resteax"); break; default: typeerror (flags); } } void g_cmp (unsigned flags, unsigned long val) /* Immidiate compare. The primary register will not be changed, Z flag * will be set. */ { unsigned L; /* Check the size and determine operation */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("cmp #$%02X", (unsigned char)val); break; } /* FALLTHROUGH */ case CF_INT: L = GetLocalLabel(); AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("cpx #$%02X", (unsigned char)(val >> 8)); g_defcodelabel (L); break; case CF_LONG: Internal ("g_cmp: Long compares not implemented"); break; default: typeerror (flags); } } static void oper (unsigned Flags, unsigned long Val, const char** Subs) /* Encode a binary operation. subs is a pointer to four strings: * 0 --> Operate on ints * 1 --> Operate on unsigneds * 2 --> Operate on longs * 3 --> Operate on unsigned longs */ { /* Determine the offset into the array */ if (Flags & CF_UNSIGNED) { ++Subs; } if ((Flags & CF_TYPEMASK) == CF_LONG) { Subs += 2; } /* Load the value if it is not already in the primary */ if (Flags & CF_CONST) { /* Load value */ g_getimmed (Flags, Val, 0); } /* Output the operation */ AddCodeLine ("jsr %s", *Subs); /* The operation will pop it's argument */ pop (Flags); } void g_test (unsigned flags) /* Test the value in the primary and set the condition codes */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("tax"); break; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("stx tmp1"); AddCodeLine ("ora tmp1"); break; case CF_LONG: if (flags & CF_UNSIGNED) { AddCodeLine ("jsr utsteax"); } else { AddCodeLine ("jsr tsteax"); } break; default: typeerror (flags); } } void g_push (unsigned flags, unsigned long val) /* Push the primary register or a constant value onto the stack */ { if (flags & CF_CONST && (flags & CF_TYPEMASK) != CF_LONG) { /* We have a constant 8 or 16 bit value */ if ((flags & CF_TYPEMASK) == CF_CHAR && (flags & CF_FORCECHAR)) { /* Handle as 8 bit value */ AddCodeLine ("lda #$%02X", (unsigned char) val); AddCodeLine ("jsr pusha"); } else { /* Handle as 16 bit value */ g_getimmed (flags, val, 0); AddCodeLine ("jsr pushax"); } } else { /* Value is not 16 bit or not constant */ if (flags & CF_CONST) { /* Constant 32 bit value, load into eax */ g_getimmed (flags, val, 0); } /* Push the primary register */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { /* Handle as char */ AddCodeLine ("jsr pusha"); break; } /* FALL THROUGH */ case CF_INT: AddCodeLine ("jsr pushax"); break; case CF_LONG: AddCodeLine ("jsr pusheax"); break; default: typeerror (flags); } } /* Adjust the stack offset */ push (flags); } void g_swap (unsigned flags) /* Swap the primary register and the top of the stack. flags give the type * of *both* values (must have same size). */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: case CF_INT: AddCodeLine ("jsr swapstk"); break; case CF_LONG: AddCodeLine ("jsr swapestk"); break; default: typeerror (flags); } } void g_call (unsigned Flags, const char* Label, unsigned ArgSize) /* Call the specified subroutine name */ { if ((Flags & CF_FIXARGC) == 0) { /* Pass the argument count */ AddCodeLine ("ldy #$%02X", ArgSize); } AddCodeLine ("jsr _%s", Label); StackPtr += ArgSize; /* callee pops args */ } void g_callind (unsigned Flags, unsigned ArgSize, int Offs) /* Call subroutine indirect */ { if ((Flags & CF_LOCAL) == 0) { /* Address is in a/x */ if ((Flags & CF_FIXARGC) == 0) { /* Pass arg count */ AddCodeLine ("ldy #$%02X", ArgSize); } AddCodeLine ("jsr callax"); } else { /* The address is on stack, offset is on Val */ Offs -= StackPtr; CheckLocalOffs (Offs); AddCodeLine ("pha"); AddCodeLine ("ldy #$%02X", Offs); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta jmpvec+1"); AddCodeLine ("iny"); AddCodeLine ("lda (sp),y"); AddCodeLine ("sta jmpvec+2"); AddCodeLine ("pla"); AddCodeLine ("jsr jmpvec"); } /* Callee pops args */ StackPtr += ArgSize; } void g_jump (unsigned Label) /* Jump to specified internal label number */ { AddCodeLine ("jmp %s", LocalLabelName (Label)); } void g_truejump (unsigned flags attribute ((unused)), unsigned label) /* Jump to label if zero flag clear */ { AddCodeLine ("jne %s", LocalLabelName (label)); } void g_falsejump (unsigned flags attribute ((unused)), unsigned label) /* Jump to label if zero flag set */ { AddCodeLine ("jeq %s", LocalLabelName (label)); } void g_drop (unsigned Space) /* Drop space allocated on the stack */ { if (Space > 255) { /* Inline the code since calling addysp repeatedly is quite some * overhead. */ AddCodeLine ("pha"); AddCodeLine ("lda #$%02X", (unsigned char) Space); AddCodeLine ("clc"); AddCodeLine ("adc sp"); AddCodeLine ("sta sp"); AddCodeLine ("lda #$%02X", (unsigned char) (Space >> 8)); AddCodeLine ("adc sp+1"); AddCodeLine ("sta sp+1"); AddCodeLine ("pla"); } else if (Space > 8) { AddCodeLine ("ldy #$%02X", Space); AddCodeLine ("jsr addysp"); } else if (Space != 0) { AddCodeLine ("jsr incsp%u", Space); } } void g_space (int Space) /* Create or drop space on the stack */ { if (Space < 0) { /* This is actually a drop operation */ g_drop (-Space); } else if (Space > 255) { /* Inline the code since calling subysp repeatedly is quite some * overhead. */ AddCodeLine ("pha"); AddCodeLine ("lda sp"); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char) Space); AddCodeLine ("sta sp"); AddCodeLine ("lda sp+1"); AddCodeLine ("sbc #$%02X", (unsigned char) (Space >> 8)); AddCodeLine ("sta sp+1"); AddCodeLine ("pla"); } else if (Space > 8) { AddCodeLine ("ldy #$%02X", Space); AddCodeLine ("jsr subysp"); } else if (Space != 0) { AddCodeLine ("jsr decsp%u", Space); } } void g_cstackcheck (void) /* Check for a C stack overflow */ { AddCodeLine ("jsr cstkchk"); } void g_stackcheck (void) /* Check for a stack overflow */ { AddCodeLine ("jsr stkchk"); } void g_add (unsigned flags, unsigned long val) /* Primary = TOS + Primary */ { static const char* ops[12] = { "tosaddax", "tosaddax", "tosaddeax", "tosaddeax" }; if (flags & CF_CONST) { flags &= ~CF_FORCECHAR; /* Handle chars as ints */ g_push (flags & ~CF_CONST, 0); } oper (flags, val, ops); } void g_sub (unsigned flags, unsigned long val) /* Primary = TOS - Primary */ { static const char* ops[12] = { "tossubax", "tossubax", "tossubeax", "tossubeax", }; if (flags & CF_CONST) { flags &= ~CF_FORCECHAR; /* Handle chars as ints */ g_push (flags & ~CF_CONST, 0); } oper (flags, val, ops); } void g_rsub (unsigned flags, unsigned long val) /* Primary = Primary - TOS */ { static const char* ops[12] = { "tosrsubax", "tosrsubax", "tosrsubeax", "tosrsubeax", }; oper (flags, val, ops); } void g_mul (unsigned flags, unsigned long val) /* Primary = TOS * Primary */ { static const char* ops[12] = { "tosmulax", "tosumulax", "tosmuleax", "tosumuleax", }; int p2; /* Do strength reduction if the value is constant and a power of two */ if (flags & CF_CONST && (p2 = PowerOf2 (val)) >= 0) { /* Generate a shift instead */ g_asl (flags, p2); return; } /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { /* Handle some special cases */ switch (val) { case 3: AddCodeLine ("sta tmp1"); AddCodeLine ("asl a"); AddCodeLine ("clc"); AddCodeLine ("adc tmp1"); return; case 5: AddCodeLine ("sta tmp1"); AddCodeLine ("asl a"); AddCodeLine ("asl a"); AddCodeLine ("clc"); AddCodeLine ("adc tmp1"); return; case 6: AddCodeLine ("sta tmp1"); AddCodeLine ("asl a"); AddCodeLine ("clc"); AddCodeLine ("adc tmp1"); AddCodeLine ("asl a"); return; case 10: AddCodeLine ("sta tmp1"); AddCodeLine ("asl a"); AddCodeLine ("asl a"); AddCodeLine ("clc"); AddCodeLine ("adc tmp1"); AddCodeLine ("asl a"); return; } } /* FALLTHROUGH */ case CF_INT: switch (val) { case 3: AddCodeLine ("jsr mulax3"); return; case 5: AddCodeLine ("jsr mulax5"); return; case 6: AddCodeLine ("jsr mulax6"); return; case 7: AddCodeLine ("jsr mulax7"); return; case 9: AddCodeLine ("jsr mulax9"); return; case 10: AddCodeLine ("jsr mulax10"); return; } break; case CF_LONG: break; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. */ flags &= ~CF_FORCECHAR; /* Handle chars as ints */ g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_div (unsigned flags, unsigned long val) /* Primary = TOS / Primary */ { static const char* ops[12] = { "tosdivax", "tosudivax", "tosdiveax", "tosudiveax", }; /* Do strength reduction if the value is constant and a power of two */ int p2; if ((flags & CF_CONST) && (p2 = PowerOf2 (val)) >= 0) { /* Generate a shift instead */ g_asr (flags, p2); } else { /* Generate a division */ if (flags & CF_CONST) { /* lhs is not on stack */ flags &= ~CF_FORCECHAR; /* Handle chars as ints */ g_push (flags & ~CF_CONST, 0); } oper (flags, val, ops); } } void g_mod (unsigned flags, unsigned long val) /* Primary = TOS % Primary */ { static const char* ops[12] = { "tosmodax", "tosumodax", "tosmodeax", "tosumodeax", }; int p2; /* Check if we can do some cost reduction */ if ((flags & CF_CONST) && (flags & CF_UNSIGNED) && val != 0xFFFFFFFF && (p2 = PowerOf2 (val)) >= 0) { /* We can do that with an AND operation */ g_and (flags, val - 1); } else { /* Do it the hard way... */ if (flags & CF_CONST) { /* lhs is not on stack */ flags &= ~CF_FORCECHAR; /* Handle chars as ints */ g_push (flags & ~CF_CONST, 0); } oper (flags, val, ops); } } void g_or (unsigned flags, unsigned long val) /* Primary = TOS | Primary */ { static const char* ops[12] = { "tosorax", "tosorax", "tosoreax", "tosoreax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if ((val & 0xFF) != 0) { AddCodeLine ("ora #$%02X", (unsigned char)val); } return; } /* FALLTHROUGH */ case CF_INT: if (val <= 0xFF) { if ((val & 0xFF) != 0) { AddCodeLine ("ora #$%02X", (unsigned char)val); } } else if ((val & 0xFF00) == 0xFF00) { if ((val & 0xFF) != 0) { AddCodeLine ("ora #$%02X", (unsigned char)val); } AddCodeLine ("ldx #$FF"); } else if (val != 0) { AddCodeLine ("ora #$%02X", (unsigned char)val); AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("ora #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } return; case CF_LONG: if (val <= 0xFF) { if ((val & 0xFF) != 0) { AddCodeLine ("ora #$%02X", (unsigned char)val); } return; } break; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_xor (unsigned flags, unsigned long val) /* Primary = TOS ^ Primary */ { static const char* ops[12] = { "tosxorax", "tosxorax", "tosxoreax", "tosxoreax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if ((val & 0xFF) != 0) { AddCodeLine ("eor #$%02X", (unsigned char)val); } return; } /* FALLTHROUGH */ case CF_INT: if (val <= 0xFF) { if (val != 0) { AddCodeLine ("eor #$%02X", (unsigned char)val); } } else if (val != 0) { if ((val & 0xFF) != 0) { AddCodeLine ("eor #$%02X", (unsigned char)val); } AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("eor #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } return; case CF_LONG: if (val <= 0xFF) { if (val != 0) { AddCodeLine ("eor #$%02X", (unsigned char)val); } return; } break; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_and (unsigned Flags, unsigned long Val) /* Primary = TOS & Primary */ { static const char* ops[12] = { "tosandax", "tosandax", "tosandeax", "tosandeax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (Flags & CF_CONST) { switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_FORCECHAR) { if ((Val & 0xFF) == 0x00) { AddCodeLine ("lda #$00"); } else if ((Val & 0xFF) != 0xFF) { AddCodeLine ("and #$%02X", (unsigned char)Val); } return; } /* FALLTHROUGH */ case CF_INT: if ((Val & 0xFFFF) != 0xFFFF) { if (Val <= 0xFF) { AddCodeLine ("ldx #$00"); if (Val == 0) { AddCodeLine ("lda #$00"); } else if (Val != 0xFF) { AddCodeLine ("and #$%02X", (unsigned char)Val); } } else if ((Val & 0xFFFF) == 0xFF00) { AddCodeLine ("lda #$00"); } else if ((Val & 0xFF00) == 0xFF00) { AddCodeLine ("and #$%02X", (unsigned char)Val); } else if ((Val & 0x00FF) == 0x0000) { AddCodeLine ("txa"); AddCodeLine ("and #$%02X", (unsigned char)(Val >> 8)); AddCodeLine ("tax"); AddCodeLine ("lda #$00"); } else { AddCodeLine ("tay"); AddCodeLine ("txa"); AddCodeLine ("and #$%02X", (unsigned char)(Val >> 8)); AddCodeLine ("tax"); AddCodeLine ("tya"); if ((Val & 0x00FF) == 0x0000) { AddCodeLine ("lda #$00"); } else if ((Val & 0x00FF) != 0x00FF) { AddCodeLine ("and #$%02X", (unsigned char)Val); } } } return; case CF_LONG: if (Val <= 0xFF) { AddCodeLine ("ldx #$00"); AddCodeLine ("stx sreg+1"); AddCodeLine ("stx sreg"); if ((Val & 0xFF) != 0xFF) { AddCodeLine ("and #$%02X", (unsigned char)Val); } return; } else if (Val == 0xFF00) { AddCodeLine ("lda #$00"); AddCodeLine ("sta sreg+1"); AddCodeLine ("sta sreg"); return; } break; default: typeerror (Flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ Flags &= ~CF_FORCECHAR; g_push (Flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (Flags, Val, ops); } void g_asr (unsigned flags, unsigned long val) /* Primary = TOS >> Primary */ { static const char* ops[12] = { "tosasrax", "tosshrax", "tosasreax", "tosshreax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: case CF_INT: val &= 0x0F; if (val >= 8) { if (flags & CF_UNSIGNED) { AddCodeLine ("txa"); AddCodeLine ("ldx #$00"); } else { unsigned L = GetLocalLabel(); AddCodeLine ("cpx #$80"); /* Sign bit into carry */ AddCodeLine ("txa"); AddCodeLine ("ldx #$00"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("dex"); /* Make $FF */ g_defcodelabel (L); } val -= 8; } if (val >= 4) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shrax4"); } else { AddCodeLine ("jsr asrax4"); } val -= 4; } if (val > 0) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shrax%ld", val); } else { AddCodeLine ("jsr asrax%ld", val); } } return; case CF_LONG: val &= 0x1F; if (val >= 24) { AddCodeLine ("ldx #$00"); AddCodeLine ("lda sreg+1"); if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } AddCodeLine ("stx sreg"); AddCodeLine ("stx sreg+1"); val -= 24; } if (val >= 16) { AddCodeLine ("ldy #$00"); AddCodeLine ("ldx sreg+1"); if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bpl %s", LocalLabelName (L)); AddCodeLine ("dey"); g_defcodelabel (L); } AddCodeLine ("lda sreg"); AddCodeLine ("sty sreg+1"); AddCodeLine ("sty sreg"); val -= 16; } if (val >= 8) { AddCodeLine ("txa"); AddCodeLine ("ldx sreg"); AddCodeLine ("ldy sreg+1"); AddCodeLine ("sty sreg"); if ((flags & CF_UNSIGNED) == 0) { unsigned L = GetLocalLabel(); AddCodeLine ("cpy #$80"); AddCodeLine ("ldy #$00"); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("dey"); g_defcodelabel (L); } else { AddCodeLine ("ldy #$00"); } AddCodeLine ("sty sreg+1"); val -= 8; } if (val >= 4) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shreax4"); } else { AddCodeLine ("jsr asreax4"); } val -= 4; } if (val > 0) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shreax%ld", val); } else { AddCodeLine ("jsr asreax%ld", val); } } return; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_asl (unsigned flags, unsigned long val) /* Primary = TOS << Primary */ { static const char* ops[12] = { "tosaslax", "tosshlax", "tosasleax", "tosshleax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: case CF_INT: val &= 0x0F; if (val >= 8) { AddCodeLine ("tax"); AddCodeLine ("lda #$00"); val -= 8; } if (val >= 4) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shlax4"); } else { AddCodeLine ("jsr aslax4"); } val -= 4; } if (val > 0) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shlax%ld", val); } else { AddCodeLine ("jsr aslax%ld", val); } } return; case CF_LONG: val &= 0x1F; if (val >= 24) { AddCodeLine ("sta sreg+1"); AddCodeLine ("lda #$00"); AddCodeLine ("tax"); AddCodeLine ("sta sreg"); val -= 24; } if (val >= 16) { AddCodeLine ("stx sreg+1"); AddCodeLine ("sta sreg"); AddCodeLine ("lda #$00"); AddCodeLine ("tax"); val -= 16; } if (val >= 8) { AddCodeLine ("ldy sreg"); AddCodeLine ("sty sreg+1"); AddCodeLine ("stx sreg"); AddCodeLine ("tax"); AddCodeLine ("lda #$00"); val -= 8; } if (val > 4) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shleax4"); } else { AddCodeLine ("jsr asleax4"); } val -= 4; } if (val > 0) { if (flags & CF_UNSIGNED) { AddCodeLine ("jsr shleax%ld", val); } else { AddCodeLine ("jsr asleax%ld", val); } } return; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_neg (unsigned Flags) /* Primary = -Primary */ { switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_FORCECHAR) { AddCodeLine ("eor #$FF"); AddCodeLine ("clc"); AddCodeLine ("adc #$01"); return; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("jsr negax"); break; case CF_LONG: AddCodeLine ("jsr negeax"); break; default: typeerror (Flags); } } void g_bneg (unsigned flags) /* Primary = !Primary */ { switch (flags & CF_TYPEMASK) { case CF_CHAR: AddCodeLine ("jsr bnega"); break; case CF_INT: AddCodeLine ("jsr bnegax"); break; case CF_LONG: AddCodeLine ("jsr bnegeax"); break; default: typeerror (flags); } } void g_com (unsigned Flags) /* Primary = ~Primary */ { switch (Flags & CF_TYPEMASK) { case CF_CHAR: if (Flags & CF_FORCECHAR) { AddCodeLine ("eor #$FF"); return; } /* FALLTHROUGH */ case CF_INT: AddCodeLine ("jsr complax"); break; case CF_LONG: AddCodeLine ("jsr compleax"); break; default: typeerror (Flags); } } void g_inc (unsigned flags, unsigned long val) /* Increment the primary register by a given number */ { /* Don't inc by zero */ if (val == 0) { return; } /* Generate code for the supported types */ flags &= ~CF_CONST; switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && val <= 2) { while (val--) { AddCodeLine ("ina"); } } else { AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", (unsigned char)val); } break; } /* FALLTHROUGH */ case CF_INT: if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && val == 1) { unsigned L = GetLocalLabel(); AddCodeLine ("ina"); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); } else if (IS_Get (&CodeSizeFactor) < 200) { /* Use jsr calls */ if (val <= 8) { AddCodeLine ("jsr incax%lu", val); } else if (val <= 255) { AddCodeLine ("ldy #$%02X", (unsigned char) val); AddCodeLine ("jsr incaxy"); } else { g_add (flags | CF_CONST, val); } } else { /* Inline the code */ if (val <= 0x300) { if ((val & 0xFF) != 0) { unsigned L = GetLocalLabel(); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", (unsigned char) val); AddCodeLine ("bcc %s", LocalLabelName (L)); AddCodeLine ("inx"); g_defcodelabel (L); } if (val >= 0x100) { AddCodeLine ("inx"); } if (val >= 0x200) { AddCodeLine ("inx"); } if (val >= 0x300) { AddCodeLine ("inx"); } } else if ((val & 0xFF) != 0) { AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", (unsigned char) val); AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("adc #$%02X", (unsigned char) (val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } else { AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("clc"); AddCodeLine ("adc #$%02X", (unsigned char) (val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } } break; case CF_LONG: if (val <= 255) { AddCodeLine ("ldy #$%02X", (unsigned char) val); AddCodeLine ("jsr inceaxy"); } else { g_add (flags | CF_CONST, val); } break; default: typeerror (flags); } } void g_dec (unsigned flags, unsigned long val) /* Decrement the primary register by a given number */ { /* Don't dec by zero */ if (val == 0) { return; } /* Generate code for the supported types */ flags &= ~CF_CONST; switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && val <= 2) { while (val--) { AddCodeLine ("dea"); } } else { AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); } break; } /* FALLTHROUGH */ case CF_INT: if (IS_Get (&CodeSizeFactor) < 200) { /* Use subroutines */ if (val <= 8) { AddCodeLine ("jsr decax%d", (int) val); } else if (val <= 255) { AddCodeLine ("ldy #$%02X", (unsigned char) val); AddCodeLine ("jsr decaxy"); } else { g_sub (flags | CF_CONST, val); } } else { /* Inline the code */ if (val < 0x300) { if ((val & 0xFF) != 0) { unsigned L = GetLocalLabel(); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char) val); AddCodeLine ("bcs %s", LocalLabelName (L)); AddCodeLine ("dex"); g_defcodelabel (L); } if (val >= 0x100) { AddCodeLine ("dex"); } if (val >= 0x200) { AddCodeLine ("dex"); } } else { if ((val & 0xFF) != 0) { AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char) val); AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char) (val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } else { AddCodeLine ("pha"); AddCodeLine ("txa"); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char) (val >> 8)); AddCodeLine ("tax"); AddCodeLine ("pla"); } } } break; case CF_LONG: if (val <= 255) { AddCodeLine ("ldy #$%02X", (unsigned char) val); AddCodeLine ("jsr deceaxy"); } else { g_sub (flags | CF_CONST, val); } break; default: typeerror (flags); } } /* * Following are the conditional operators. They compare the TOS against * the primary and put a literal 1 in the primary if the condition is * true, otherwise they clear the primary register */ void g_eq (unsigned flags, unsigned long val) /* Test for equal */ { static const char* ops[12] = { "toseqax", "toseqax", "toseqeax", "toseqeax", }; unsigned L; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("jsr booleq"); return; } /* FALLTHROUGH */ case CF_INT: L = GetLocalLabel(); AddCodeLine ("cpx #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("cmp #$%02X", (unsigned char)val); g_defcodelabel (L); AddCodeLine ("jsr booleq"); return; case CF_LONG: break; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_ne (unsigned flags, unsigned long val) /* Test for not equal */ { static const char* ops[12] = { "tosneax", "tosneax", "tosneeax", "tosneeax", }; unsigned L; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("jsr boolne"); return; } /* FALLTHROUGH */ case CF_INT: L = GetLocalLabel(); AddCodeLine ("cpx #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("cmp #$%02X", (unsigned char)val); g_defcodelabel (L); AddCodeLine ("jsr boolne"); return; case CF_LONG: break; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_lt (unsigned flags, unsigned long val) /* Test for less than */ { static const char* ops[12] = { "tosltax", "tosultax", "toslteax", "tosulteax", }; unsigned Label; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { /* Because the handling of the overflow flag is too complex for * inlining, we can handle only unsigned compares, and signed * compares against zero here. */ if (flags & CF_UNSIGNED) { /* Give a warning in some special cases */ if (val == 0) { Warning ("Condition is never true"); AddCodeLine ("jsr return0"); return; } /* Look at the type */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("jsr boolult"); return; } /* FALLTHROUGH */ case CF_INT: /* If the low byte is zero, we must only test the high byte */ AddCodeLine ("cpx #$%02X", (unsigned char)(val >> 8)); if ((val & 0xFF) != 0) { unsigned L = GetLocalLabel(); AddCodeLine ("bne %s", LocalLabelName (L)); AddCodeLine ("cmp #$%02X", (unsigned char)val); g_defcodelabel (L); } AddCodeLine ("jsr boolult"); return; case CF_LONG: /* Do a subtraction */ AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("lda sreg"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 16)); AddCodeLine ("lda sreg+1"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 24)); AddCodeLine ("jsr boolult"); return; default: typeerror (flags); } } else if (val == 0) { /* A signed compare against zero must only look at the sign bit */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; } /* FALLTHROUGH */ case CF_INT: /* Just check the high byte */ AddCodeLine ("cpx #$80"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; case CF_LONG: /* Just check the high byte */ AddCodeLine ("lda sreg+1"); AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; default: typeerror (flags); } } else { /* Signed compare against a constant != zero */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { Label = GetLocalLabel (); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); AddCodeLine ("bvc %s", LocalLabelName (Label)); AddCodeLine ("eor #$80"); g_defcodelabel (Label); AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; } /* FALLTHROUGH */ case CF_INT: /* Do a subtraction */ Label = GetLocalLabel (); AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("bvc %s", LocalLabelName (Label)); AddCodeLine ("eor #$80"); g_defcodelabel (Label); AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; case CF_LONG: /* This one is too costly */ break; default: typeerror (flags); } } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_le (unsigned flags, unsigned long val) /* Test for less than or equal to */ { static const char* ops[12] = { "tosleax", "tosuleax", "tosleeax", "tosuleeax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { /* Look at the type */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if (flags & CF_UNSIGNED) { /* Unsigned compare */ if (val < 0xFF) { /* Use < instead of <= because the former gives * better code on the 6502 than the latter. */ g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } else { /* Signed compare */ if ((long) val < 0x7F) { /* Use < instead of <= because the former gives * better code on the 6502 than the latter. */ g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } return; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_UNSIGNED) { /* Unsigned compare */ if (val < 0xFFFF) { /* Use < instead of <= because the former gives * better code on the 6502 than the latter. */ g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } else { /* Signed compare */ if ((long) val < 0x7FFF) { g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } return; case CF_LONG: if (flags & CF_UNSIGNED) { /* Unsigned compare */ if (val < 0xFFFFFFFF) { /* Use < instead of <= because the former gives * better code on the 6502 than the latter. */ g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } else { /* Signed compare */ if ((long) val < 0x7FFFFFFF) { g_lt (flags, val+1); } else { /* Always true */ Warning ("Condition is always true"); AddCodeLine ("jsr return1"); } } return; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_gt (unsigned flags, unsigned long val) /* Test for greater than */ { static const char* ops[12] = { "tosgtax", "tosugtax", "tosgteax", "tosugteax", }; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { /* Look at the type */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { if (flags & CF_UNSIGNED) { if (val == 0) { /* If we have a compare > 0, we will replace it by * != 0 here, since both are identical but the * latter is easier to optimize. */ g_ne (flags, val); } else if (val < 0xFF) { /* Use >= instead of > because the former gives * better code on the 6502 than the latter. */ g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } else { if ((long) val < 0x7F) { /* Use >= instead of > because the former gives * better code on the 6502 than the latter. */ g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } return; } /* FALLTHROUGH */ case CF_INT: if (flags & CF_UNSIGNED) { /* Unsigned compare */ if (val == 0) { /* If we have a compare > 0, we will replace it by * != 0 here, since both are identical but the latter * is easier to optimize. */ g_ne (flags, val); } else if (val < 0xFFFF) { /* Use >= instead of > because the former gives better * code on the 6502 than the latter. */ g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } else { /* Signed compare */ if ((long) val < 0x7FFF) { g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } return; case CF_LONG: if (flags & CF_UNSIGNED) { /* Unsigned compare */ if (val == 0) { /* If we have a compare > 0, we will replace it by * != 0 here, since both are identical but the latter * is easier to optimize. */ g_ne (flags, val); } else if (val < 0xFFFFFFFF) { /* Use >= instead of > because the former gives better * code on the 6502 than the latter. */ g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } else { /* Signed compare */ if ((long) val < 0x7FFFFFFF) { g_ge (flags, val+1); } else { /* Never true */ Warning ("Condition is never true"); AddCodeLine ("jsr return0"); } } return; default: typeerror (flags); } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } void g_ge (unsigned flags, unsigned long val) /* Test for greater than or equal to */ { static const char* ops[12] = { "tosgeax", "tosugeax", "tosgeeax", "tosugeeax", }; unsigned Label; /* If the right hand side is const, the lhs is not on stack but still * in the primary register. */ if (flags & CF_CONST) { /* Because the handling of the overflow flag is too complex for * inlining, we can handle only unsigned compares, and signed * compares against zero here. */ if (flags & CF_UNSIGNED) { /* Give a warning in some special cases */ if (val == 0) { Warning ("Condition is always true"); AddCodeLine ("jsr return1"); return; } /* Look at the type */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { /* Do a subtraction. Condition is true if carry set */ AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; } /* FALLTHROUGH */ case CF_INT: /* Do a subtraction. Condition is true if carry set */ AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; case CF_LONG: /* Do a subtraction. Condition is true if carry set */ AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("lda sreg"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 16)); AddCodeLine ("lda sreg+1"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 24)); AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; default: typeerror (flags); } } else if (val == 0) { /* A signed compare against zero must only look at the sign bit */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { AddCodeLine ("tax"); AddCodeLine ("jsr boolge"); return; } /* FALLTHROUGH */ case CF_INT: /* Just test the high byte */ AddCodeLine ("txa"); AddCodeLine ("jsr boolge"); return; case CF_LONG: /* Just test the high byte */ AddCodeLine ("lda sreg+1"); AddCodeLine ("jsr boolge"); return; default: typeerror (flags); } } else { /* Signed compare against a constant != zero */ switch (flags & CF_TYPEMASK) { case CF_CHAR: if (flags & CF_FORCECHAR) { Label = GetLocalLabel (); AddCodeLine ("sec"); AddCodeLine ("sbc #$%02X", (unsigned char)val); AddCodeLine ("bvs %s", LocalLabelName (Label)); AddCodeLine ("eor #$80"); g_defcodelabel (Label); AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; } /* FALLTHROUGH */ case CF_INT: /* Do a subtraction */ Label = GetLocalLabel (); AddCodeLine ("cmp #$%02X", (unsigned char)val); AddCodeLine ("txa"); AddCodeLine ("sbc #$%02X", (unsigned char)(val >> 8)); AddCodeLine ("bvs %s", LocalLabelName (Label)); AddCodeLine ("eor #$80"); g_defcodelabel (Label); AddCodeLine ("asl a"); /* Bit 7 -> carry */ AddCodeLine ("lda #$00"); AddCodeLine ("ldx #$00"); AddCodeLine ("rol a"); return; case CF_LONG: /* This one is too costly */ break; default: typeerror (flags); } } /* If we go here, we didn't emit code. Push the lhs on stack and fall * into the normal, non-optimized stuff. Note: The standard stuff will * always work with ints. */ flags &= ~CF_FORCECHAR; g_push (flags & ~CF_CONST, 0); } /* Use long way over the stack */ oper (flags, val, ops); } /*****************************************************************************/ /* Allocating static storage */ /*****************************************************************************/ void g_res (unsigned n) /* Reserve static storage, n bytes */ { AddDataLine ("\t.res\t%u,$00", n); } void g_defdata (unsigned flags, unsigned long val, long offs) /* Define data with the size given in flags */ { if (flags & CF_CONST) { /* Numeric constant */ switch (flags & CF_TYPEMASK) { case CF_CHAR: AddDataLine ("\t.byte\t$%02lX", val & 0xFF); break; case CF_INT: AddDataLine ("\t.word\t$%04lX", val & 0xFFFF); break; case CF_LONG: AddDataLine ("\t.dword\t$%08lX", val & 0xFFFFFFFF); break; default: typeerror (flags); break; } } else { /* Create the correct label name */ const char* Label = GetLabelName (flags, val, offs); /* Labels are always 16 bit */ AddDataLine ("\t.addr\t%s", Label); } } void g_defbytes (const void* Bytes, unsigned Count) /* Output a row of bytes as a constant */ { unsigned Chunk; char Buf [128]; char* B; /* Cast the buffer pointer */ const unsigned char* Data = (const unsigned char*) Bytes; /* Output the stuff */ while (Count) { /* How many go into this line? */ if ((Chunk = Count) > 16) { Chunk = 16; } Count -= Chunk; /* Output one line */ strcpy (Buf, "\t.byte\t"); B = Buf + 7; do { B += sprintf (B, "$%02X", *Data++); if (--Chunk) { *B++ = ','; } } while (Chunk); /* Output the line */ AddDataLine ("%s", Buf); } } void g_zerobytes (unsigned Count) /* Output Count bytes of data initialized with zero */ { if (Count > 0) { AddDataLine ("\t.res\t%u,$00", Count); } } void g_initregister (unsigned Label, unsigned Reg, unsigned Size) /* Initialize a register variable from static initialization data */ { /* Register variables do always have less than 128 bytes */ unsigned CodeLabel = GetLocalLabel (); AddCodeLine ("ldx #$%02X", (unsigned char) (Size - 1)); g_defcodelabel (CodeLabel); AddCodeLine ("lda %s,x", GetLabelName (CF_STATIC, Label, 0)); AddCodeLine ("sta %s,x", GetLabelName (CF_REGVAR, Reg, 0)); AddCodeLine ("dex"); AddCodeLine ("bpl %s", LocalLabelName (CodeLabel)); } void g_initauto (unsigned Label, unsigned Size) /* Initialize a local variable at stack offset zero from static data */ { unsigned CodeLabel = GetLocalLabel (); CheckLocalOffs (Size); if (Size <= 128) { AddCodeLine ("ldy #$%02X", Size-1); g_defcodelabel (CodeLabel); AddCodeLine ("lda %s,y", GetLabelName (CF_STATIC, Label, 0)); AddCodeLine ("sta (sp),y"); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (CodeLabel)); } else if (Size <= 256) { AddCodeLine ("ldy #$00"); g_defcodelabel (CodeLabel); AddCodeLine ("lda %s,y", GetLabelName (CF_STATIC, Label, 0)); AddCodeLine ("sta (sp),y"); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Size); AddCodeLine ("bne %s", LocalLabelName (CodeLabel)); } } void g_initstatic (unsigned InitLabel, unsigned VarLabel, unsigned Size) /* Initialize a static local variable from static initialization data */ { if (Size <= 128) { unsigned CodeLabel = GetLocalLabel (); AddCodeLine ("ldy #$%02X", Size-1); g_defcodelabel (CodeLabel); AddCodeLine ("lda %s,y", GetLabelName (CF_STATIC, InitLabel, 0)); AddCodeLine ("sta %s,y", GetLabelName (CF_STATIC, VarLabel, 0)); AddCodeLine ("dey"); AddCodeLine ("bpl %s", LocalLabelName (CodeLabel)); } else if (Size <= 256) { unsigned CodeLabel = GetLocalLabel (); AddCodeLine ("ldy #$00"); g_defcodelabel (CodeLabel); AddCodeLine ("lda %s,y", GetLabelName (CF_STATIC, InitLabel, 0)); AddCodeLine ("sta %s,y", GetLabelName (CF_STATIC, VarLabel, 0)); AddCodeLine ("iny"); AddCodeLine ("cpy #$%02X", (unsigned char) Size); AddCodeLine ("bne %s", LocalLabelName (CodeLabel)); } else { /* Use the easy way here: memcpy */ g_getimmed (CF_STATIC, VarLabel, 0); AddCodeLine ("jsr pushax"); g_getimmed (CF_STATIC, InitLabel, 0); AddCodeLine ("jsr pushax"); g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, Size, 0); AddCodeLine ("jsr %s", GetLabelName (CF_EXTERNAL, (unsigned long) "memcpy", 0)); } } /*****************************************************************************/ /* Switch statement */ /*****************************************************************************/ void g_switch (Collection* Nodes, unsigned DefaultLabel, unsigned Depth) /* Generate code for a switch statement */ { unsigned NextLabel = 0; unsigned I; /* Setup registers and determine which compare insn to use */ const char* Compare; switch (Depth) { case 1: Compare = "cmp #$%02X"; break; case 2: Compare = "cpx #$%02X"; break; case 3: AddCodeLine ("ldy sreg"); Compare = "cpy #$%02X"; break; case 4: AddCodeLine ("ldy sreg+1"); Compare = "cpy #$%02X"; break; default: Internal ("Invalid depth in g_switch: %u", Depth); } /* Walk over all nodes */ for (I = 0; I < CollCount (Nodes); ++I) { /* Get the next case node */ CaseNode* N = CollAtUnchecked (Nodes, I); /* If we have a next label, define it */ if (NextLabel) { g_defcodelabel (NextLabel); NextLabel = 0; } /* Do the compare */ AddCodeLine (Compare, CN_GetValue (N)); /* If this is the last level, jump directly to the case code if found */ if (Depth == 1) { /* Branch if equal */ g_falsejump (0, CN_GetLabel (N)); } else { /* Determine the next label */ if (I == CollCount (Nodes) - 1) { /* Last node means not found */ g_truejump (0, DefaultLabel); } else { /* Jump to the next check */ NextLabel = GetLocalLabel (); g_truejump (0, NextLabel); } /* Check the next level */ g_switch (N->Nodes, DefaultLabel, Depth-1); } } /* If we go here, we haven't found the label */ g_jump (DefaultLabel); } /*****************************************************************************/ /* User supplied assembler code */ /*****************************************************************************/ void g_asmcode (struct StrBuf* B) /* Output one line of assembler code. */ { AddCodeLine ("%.*s", (int) SB_GetLen (B), SB_GetConstBuf (B)); }
879
./cc65/src/cc65/locals.c
/*****************************************************************************/ /* */ /* locals.c */ /* */ /* Local variable handling for the cc65 C compiler */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "xmalloc.h" #include "xsprintf.h" /* cc65 */ #include "anonname.h" #include "asmlabel.h" #include "codegen.h" #include "declare.h" #include "error.h" #include "expr.h" #include "function.h" #include "global.h" #include "loadexpr.h" #include "locals.h" #include "stackptr.h" #include "standard.h" #include "symtab.h" #include "typeconv.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static unsigned AllocLabel (void (*UseSeg) ()) /* Switch to a segment, define a local label and return it */ { unsigned Label; /* Switch to the segment */ UseSeg (); /* Define the variable label */ Label = GetLocalLabel (); g_defdatalabel (Label); /* Return the label */ return Label; } static void AllocStorage (unsigned Label, void (*UseSeg) (), unsigned Size) /* Reserve Size bytes of BSS storage prefixed by a local label. */ { /* Switch to the segment */ UseSeg (); /* Define the variable label */ g_defdatalabel (Label); /* Reserve space for the data */ g_res (Size); } static void ParseRegisterDecl (Declaration* Decl, int Reg) /* Parse the declaration of a register variable. Reg is the offset of the * variable in the register bank. */ { SymEntry* Sym; /* Determine if this is a compound variable */ int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type); /* Get the size of the variable */ unsigned Size = SizeOf (Decl->Type); /* Save the current contents of the register variable on stack */ F_AllocLocalSpace (CurrentFunc); g_save_regvars (Reg, Size); /* Add the symbol to the symbol table. We do that now, because for register * variables the current stack pointer is implicitly used as location for * the save area. */ Sym = AddLocalSym (Decl->Ident, Decl->Type, Decl->StorageClass, Reg); /* Check for an optional initialization */ if (CurTok.Tok == TOK_ASSIGN) { ExprDesc Expr; /* Skip the '=' */ NextToken (); /* Special handling for compound types */ if (IsCompound) { /* Switch to read only data and define a label for the * initialization data. */ unsigned InitLabel = AllocLabel (g_userodata); /* Parse the initialization generating a memory image of the * data in the RODATA segment. The function does return the size * of the initialization data, which may be greater than the * actual size of the type, if the type is a structure with a * flexible array member that has been initialized. Since we must * know the size of the data in advance for register variables, * we cannot allow that here. */ if (ParseInit (Sym->Type) != Size) { Error ("Cannot initialize flexible array members of storage class `register'"); } /* Generate code to copy this data into the variable space */ g_initregister (InitLabel, Reg, Size); } else { /* Parse the expression */ hie1 (&Expr); /* Convert it to the target type */ TypeConversion (&Expr, Sym->Type); /* Load the value into the primary */ LoadExpr (CF_NONE, &Expr); /* Store the value into the variable */ g_putstatic (CF_REGVAR | TypeOf (Sym->Type), Reg, 0); } /* Mark the variable as referenced */ Sym->Flags |= SC_REF; } /* Cannot allocate a variable of zero size */ if (Size == 0) { Error ("Variable `%s' has unknown size", Decl->Ident); } } static void ParseAutoDecl (Declaration* Decl) /* Parse the declaration of an auto variable. */ { unsigned Flags; SymEntry* Sym; /* Determine if this is a compound variable */ int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type); /* Get the size of the variable */ unsigned Size = SizeOf (Decl->Type); /* Check if this is a variable on the stack or in static memory */ if (IS_Get (&StaticLocals) == 0) { /* Add the symbol to the symbol table. The stack offset we use here * may get corrected later. */ Sym = AddLocalSym (Decl->Ident, Decl->Type, Decl->StorageClass, F_GetStackPtr (CurrentFunc) - (int) Size); /* Check for an optional initialization */ if (CurTok.Tok == TOK_ASSIGN) { ExprDesc Expr; /* Skip the '=' */ NextToken (); /* Special handling for compound types */ if (IsCompound) { /* Switch to read only data and define a label for the * initialization data. */ unsigned InitLabel = AllocLabel (g_userodata); /* Parse the initialization generating a memory image of the * data in the RODATA segment. The function will return the * actual size of the initialization data, which may be * greater than the size of the variable if it is a struct * that contains a flexible array member and we're not in * ANSI mode. */ Size = ParseInit (Sym->Type); /* Now reserve space for the variable on the stack and correct * the offset in the symbol table entry. */ Sym->V.Offs = F_ReserveLocalSpace (CurrentFunc, Size); /* Next, allocate the space on the stack. This means that the * variable is now located at offset 0 from the current sp. */ F_AllocLocalSpace (CurrentFunc); /* Generate code to copy the initialization data into the * variable space */ g_initauto (InitLabel, Size); } else { /* Allocate previously reserved local space */ F_AllocLocalSpace (CurrentFunc); /* Setup the type flags for the assignment */ Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE; /* Parse the expression */ hie1 (&Expr); /* Convert it to the target type */ TypeConversion (&Expr, Sym->Type); /* If the value is not const, load it into the primary. * Otherwise pass the information to the code generator. */ if (ED_IsConstAbsInt (&Expr)) { Flags |= CF_CONST; } else { LoadExpr (CF_NONE, &Expr); ED_MakeRVal (&Expr); } /* Push the value */ g_push (Flags | TypeOf (Sym->Type), Expr.IVal); } /* Mark the variable as referenced */ Sym->Flags |= SC_REF; } else { /* Non-initialized local variable. Just keep track of * the space needed. */ F_ReserveLocalSpace (CurrentFunc, Size); } } else { unsigned DataLabel; /* Static local variables. */ Decl->StorageClass = (Decl->StorageClass & ~SC_AUTO) | SC_STATIC; /* Generate a label, but don't define it */ DataLabel = GetLocalLabel (); /* Add the symbol to the symbol table. */ Sym = AddLocalSym (Decl->Ident, Decl->Type, Decl->StorageClass, DataLabel); /* Allow assignments */ if (CurTok.Tok == TOK_ASSIGN) { ExprDesc Expr; /* Skip the '=' */ NextToken (); if (IsCompound) { /* Switch to read only data and define a label for the * initialization data. */ unsigned InitLabel = AllocLabel (g_userodata); /* Parse the initialization generating a memory image of the * data in the RODATA segment. */ Size = ParseInit (Sym->Type); /* Allocate space for the variable */ AllocStorage (DataLabel, g_usebss, Size); /* Generate code to copy this data into the variable space */ g_initstatic (InitLabel, DataLabel, Size); } else { /* Allocate space for the variable */ AllocStorage (DataLabel, g_usebss, Size); /* Parse the expression */ hie1 (&Expr); /* Convert it to the target type */ TypeConversion (&Expr, Sym->Type); /* Load the value into the primary */ LoadExpr (CF_NONE, &Expr); /* Store the value into the variable */ g_putstatic (TypeOf (Sym->Type), DataLabel, 0); } /* Mark the variable as referenced */ Sym->Flags |= SC_REF; } else { /* No assignment - allocate a label and space for the variable */ AllocStorage (DataLabel, g_usebss, Size); } } /* Cannot allocate a variable of zero size */ if (Size == 0) { Error ("Variable `%s' has unknown size", Decl->Ident); } } static void ParseStaticDecl (Declaration* Decl) /* Parse the declaration of a static variable. */ { unsigned Size; /* Generate a label, but don't define it */ unsigned DataLabel = GetLocalLabel (); /* Add the symbol to the symbol table. */ SymEntry* Sym = AddLocalSym (Decl->Ident, Decl->Type, Decl->StorageClass, DataLabel); /* Static data */ if (CurTok.Tok == TOK_ASSIGN) { /* Initialization ahead, switch to data segment and define the label. * For arrays, we need to check the elements of the array for * constness, not the array itself. */ if (IsQualConst (GetBaseElementType (Sym->Type))) { g_userodata (); } else { g_usedata (); } g_defdatalabel (DataLabel); /* Skip the '=' */ NextToken (); /* Allow initialization of static vars */ Size = ParseInit (Sym->Type); /* Mark the variable as referenced */ Sym->Flags |= SC_REF; } else { /* Get the size of the variable */ Size = SizeOf (Decl->Type); /* Allocate a label and space for the variable in the BSS segment */ AllocStorage (DataLabel, g_usebss, Size); } /* Cannot allocate a variable of zero size */ if (Size == 0) { Error ("Variable `%s' has unknown size", Decl->Ident); } } static void ParseOneDecl (const DeclSpec* Spec) /* Parse one variable declaration */ { Declaration Decl; /* Declaration data structure */ /* Read the declaration */ ParseDecl (Spec, &Decl, DM_NEED_IDENT); /* Set the correct storage class for functions */ if ((Decl.StorageClass & SC_FUNC) == SC_FUNC) { /* Function prototypes are always external */ if ((Decl.StorageClass & SC_EXTERN) == 0) { Warning ("Function must be extern"); } Decl.StorageClass |= SC_EXTERN; } /* If we don't have a name, this was flagged as an error earlier. * To avoid problems later, use an anonymous name here. */ if (Decl.Ident[0] == '\0') { AnonName (Decl.Ident, "param"); } /* If the symbol is not marked as external, it will be defined now */ if ((Decl.StorageClass & SC_EXTERN) == 0) { Decl.StorageClass |= SC_DEF; } /* Handle anything that needs storage (no functions, no typdefs) */ if ((Decl.StorageClass & SC_FUNC) != SC_FUNC && (Decl.StorageClass & SC_TYPEMASK) != SC_TYPEDEF) { /* If we have a register variable, try to allocate a register and * convert the declaration to "auto" if this is not possible. */ int Reg = 0; /* Initialize to avoid gcc complains */ if ((Decl.StorageClass & SC_REGISTER) != 0 && (Reg = F_AllocRegVar (CurrentFunc, Decl.Type)) < 0) { /* No space for this register variable, convert to auto */ Decl.StorageClass = (Decl.StorageClass & ~SC_REGISTER) | SC_AUTO; } /* Check the variable type */ if ((Decl.StorageClass & SC_REGISTER) == SC_REGISTER) { /* Register variable */ ParseRegisterDecl (&Decl, Reg); } else if ((Decl.StorageClass & SC_AUTO) == SC_AUTO) { /* Auto variable */ ParseAutoDecl (&Decl); } else if ((Decl.StorageClass & SC_EXTERN) == SC_EXTERN) { /* External identifier - may not get initialized */ if (CurTok.Tok == TOK_ASSIGN) { Error ("Cannot initialize externals"); } /* Add the external symbol to the symbol table */ AddLocalSym (Decl.Ident, Decl.Type, Decl.StorageClass, 0); } else if ((Decl.StorageClass & SC_STATIC) == SC_STATIC) { /* Static variable */ ParseStaticDecl (&Decl); } else { Internal ("Invalid storage class in ParseOneDecl: %04X", Decl.StorageClass); } } else { /* Add the symbol to the symbol table */ AddLocalSym (Decl.Ident, Decl.Type, Decl.StorageClass, 0); } } void DeclareLocals (void) /* Declare local variables and types. */ { /* Remember the current stack pointer */ int InitialStack = StackPtr; /* Loop until we don't find any more variables */ while (1) { /* Check variable declarations. We need to distinguish between a * default int type and the end of variable declarations. So we * will do the following: If there is no explicit storage class * specifier *and* no explicit type given, *and* no type qualifiers * have been read, it is assumed that we have reached the end of * declarations. */ DeclSpec Spec; ParseDeclSpec (&Spec, SC_AUTO, T_INT); if ((Spec.Flags & DS_DEF_STORAGE) != 0 && /* No storage spec */ (Spec.Flags & DS_DEF_TYPE) != 0 && /* No type given */ GetQualifier (Spec.Type) == T_QUAL_NONE) { /* No type qualifier */ break; } /* Accept type only declarations */ if (CurTok.Tok == TOK_SEMI) { /* Type declaration only */ CheckEmptyDecl (&Spec); NextToken (); continue; } /* Parse a comma separated variable list */ while (1) { /* Parse one declaration */ ParseOneDecl (&Spec); /* Check if there is more */ if (CurTok.Tok == TOK_COMMA) { /* More to come */ NextToken (); } else { /* Done */ break; } } /* A semicolon must follow */ ConsumeSemi (); } /* Be sure to allocate any reserved space for locals */ F_AllocLocalSpace (CurrentFunc); /* In case we've allocated local variables in this block, emit a call to * the stack checking routine if stack checks are enabled. */ if (IS_Get (&CheckStack) && InitialStack != StackPtr) { g_cstackcheck (); } }
880
./cc65/src/dbginfo/dbgsh.c
/*****************************************************************************/ /* */ /* dbgsh.c */ /* */ /* debug info test shell */ /* */ /* */ /* */ /* (C) 2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <time.h> #include <errno.h> /* common */ #include "attrib.h" #include "chartype.h" #include "cmdline.h" #include "coll.h" /* dbginfo */ #include "dbginfo.h" /*****************************************************************************/ /* Command handler forwards */ /*****************************************************************************/ static void CmdHelp (Collection* Args attribute ((unused))); /* Output a help text */ static void CmdLoad (Collection* Args); /* Load a debug info file */ static void CmdQuit (Collection* Args attribute ((unused))); /* Terminate the application */ static void CmdShow (Collection* Args); /* Show items from the debug info file */ static void CmdShowHelp (Collection* Args); /* Print help for the show command */ static void CmdShowChildScopes (Collection* Args); /* Show child scopes from the debug info file */ static void CmdShowCSymbol (Collection* Args); /* Show c symbols from the debug info file */ static void CmdShowFunction (Collection* Args); /* Show C functions from the debug info file */ static void CmdShowLibrary (Collection* Args); /* Show libraries from the debug info file */ static void CmdShowLine (Collection* Args); /* Show lines from the debug info file */ static void CmdShowModule (Collection* Args); /* Show modules from the debug info file */ static void CmdShowScope (Collection* Args); /* Show scopes from the debug info file */ static void CmdShowSegment (Collection* Args); /* Show segments from the debug info file */ static void CmdShowSource (Collection* Args); /* Show source files from the debug info file */ static void CmdShowSpan (Collection* Args); /* Show spans from the debug info file */ static void CmdShowSymbol (Collection* Args); /* Show symbols */ static void CmdShowSymDef (Collection* Args); /* Show lines from the debug info file */ static void CmdShowSymRef (Collection* Args); /* Show lines from the debug info file */ static void CmdShowType (Collection* Args); /* Show types from the debug info file */ static void CmdUnload (Collection* Args attribute ((unused))); /* Unload a debug info file */ /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Terminate flag - end program when set to true */ static int Terminate = 0; /* The debug file data */ static cc65_dbginfo Info = 0; /* Error and warning counters */ static unsigned FileErrors = 0; static unsigned FileWarnings = 0; /* Type of an id */ enum { InvalidId, CSymbolId, LibraryId, LineId, ModuleId, ScopeId, SegmentId, SourceId, SpanId, SymbolId, TypeId }; /* Structure that contains a command description */ typedef struct CmdEntry CmdEntry; struct CmdEntry { char Cmd[12]; const char* Help; int ArgCount; void (*Func) (Collection*); }; /* Table with main commands */ static const CmdEntry MainCmds[] = { { "exit", 0, 1, CmdQuit }, { "help", "Show available commands", 1, CmdHelp }, { "load", "Load a debug info file", 2, CmdLoad }, { "quit", "Terminate the shell", 1, CmdQuit }, { "show", "Show items from the info file", -2, CmdShow }, { "unload", "Unload a debug info file", 1, CmdUnload }, }; /* Table with show commands */ static const CmdEntry ShowCmds[] = { { "childscopes", "Show child scopes of other scopes.", -2, CmdShowChildScopes }, { "csym", 0, -1, CmdShowCSymbol }, { "csymbol", "Show c symbols.", -1, CmdShowCSymbol }, { "func", 0, -2, CmdShowFunction }, { "function", "Show c functions.", -2, CmdShowFunction }, { "help", "Show available subcommands.", 1, CmdShowHelp }, { "line", "Show line info. May be followed by one or more line ids.", -2, CmdShowLine }, { "library", "Show libraries. May be followed by one or more library ids.", -1, CmdShowLibrary }, { "module", "Show modules. May be followed by one or more module ids.", -1, CmdShowModule }, { "scope", "Show scopes. May be followed by one or more segment ids.", -1, CmdShowScope }, { "segment", "Show segments. May be followed by one or more segment ids.", -1, CmdShowSegment }, { "source", "Show sources. May be followed by one or more source file ids.", -1, CmdShowSource }, { "span", "Show spans. May be followed by one or more span ids.", -1, CmdShowSpan }, { "symbol", "Show symbols. May be followed by one or more symbol or scope ids.", -2, CmdShowSymbol }, { "symdef", "Show where a symbol was defined. May be followed by one or more symbol ids.", -2, CmdShowSymDef }, { "symref", "Show where a symbol was referenced. May be followed by one or more symbol ids.", -2, CmdShowSymRef }, { "type", "Show type information. May be followed by one or more type ids.", -2, CmdShowType }, }; /*****************************************************************************/ /* Helpers */ /*****************************************************************************/ static void NewLine (void) /* Output a newline */ { putchar ('\n'); } static void Print (const char* Format, ...) attribute((format(printf,1,2))); static void Print (const char* Format, ...) /* Print a piece of output (no linefeed added) */ { va_list ap; va_start (ap, Format); vprintf (Format, ap); va_end (ap); } static void PrintLine (const char* Format, ...) attribute((format(printf,1,2))); static void PrintLine (const char* Format, ...) /* Print one line of output. The linefeed is supplied by the function */ { va_list ap; va_start (ap, Format); vprintf (Format, ap); NewLine (); va_end (ap); } static void PrintSeparator (void) /* Print a separator line */ { PrintLine ("---------------------------------------------------------------------------"); } static void FileError (const cc65_parseerror* Info) /* Callback function - is called in case of errors */ { /* Output a message */ PrintLine ("%s:%s(%lu): %s", Info->type? "Error" : "Warning", Info->name, (unsigned long) Info->line, Info->errormsg); /* Bump the counters */ switch (Info->type) { case CC65_WARNING: ++FileWarnings; break; default: ++FileErrors; break; } } static const CmdEntry* FindCmd (const char* Cmd, const CmdEntry* Tab, unsigned Count) /* Search for a command in the given table */ { unsigned I; for (I = 0; I < Count; ++I, ++Tab) { if (strcmp (Cmd, Tab->Cmd) == 0) { return Tab; } } return 0; } static void ExecCmd (Collection* Args, const CmdEntry* Tab, unsigned Count) /* Search for the command in slot 0 of the given collection. If found, check * the argument count, then execute it. If there are problems, output a * diagnostic. */ { /* Search for the command, check number of args, then execute it */ const char* Cmd = CollAt (Args, 0); const CmdEntry* E = FindCmd (Cmd, Tab, Count); if (E == 0) { PrintLine ("No such command: %s", Cmd); return; } /* Check the number of arguments. Zero means that the function will check * itself. A negative count means that the function needs at least * abs(count) arguments. A positive count means that the function needs * exactly this number of arguments. * Note: The number includes the command itself. */ if (E->ArgCount > 0 && (int)CollCount (Args) != E->ArgCount) { /* Argument number mismatch */ switch (E->ArgCount) { case 1: PrintLine ("Command doesn't accept an argument"); return; case 2: PrintLine ("Command requires an argument"); return; default: PrintLine ("Command requires %d arguments", E->ArgCount-1); return; } } else if (E->ArgCount < 0 && (int)CollCount (Args) < -E->ArgCount) { /* Argument number mismatch */ switch (E->ArgCount) { case -2: PrintLine ("Command requires at least one argument"); return; default: PrintLine ("Command requires at least %d arguments", E->ArgCount-1); return; } } else { /* Remove the command from the argument list, then execute it */ CollDelete (Args, 0); E->Func (Args); } } static void PrintHelp (const CmdEntry* Tab, unsigned Count) /* Output help for one command table */ { while (Count--) { /* Ignore the commands without help text */ if (Tab->Help) { PrintLine ("%-*s%s", (int) sizeof (Tab->Cmd) + 2, Tab->Cmd, Tab->Help); } ++Tab; } } static unsigned FindIdType (const char* TypeName) /* Find an id type by its name. Returns the type or InvalidId. */ { static const struct { char Name[8]; unsigned Type; } TypeTab[] = { { "l", LineId }, { "lib", LibraryId }, { "library", LibraryId }, { "line", LineId }, { "m", ModuleId }, { "mod", ModuleId }, { "module", ModuleId }, { "s", SymbolId }, { "sc", ScopeId }, { "scope", ScopeId }, { "seg", SegmentId }, { "segment", SegmentId }, { "source", SourceId }, { "src", SourceId }, { "sp", SpanId }, { "span", SpanId }, { "sym", SymbolId }, { "symbol", SymbolId }, { "t", TypeId }, { "type", TypeId }, }; unsigned I; for (I = 0; I < sizeof(TypeTab) / sizeof(TypeTab[0]); ++I) { if (strcmp (TypeName, TypeTab[I].Name) == 0) { return TypeTab[I].Type; } } return InvalidId; } static int GetId (const char* S, unsigned* Id, unsigned* IdType) /* Parse a string for an id. If a valid id is found, it is placed in Id and * the function returns true. If an optional type is found, it is placed in * IdType, otherwise IdType is left unchanged. If no id is found, the * function returns false. */ { char TypeBuf[20]; char C; if (sscanf (S, "%u%c", Id, &C) == 1) { /* Just an id found, return it */ return 1; } if (sscanf (S, "%19[a-z]:%u%c", TypeBuf, Id, &C) == 2) { *IdType = FindIdType (TypeBuf); return (*IdType != InvalidId); } /* Not a valid id */ return 0; } /*****************************************************************************/ /* Output functions for item lists */ /*****************************************************************************/ static void PrintAddr (cc65_addr Addr, unsigned FieldWidth) /* Output an address */ { Print ("$%06lX", (unsigned long) Addr); if (FieldWidth > 7) { Print ("%*s", FieldWidth - 7, ""); } } static void PrintNumber (long Num, unsigned Width, unsigned FieldWidth) /* Output a number */ { Print ("%*ld", Width, Num); if (FieldWidth > Width) { Print ("%*s", FieldWidth - Width, ""); } } static void PrintId (unsigned Id, unsigned FieldWidth) /* Output an id field */ { if (Id == CC65_INV_ID) { Print (" -"); } else { Print ("%4u", Id); } if (FieldWidth > 4) { Print ("%*s", FieldWidth - 4, ""); } } static void PrintSize (cc65_size Size, unsigned FieldWidth) /* Output a size */ { Print ("$%04lX", (unsigned long) Size); if (FieldWidth > 5) { Print ("%*s", FieldWidth - 5, ""); } } static void PrintTime (time_t T, unsigned FieldWidth) /* Output a time stamp of some sort */ { /* Convert to string */ char Buf[100]; unsigned Len = strftime (Buf, sizeof (Buf), "%Y-%m-%d %H:%M:%S", localtime (&T)); /* Output */ Print ("%s", Buf); if (FieldWidth > Len) { Print ("%*s", FieldWidth - Len, ""); } } static void PrintCSymbolHeader (void) /* Output a header for a list of C symbols */ { /* Header */ PrintLine (" id name type kind sc offs symbol scope"); PrintSeparator (); } static void PrintCSymbols (const cc65_csyminfo* S) /* Output a list of C symbols */ { unsigned I; const cc65_csymdata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->csym_id, 6); Print ("%-28s", D->csym_name); PrintId (D->type_id, 6); PrintNumber (D->csym_kind, 4, 6); PrintNumber (D->csym_sc, 4, 6); PrintNumber (D->csym_offs, 4, 8); PrintId (D->symbol_id, 6); PrintId (D->scope_id, 0); NewLine (); } } static void PrintLibraryHeader (void) /* Output the header for a library list */ { PrintLine (" id name"); PrintSeparator (); } static void PrintLibraries (const cc65_libraryinfo* L) /* Output a list of libraries */ { unsigned I; const cc65_librarydata* D; /* Libraries */ for (I = 0, D = L->data; I < L->count; ++I, ++D) { PrintId (D->library_id, 8); Print ("%-24s", D->library_name); NewLine (); } } static void PrintLineHeader (void) /* Output a header for a line list */ { /* Header */ PrintLine (" id source line type count"); PrintSeparator (); } static void PrintLines (const cc65_lineinfo* L) /* Output a list of lines */ { unsigned I; const cc65_linedata* D; /* Lines */ for (I = 0, D = L->data; I < L->count; ++I, ++D) { PrintId (D->line_id, 8); PrintId (D->source_id, 8); PrintNumber (D->source_line, 6, 9); PrintNumber (D->line_type, 4, 6); PrintNumber (D->count, 3, 0); NewLine (); } } static void PrintModuleHeader (void) /* Output a header for a module list */ { /* Header */ PrintLine (" id name source library scope"); PrintSeparator (); } static void PrintModules (const cc65_moduleinfo* M) /* Output a list of modules */ { unsigned I; const cc65_moduledata* D; /* Modules */ for (I = 0, D = M->data; I < M->count; ++I, ++D) { PrintId (D->module_id, 8); Print ("%-24s", D->module_name); PrintId (D->source_id, 8); PrintId (D->library_id, 9); PrintId (D->scope_id, 6); NewLine (); } } static void PrintScopeHeader (void) /* Output a header for a list of scopes */ { /* Header */ PrintLine (" id name type size parent symbol module"); PrintSeparator (); } static void PrintScopes (const cc65_scopeinfo* S) /* Output a list of scopes */ { unsigned I; const cc65_scopedata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->scope_id, 8); Print ("%-24s", D->scope_name); PrintNumber (D->scope_type, 4, 8); /* ## */ PrintSize (D->scope_size, 8); PrintId (D->parent_id, 8); PrintId (D->symbol_id, 8); PrintId (D->module_id, 0); NewLine (); } } static void PrintSegmentHeader (void) /* Output a header for a list of segments */ { /* Header */ PrintLine (" id name address size output file offs"); PrintSeparator (); } static void PrintSegments (const cc65_segmentinfo* S) /* Output a list of segments */ { unsigned I; const cc65_segmentdata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->segment_id, 8); Print ("%-16s", D->segment_name); PrintAddr (D->segment_start, 9); PrintSize (D->segment_size, 7); Print ("%-16s", D->output_name? D->output_name : ""); PrintSize (D->output_offs, 6); NewLine (); } } static void PrintSourceHeader (void) /* Output a header for a list of source files */ { /* Header */ PrintLine (" id name size modification time"); PrintSeparator (); } static void PrintSources (const cc65_sourceinfo* S) /* Output a list of sources */ { unsigned I; const cc65_sourcedata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->source_id, 8); Print ("%-30s", D->source_name); PrintNumber (D->source_size, 7, 9); PrintTime (D->source_mtime, 0); NewLine (); } } static void PrintSpanHeader (void) /* Output a header for a list of spans */ { /* Header */ PrintLine (" id start end seg type lines scopes"); PrintSeparator (); } static void PrintSpans (const cc65_spaninfo* S) /* Output a list of spans */ { unsigned I; const cc65_spandata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->span_id, 7); PrintAddr (D->span_start, 8); PrintAddr (D->span_end, 9); PrintId (D->segment_id, 7); PrintId (D->type_id, 6); PrintNumber (D->line_count, 6, 7); PrintNumber (D->scope_count, 7, 0); NewLine (); } } static void PrintSymbolHeader (void) /* Output a header for a list of symbols */ { /* Header */ PrintLine (" id name type size value export seg scope parent"); PrintSeparator (); } static void PrintSymbols (const cc65_symbolinfo* S) /* Output a list of symbols */ { unsigned I; const cc65_symboldata* D; /* Segments */ for (I = 0, D = S->data; I < S->count; ++I, ++D) { PrintId (D->symbol_id, 6); Print ("%-24s", D->symbol_name); PrintNumber (D->symbol_type, 4, 6); PrintNumber (D->symbol_size, 4, 6); PrintNumber (D->symbol_value, 5, 7); PrintId (D->export_id, 7); PrintId (D->segment_id, 6); PrintId (D->scope_id, 6); PrintId (D->parent_id, 0); NewLine (); } } static void PrintTypeHeader (void) /* Output a header for a list of types */ { /* Header */ PrintLine (" id description"); PrintSeparator (); } static void PrintType (unsigned Id, const cc65_typedata* T) /* Output one type */ { /* Output the id */ PrintId (Id, 6); while (1) { switch (T->what) { case CC65_TYPE_VOID: Print ("VOID"); goto ExitPoint; case CC65_TYPE_BYTE: Print ("BYTE"); goto ExitPoint; case CC65_TYPE_WORD: Print ("WORD"); goto ExitPoint; case CC65_TYPE_DBYTE: Print ("DBYTE"); goto ExitPoint; case CC65_TYPE_DWORD: Print ("DWORD"); goto ExitPoint; case CC65_TYPE_FARPTR: Print ("FAR "); /* FALLTHROUGH */ case CC65_TYPE_PTR: Print ("POINTER TO "); T = T->data.ptr.ind_type; break; case CC65_TYPE_ARRAY: Print ("ARRAY[%u] OF ", T->data.array.ele_count); T = T->data.array.ele_type; break; default: /* Anything else is currently not implemented */ Print ("***NOT IMPLEMENTED***"); goto ExitPoint; } } ExitPoint: NewLine (); } /*****************************************************************************/ /* Debug file handling */ /*****************************************************************************/ static void UnloadFile (void) /* Unload the debug info file */ { if (Info) { cc65_free_dbginfo (Info); Info = 0; } } static int FileIsLoaded (void) /* Return true if the file is open and has loaded without errors: If not, * print an error message and return false. */ { /* File open? */ if (Info == 0) { PrintLine ("No debug info file"); return 0; } /* Errors on load? */ if (FileErrors > 0) { PrintLine ("File had load errors!"); return 0; } /* Warnings on load? */ if (FileWarnings > 0) { PrintLine ("Beware - file had load warnings!"); } /* Ok */ return 1; } /*****************************************************************************/ /* Command handlers */ /*****************************************************************************/ static void CmdHelp (Collection* Args attribute ((unused))) /* Output a help text */ { PrintHelp (MainCmds, sizeof (MainCmds) / sizeof (MainCmds[0])); } static void CmdLoad (Collection* Args) /* Load a debug info file */ { /* Unload a loaded file */ UnloadFile (); /* Clear the counters */ FileErrors = 0; FileWarnings = 0; /* Open the debug info file */ Info = cc65_read_dbginfo (CollAt (Args, 0), FileError); /* Print a status */ if (FileErrors > 0) { PrintLine ("File loaded with %u errors", FileErrors); } else if (FileWarnings > 0) { PrintLine ("File loaded with %u warnings", FileWarnings); } else { PrintLine ("File loaded successfully"); } } static void CmdQuit (Collection* Args attribute ((unused))) /* Terminate the application */ { UnloadFile (); Terminate = 1; } static void CmdShow (Collection* Args) /* Show items from the debug info file */ { /* Search for the subcommand, check number of args, then execute it */ ExecCmd (Args, ShowCmds, sizeof (ShowCmds) / sizeof (ShowCmds[0])); } static void CmdShowHelp (Collection* Args attribute ((unused))) /* Print help for the show command */ { PrintHelp (ShowCmds, sizeof (ShowCmds) / sizeof (ShowCmds[0])); } static void CmdShowChildScopes (Collection* Args) /* Show child scopes from the debug info file */ { const cc65_scopeinfo* S; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintScopeHeader (); /* Output child scopes for all arguments */ for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = ScopeId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ScopeId: S = cc65_childscopes_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* Invalid id */ S = 0; } /* Output the list */ if (S) { PrintScopes (S); cc65_free_scopeinfo (Info, S); } } } static void CmdShowCSymbol (Collection* Args) /* Show C symbols from the debug info file */ { const cc65_csyminfo* S; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintCSymbolHeader (); /* No arguments means show all libraries */ if (CollCount (Args) == 0) { /* Fetch the list of c symbols */ S = cc65_get_csymlist (Info); /* Output the c symbols */ PrintCSymbols (S); /* Free the list */ cc65_free_csyminfo (Info, S); } else { /* Output c symbols for all arguments */ unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = CSymbolId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case CSymbolId: S = cc65_csym_byid (Info, Id); break; case ScopeId: S = cc65_csym_byscope (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* Invalid id */ S = 0; } /* Output the list */ if (S) { PrintCSymbols (S); cc65_free_csyminfo (Info, S); } } } } static void CmdShowFunction (Collection* Args) /* Show C functions from the debug info file */ { const cc65_csyminfo* S; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintCSymbolHeader (); /* Output c symbols for all arguments */ for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = ModuleId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ModuleId: S = cc65_cfunc_bymodule (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* An invalid id may be a function name */ S = cc65_cfunc_byname (Info, CollConstAt (Args, I)); } /* Output the list */ if (S) { PrintCSymbols (S); cc65_free_csyminfo (Info, S); } } } static void CmdShowLine (Collection* Args) /* Show lines from the debug info file */ { const cc65_lineinfo* L; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintLineHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = LineId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case LineId: L = cc65_line_byid (Info, Id); break; case SourceId: L = cc65_line_bysource (Info, Id); break; case SymbolId: /* ### not very clean */ L = cc65_line_bysymdef (Info, Id); if (L) { PrintLines (L); cc65_free_lineinfo (Info, L); } L = cc65_line_bysymref (Info, Id); break; default: L = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ L = 0; } /* Output the list */ if (L) { PrintLines (L); cc65_free_lineinfo (Info, L); } } } static void CmdShowLibrary (Collection* Args) /* Show libraries from the debug info file */ { const cc65_libraryinfo* L; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintLibraryHeader (); /* No arguments means show all libraries */ if (CollCount (Args) == 0) { /* Fetch the list of libraries */ L = cc65_get_librarylist (Info); /* Output the libraries */ PrintLibraries (L); /* Free the list */ cc65_free_libraryinfo (Info, L); } else { unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = LibraryId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case LibraryId: L = cc65_library_byid (Info, Id); break; default: L = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ L = 0; } /* Output the list */ if (L) { PrintLibraries (L); cc65_free_libraryinfo (Info, L); } } } } static void CmdShowModule (Collection* Args) /* Show modules from the debug info file */ { const cc65_moduleinfo* M; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintModuleHeader (); /* No arguments means show all modules */ if (CollCount (Args) == 0) { /* Fetch the list of modules */ M = cc65_get_modulelist (Info); /* Output the modules */ PrintModules (M); /* Free the list */ cc65_free_moduleinfo (Info, M); } else { unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = ModuleId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ModuleId: M = cc65_module_byid (Info, Id); break; default: M = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ M = 0; } /* Output the list */ if (M) { PrintModules (M); cc65_free_moduleinfo (Info, M); } } } } static void CmdShowScope (Collection* Args) /* Show scopes from the debug info file */ { const cc65_scopeinfo* S; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintScopeHeader (); /* No arguments means show all modules */ if (CollCount (Args) == 0) { /* Fetch the list of segments */ S = cc65_get_scopelist (Info); /* Output the segments */ PrintScopes (S); /* Free the list */ cc65_free_scopeinfo (Info, S); } else { unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = ScopeId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ModuleId: S = cc65_scope_bymodule (Info, Id); break; case ScopeId: S = cc65_scope_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* An invalid id may be a scope name */ S = cc65_scope_byname (Info, CollConstAt (Args, I)); } /* Output the list */ if (S) { PrintScopes (S); cc65_free_scopeinfo (Info, S); } } } } static void CmdShowSegment (Collection* Args) /* Show segments from the debug info file */ { const cc65_segmentinfo* S; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintSegmentHeader (); /* No arguments means show all modules */ if (CollCount (Args) == 0) { /* Fetch the list of segments */ S = cc65_get_segmentlist (Info); /* Output the segments */ PrintSegments (S); /* Free the list */ cc65_free_segmentinfo (Info, S); } else { unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SegmentId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case SegmentId: S = cc65_segment_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* An invalid id may be a segment name */ S = cc65_segment_byname (Info, CollConstAt (Args, I)); } /* Output the list */ if (S) { PrintSegments (S); cc65_free_segmentinfo (Info, S); } } } } static void CmdShowSource (Collection* Args) /* Show source files from the debug info file */ { const cc65_sourceinfo* S; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintSourceHeader (); /* No arguments means show all modules */ if (CollCount (Args) == 0) { /* Fetch the list of source files */ S = cc65_get_sourcelist (Info); /* Output the source files */ PrintSources (S); /* Free the list */ cc65_free_sourceinfo (Info, S); } else { unsigned I; for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SourceId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ModuleId: S = cc65_source_bymodule (Info, Id); break; case SourceId: S = cc65_source_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ S = 0; } /* Output the list */ if (S) { PrintSources (S); cc65_free_sourceinfo (Info, S); } } } } static void CmdShowSpan (Collection* Args) /* Show spans from the debug info file */ { const cc65_spaninfo* S; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintSpanHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SpanId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case LineId: S = cc65_span_byline (Info, Id); break; case ScopeId: S = cc65_span_byscope (Info, Id); break; case SpanId: S = cc65_span_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ S = 0; } /* Output the list */ if (S) { PrintSpans (S); cc65_free_spaninfo (Info, S); } } } static void CmdShowSymbol (Collection* Args) /* Show symbols from the debug info file */ { const cc65_symbolinfo* S; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintSymbolHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SymbolId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case ScopeId: S = cc65_symbol_byscope (Info, Id); break; case SymbolId: S = cc65_symbol_byid (Info, Id); break; default: S = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ S = 0; } /* Output the list */ if (S) { PrintSymbols (S); cc65_free_symbolinfo (Info, S); } } } static void CmdShowSymDef (Collection* Args) /* Show symbol definitions from the debug info file */ { const cc65_lineinfo* L; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintLineHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SymbolId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case SymbolId: L = cc65_line_bysymdef (Info, Id); break; default: L = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ L = 0; } /* Output the list */ if (L) { PrintLines (L); cc65_free_lineinfo (Info, L); } } } static void CmdShowSymRef (Collection* Args) /* Show symbol references from the debug info file */ { const cc65_lineinfo* L; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintLineHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = SymbolId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case SymbolId: L = cc65_line_bysymref (Info, Id); break; default: L = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ L = 0; } /* Output the list */ if (L) { PrintLines (L); cc65_free_lineinfo (Info, L); } } } static void CmdShowType (Collection* Args) /* Show types from the debug info file */ { const cc65_typedata* T; const cc65_spaninfo* S; unsigned I; /* Be sure a file is loaded */ if (!FileIsLoaded ()) { return; } /* Output the header */ PrintTypeHeader (); for (I = 0; I < CollCount (Args); ++I) { /* Parse the argument */ unsigned Id; unsigned IdType = TypeId; if (GetId (CollConstAt (Args, I), &Id, &IdType)) { /* Fetch list depending on type */ switch (IdType) { case SpanId: S = cc65_span_byid (Info, Id); if (S == 0 || S->count == 0) { T = 0; break; } Id = S->data[0].type_id; /* FALLTHROUGH */ case TypeId: T = cc65_type_byid (Info, Id); break; default: T = 0; PrintLine ("Invalid id type"); break; } } else { /* Ignore the invalid id */ T = 0; } /* Output the list */ if (T) { PrintType (Id, T); cc65_free_typedata (Info, T); } } } static void CmdUnload (Collection* Args attribute ((unused))) /* Unload a debug info file */ { UnloadFile (); } /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int Parse (char* CmdLine, Collection* Args) /* Parse the command line and store the arguments in Args. Return true if ok, * false on error. */ { char* End; /* Clear the collection */ CollDeleteAll (Args); /* Parse the command line */ while (1) { /* Break out on end of line */ if (*CmdLine == '\0') { break; } /* Search for start of next command */ if (IsSpace (*CmdLine)) { ++CmdLine; continue; } /* Allow double quotes to terminate a command */ if (*CmdLine == '\"' || *CmdLine == '\'') { char Term = *CmdLine++; End = CmdLine; while (*End != Term) { if (*End == '\0') { PrintLine ("Unterminated argument"); return 0; } ++End; } *End++ = '\0'; } else { End = CmdLine; while (!IsSpace (*End)) { if (*End == '\0') { PrintLine ("Unterminated argument"); return 0; } ++End; } *End++ = '\0'; } CollAppend (Args, CmdLine); CmdLine = End; } /* Ok */ return 1; } int main (int argc, char* argv[]) /* Main program */ { char Input[256]; Collection Args = STATIC_COLLECTION_INITIALIZER; /* Initialize the command line */ InitCmdLine (&argc, &argv, "dbgsh"); /* If we have commands on the command line, execute them */ if (ArgCount > 1) { unsigned I; for (I = 1; I < ArgCount; ++I) { CollAppend (&Args, ArgVec[I]); } /* Search for the command, check number of args, then execute it */ ExecCmd (&Args, MainCmds, sizeof (MainCmds) / sizeof (MainCmds[0])); } /* Loop til program end */ while (!Terminate) { /* Output a prompt, then read the input */ Print ("dbgsh> "); fflush (stdout); if (fgets (Input, sizeof (Input), stdin) == 0) { PrintLine ("(EOF)"); break; } /* Parse the command line */ if (Parse (Input, &Args) == 0 || CollCount (&Args) == 0) { continue; } /* Search for the command, check number of args, then execute it */ ExecCmd (&Args, MainCmds, sizeof (MainCmds) / sizeof (MainCmds[0])); } /* Free arguments */ DoneCollection (&Args); return 0; }
881
./cc65/src/dbginfo/dbginfo.c
/*****************************************************************************/ /* */ /* dbginfo.c */ /* */ /* cc65 debug info handling */ /* */ /* */ /* */ /* (C) 2010-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <assert.h> #include <errno.h> #include "dbginfo.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Use this for debugging - beware, lots of output */ #define DEBUG 0 /* Version numbers of the debug format we understand */ #define VER_MAJOR 2U #define VER_MINOR 0U /* Dynamic strings */ typedef struct StrBuf StrBuf; struct StrBuf { char* Buf; /* Pointer to buffer */ unsigned Len; /* Length of the string */ unsigned Allocated; /* Size of allocated memory */ }; /* Initializer for a string buffer */ #define STRBUF_INITIALIZER { 0, 0, 0 } /* An array of unsigneds/pointers that grows if needed. C guarantees that a * pointer to a union correctly converted points to each of its members. * So what we do here is using union entries that contain an unsigned * (used to store ids until they're resolved) and pointers to actual items * in storage. */ typedef union CollEntry CollEntry; union CollEntry { void* Ptr; unsigned Id; }; typedef struct Collection Collection; struct Collection { unsigned Count; /* Number of items in the list */ unsigned Size; /* Size of allocated array */ CollEntry* Items; /* Array with dynamic size */ }; /* Initializer for static collections */ #define COLLECTION_INITIALIZER { 0, 0, 0 } /* Span info management. The following table has as many entries as there * are addresses active in spans. Each entry lists the spans for this address. */ typedef struct SpanInfoListEntry SpanInfoListEntry; struct SpanInfoListEntry { cc65_addr Addr; /* Unique address */ unsigned Count; /* Number of SpanInfos for this address */ void* Data; /* Either SpanInfo* or SpanInfo** */ }; typedef struct SpanInfoList SpanInfoList; struct SpanInfoList { unsigned Count; /* Number of entries */ SpanInfoListEntry* List; /* Dynamic array with entries */ }; /* Input tokens */ typedef enum { TOK_INVALID, /* Invalid token */ TOK_EOF, /* End of file reached */ TOK_INTCON, /* Integer constant */ TOK_STRCON, /* String constant */ TOK_EQUAL, /* = */ TOK_COMMA, /* , */ TOK_MINUS, /* - */ TOK_PLUS, /* + */ TOK_EOL, /* \n */ TOK_FIRST_KEYWORD, TOK_ABSOLUTE = TOK_FIRST_KEYWORD, /* ABSOLUTE keyword */ TOK_ADDRSIZE, /* ADDRSIZE keyword */ TOK_AUTO, /* AUTO keyword */ TOK_COUNT, /* COUNT keyword */ TOK_CSYM, /* CSYM keyword */ TOK_DEF, /* DEF keyword */ TOK_ENUM, /* ENUM keyword */ TOK_EQUATE, /* EQUATE keyword */ TOK_EXPORT, /* EXPORT keyword */ TOK_EXTERN, /* EXTERN keyword */ TOK_FILE, /* FILE keyword */ TOK_FUNC, /* FUNC keyword */ TOK_GLOBAL, /* GLOBAL keyword */ TOK_ID, /* ID keyword */ TOK_IMPORT, /* IMPORT keyword */ TOK_INFO, /* INFO keyword */ TOK_LABEL, /* LABEL keyword */ TOK_LIBRARY, /* LIBRARY keyword */ TOK_LINE, /* LINE keyword */ TOK_LONG, /* LONG_keyword */ TOK_MAJOR, /* MAJOR keyword */ TOK_MINOR, /* MINOR keyword */ TOK_MODULE, /* MODULE keyword */ TOK_MTIME, /* MTIME keyword */ TOK_NAME, /* NAME keyword */ TOK_OFFS, /* OFFS keyword */ TOK_OUTPUTNAME, /* OUTPUTNAME keyword */ TOK_OUTPUTOFFS, /* OUTPUTOFFS keyword */ TOK_PARENT, /* PARENT keyword */ TOK_REF, /* REF keyword */ TOK_REGISTER, /* REGISTER keyword */ TOK_RO, /* RO keyword */ TOK_RW, /* RW keyword */ TOK_SC, /* SC keyword */ TOK_SCOPE, /* SCOPE keyword */ TOK_SEGMENT, /* SEGMENT keyword */ TOK_SIZE, /* SIZE keyword */ TOK_SPAN, /* SPAN keyword */ TOK_START, /* START keyword */ TOK_STATIC, /* STATIC keyword */ TOK_STRUCT, /* STRUCT keyword */ TOK_SYM, /* SYM keyword */ TOK_TYPE, /* TYPE keyword */ TOK_VALUE, /* VALUE keyword */ TOK_VAR, /* VAR keyword */ TOK_VERSION, /* VERSION keyword */ TOK_ZEROPAGE, /* ZEROPAGE keyword */ TOK_LAST_KEYWORD = TOK_ZEROPAGE, TOK_IDENT, /* To catch unknown keywords */ } Token; /* Data structure containing information from the debug info file. A pointer * to this structure is passed as handle to callers from the outside. */ typedef struct DbgInfo DbgInfo; struct DbgInfo { /* First we have all items in collections sorted by id. The ids are * continous, so an access by id is almost as cheap as an array access. * The collections are also used when the objects are deleted, so they're * actually the ones that "own" the items. */ Collection CSymInfoById; /* C symbol infos sorted by id */ Collection FileInfoById; /* File infos sorted by id */ Collection LibInfoById; /* Library infos sorted by id */ Collection LineInfoById; /* Line infos sorted by id */ Collection ModInfoById; /* Module infos sorted by id */ Collection ScopeInfoById; /* Scope infos sorted by id */ Collection SegInfoById; /* Segment infos sorted by id */ Collection SpanInfoById; /* Span infos sorted by id */ Collection SymInfoById; /* Symbol infos sorted by id */ Collection TypeInfoById; /* Type infos sorted by id */ /* Collections with other sort criteria */ Collection CSymFuncByName; /* C functions sorted by name */ Collection FileInfoByName; /* File infos sorted by name */ Collection ModInfoByName; /* Module info sorted by name */ Collection ScopeInfoByName;/* Scope infos sorted by name */ Collection SegInfoByName; /* Segment infos sorted by name */ Collection SymInfoByName; /* Symbol infos sorted by name */ Collection SymInfoByVal; /* Symbol infos sorted by value */ /* Other stuff */ SpanInfoList SpanInfoByAddr; /* Span infos sorted by unique address */ /* Info data */ unsigned long MemUsage; /* Memory usage for the data */ unsigned MajorVersion; /* Major version number of loaded file */ unsigned MinorVersion; /* Minor version number of loaded file */ char FileName[1]; /* Name of input file */ }; /* Data used when parsing the debug info file */ typedef struct InputData InputData; struct InputData { const char* FileName; /* Name of input file */ cc65_line Line; /* Current line number */ unsigned Col; /* Current column number */ cc65_line SLine; /* Line number at start of token */ unsigned SCol; /* Column number at start of token */ unsigned Errors; /* Number of errors */ FILE* F; /* Input file */ int C; /* Input character */ Token Tok; /* Token from input stream */ unsigned long IVal; /* Integer constant */ StrBuf SVal; /* String constant */ cc65_errorfunc Error; /* Function called in case of errors */ DbgInfo* Info; /* Pointer to debug info */ }; /* Typedefs for the item structures. Do also serve as forwards */ typedef struct CSymInfo CSymInfo; typedef struct FileInfo FileInfo; typedef struct LibInfo LibInfo; typedef struct LineInfo LineInfo; typedef struct ModInfo ModInfo; typedef struct ScopeInfo ScopeInfo; typedef struct SegInfo SegInfo; typedef struct SpanInfo SpanInfo; typedef struct SymInfo SymInfo; typedef struct TypeInfo TypeInfo; /* Internally used c symbol info struct */ struct CSymInfo { unsigned Id; /* Id of file */ unsigned short Kind; /* Kind of C symbol */ unsigned short SC; /* Storage class of C symbol */ int Offs; /* Offset */ union { unsigned Id; /* Id of attached asm symbol */ SymInfo* Info; /* Pointer to attached asm symbol */ } Sym; union { unsigned Id; /* Id of type */ TypeInfo* Info; /* Pointer to type */ } Type; union { unsigned Id; /* Id of scope */ ScopeInfo* Info; /* Pointer to scope */ } Scope; char Name[1]; /* Name of file with full path */ }; /* Internally used file info struct */ struct FileInfo { unsigned Id; /* Id of file */ unsigned long Size; /* Size of file */ unsigned long MTime; /* Modification time */ Collection ModInfoByName; /* Modules in which this file is used */ Collection LineInfoByLine; /* Line infos sorted by line */ char Name[1]; /* Name of file with full path */ }; /* Internally used library info struct */ struct LibInfo { unsigned Id; /* Id of library */ char Name[1]; /* Name of library with path */ }; /* Internally used line info struct */ struct LineInfo { unsigned Id; /* Id of line info */ cc65_line Line; /* Line number */ union { unsigned Id; /* Id of file */ FileInfo* Info; /* Pointer to file info */ } File; cc65_line_type Type; /* Type of line */ unsigned Count; /* Nesting counter for macros */ Collection SpanInfoList; /* List of spans for this line */ }; /* Internally used module info struct */ struct ModInfo { unsigned Id; /* Id of library */ union { unsigned Id; /* Id of main source file */ FileInfo* Info; /* Pointer to file info */ } File; union { unsigned Id; /* Id of library if any */ LibInfo* Info; /* Pointer to library info */ } Lib; ScopeInfo* MainScope; /* Pointer to main scope */ Collection CSymFuncByName; /* C functions by name */ Collection FileInfoByName; /* Files for this module */ Collection ScopeInfoByName;/* Scopes for this module */ char Name[1]; /* Name of module with path */ }; /* Internally used scope info struct */ struct ScopeInfo { unsigned Id; /* Id of scope */ cc65_scope_type Type; /* Type of scope */ cc65_size Size; /* Size of scope */ union { unsigned Id; /* Id of module */ ModInfo* Info; /* Pointer to module info */ } Mod; union { unsigned Id; /* Id of parent scope */ ScopeInfo* Info; /* Pointer to parent scope */ } Parent; union { unsigned Id; /* Id of label symbol */ SymInfo* Info; /* Pointer to label symbol */ } Label; CSymInfo* CSymFunc; /* C function for this scope */ Collection SpanInfoList; /* List of spans for this scope */ Collection SymInfoByName; /* Symbols in this scope */ Collection* CSymInfoByName; /* C symbols for this scope */ Collection* ChildScopeList; /* Child scopes of this scope */ char Name[1]; /* Name of scope */ }; /* Internally used segment info struct */ struct SegInfo { unsigned Id; /* Id of segment */ cc65_addr Start; /* Start address of segment */ cc65_size Size; /* Size of segment */ char* OutputName; /* Name of output file */ unsigned long OutputOffs; /* Offset in output file */ char Name[1]; /* Name of segment */ }; /* Internally used span info struct */ struct SpanInfo { unsigned Id; /* Id of span */ cc65_addr Start; /* Start of span */ cc65_addr End; /* End of span */ union { unsigned Id; /* Id of segment */ SegInfo* Info; /* Pointer to segment */ } Seg; union { unsigned Id; /* Id of type */ TypeInfo* Info; /* Pointer to type */ } Type; Collection* ScopeInfoList; /* Scopes for this span */ Collection* LineInfoList; /* Lines for this span */ }; /* Internally used symbol info struct */ struct SymInfo { unsigned Id; /* Id of symbol */ cc65_symbol_type Type; /* Type of symbol */ long Value; /* Value of symbol */ cc65_size Size; /* Size of symbol */ union { unsigned Id; /* Id of export if any */ SymInfo* Info; /* Pointer to export if any */ } Exp; union { unsigned Id; /* Id of segment if any */ SegInfo* Info; /* Pointer to segment if any */ } Seg; union { unsigned Id; /* Id of symbol scope */ ScopeInfo* Info; /* Pointer to symbol scope */ } Scope; union { unsigned Id; /* Parent symbol if any */ SymInfo* Info; /* Pointer to parent symbol if any */ } Parent; CSymInfo* CSym; /* Corresponding C symbol */ Collection* ImportList; /* List of imports if this is an export */ Collection* CheapLocals; /* List of cheap local symbols */ Collection DefLineInfoList;/* Line info of symbol definition */ Collection RefLineInfoList;/* Line info of symbol references */ char Name[1]; /* Name of symbol */ }; /* Internally used type info struct */ struct TypeInfo { unsigned Id; /* Id of type */ cc65_typedata Data[1]; /* Data, dynamically allocated */ }; /* A structure used when parsing a type string into a set of cc65_typedata * structures. */ typedef struct TypeParseData TypeParseData; struct TypeParseData { TypeInfo* Info; unsigned ItemCount; unsigned ItemIndex; cc65_typedata* ItemData; const StrBuf* Type; unsigned Pos; unsigned Error; }; /*****************************************************************************/ /* Forwards */ /*****************************************************************************/ static void NextToken (InputData* D); /* Read the next token from the input stream */ /*****************************************************************************/ /* Memory allocation */ /*****************************************************************************/ static void* xmalloc (size_t Size) /* Allocate memory, check for out of memory condition. Do some debugging */ { void* P = 0; /* Allow zero sized requests and return NULL in this case */ if (Size) { /* Allocate memory */ P = malloc (Size); /* Check for errors */ assert (P != 0); } /* Return a pointer to the block */ return P; } static void* xrealloc (void* P, size_t Size) /* Reallocate a memory block, check for out of memory */ { /* Reallocate the block */ void* N = realloc (P, Size); /* Check for errors */ assert (N != 0 || Size == 0); /* Return the pointer to the new block */ return N; } static void xfree (void* Block) /* Free the block, do some debugging */ { free (Block); } /*****************************************************************************/ /* Dynamic strings */ /*****************************************************************************/ static void SB_Done (StrBuf* B) /* Free the data of a string buffer (but not the struct itself) */ { if (B->Allocated) { xfree (B->Buf); } } static void SB_Realloc (StrBuf* B, unsigned NewSize) /* Reallocate the string buffer space, make sure at least NewSize bytes are * available. */ { /* Get the current size, use a minimum of 8 bytes */ unsigned NewAllocated = B->Allocated; if (NewAllocated == 0) { NewAllocated = 8; } /* Round up to the next power of two */ while (NewAllocated < NewSize) { NewAllocated *= 2; } /* Reallocate the buffer. Beware: The allocated size may be zero while the * length is not. This means that we have a buffer that wasn't allocated * on the heap. */ if (B->Allocated) { /* Just reallocate the block */ B->Buf = xrealloc (B->Buf, NewAllocated); } else { /* Allocate a new block and copy */ B->Buf = memcpy (xmalloc (NewAllocated), B->Buf, B->Len); } /* Remember the new block size */ B->Allocated = NewAllocated; } static void SB_CheapRealloc (StrBuf* B, unsigned NewSize) /* Reallocate the string buffer space, make sure at least NewSize bytes are * available. This function won't copy the old buffer contents over to the new * buffer and may be used if the old contents are overwritten later. */ { /* Get the current size, use a minimum of 8 bytes */ unsigned NewAllocated = B->Allocated; if (NewAllocated == 0) { NewAllocated = 8; } /* Round up to the next power of two */ while (NewAllocated < NewSize) { NewAllocated *= 2; } /* Free the old buffer if there is one */ if (B->Allocated) { xfree (B->Buf); } /* Allocate a fresh block */ B->Buf = xmalloc (NewAllocated); /* Remember the new block size */ B->Allocated = NewAllocated; } static unsigned SB_GetLen (const StrBuf* B) /* Return the length of the buffer contents */ { return B->Len; } static char* SB_GetBuf (StrBuf* B) /* Return a buffer pointer */ { return B->Buf; } static const char* SB_GetConstBuf (const StrBuf* B) /* Return a buffer pointer */ { return B->Buf; } static char SB_At (const StrBuf* B, unsigned Pos) /* Return the character from a specific position */ { assert (Pos <= B->Len); return B->Buf[Pos]; } static void SB_Terminate (StrBuf* B) /* Zero terminate the given string buffer. NOTE: The terminating zero is not * accounted for in B->Len, if you want that, you have to use AppendChar! */ { unsigned NewLen = B->Len + 1; if (NewLen > B->Allocated) { SB_Realloc (B, NewLen); } B->Buf[B->Len] = '\0'; } static void SB_Clear (StrBuf* B) /* Clear the string buffer (make it empty) */ { B->Len = 0; } static void SB_CopyBuf (StrBuf* Target, const char* Buf, unsigned Size) /* Copy Buf to Target, discarding the old contents of Target */ { if (Size) { if (Target->Allocated < Size) { SB_CheapRealloc (Target, Size); } memcpy (Target->Buf, Buf, Size); } Target->Len = Size; } static void SB_Copy (StrBuf* Target, const StrBuf* Source) /* Copy Source to Target, discarding the old contents of Target */ { SB_CopyBuf (Target, Source->Buf, Source->Len); } static void SB_AppendChar (StrBuf* B, int C) /* Append a character to a string buffer */ { unsigned NewLen = B->Len + 1; if (NewLen > B->Allocated) { SB_Realloc (B, NewLen); } B->Buf[B->Len] = (char) C; B->Len = NewLen; } static char* SB_StrDup (const StrBuf* B) /* Return the contents of B as a dynamically allocated string. The string * will always be NUL terminated. */ { /* Allocate memory */ char* S = xmalloc (B->Len + 1); /* Copy the string */ memcpy (S, B->Buf, B->Len); /* Terminate it */ S[B->Len] = '\0'; /* And return the result */ return S; } /*****************************************************************************/ /* Collections */ /*****************************************************************************/ static Collection* CollInit (Collection* C) /* Initialize a collection and return it. */ { /* Intialize the fields. */ C->Count = 0; C->Size = 0; C->Items = 0; /* Return the new struct */ return C; } static Collection* CollNew (void) /* Allocate a new collection, initialize and return it */ { return CollInit (xmalloc (sizeof (Collection))); } static void CollDone (Collection* C) /* Free the data for a collection. This will not free the data contained in * the collection. */ { /* Free the pointer array */ xfree (C->Items); /* Clear the fields, so the collection may be reused (or CollDone called) * again */ C->Count = 0; C->Size = 0; C->Items = 0; } static void CollFree (Collection* C) /* Free a dynamically allocated collection */ { /* Accept NULL pointers */ if (C) { xfree (C->Items); xfree (C); } } static unsigned CollCount (const Collection* C) /* Return the number of items in the collection. Return 0 if C is NULL. */ { return C? C->Count : 0; } static void CollMove (Collection* Source, Collection* Target) /* Move all data from one collection to another. This function will first free * the data in the target collection, and - after the move - clear the data * from the source collection. */ { /* Free the target collection data */ xfree (Target->Items); /* Now copy the whole bunch over */ *Target = *Source; /* Empty Source */ Source->Count = 0; Source->Size = 0; Source->Items = 0; } static void CollGrow (Collection* C, unsigned Size) /* Grow the collection C so it is able to hold Size items without a resize * being necessary. This can be called for performance reasons if the number * of items to be placed in the collection is known in advance. */ { CollEntry* NewItems; /* Ignore the call if the collection is already large enough */ if (Size <= C->Size) { return; } /* Grow the collection */ C->Size = Size; NewItems = xmalloc (C->Size * sizeof (CollEntry)); memcpy (NewItems, C->Items, C->Count * sizeof (CollEntry)); xfree (C->Items); C->Items = NewItems; } static void CollPrepareInsert (Collection* C, unsigned Index) /* Prepare for insertion of the data at a given position in the collection */ { /* Check for invalid indices */ assert (Index <= C->Count); /* Grow the array if necessary */ if (C->Count >= C->Size) { /* Must grow */ CollGrow (C, (C->Size == 0)? 1 : C->Size * 2); } /* Move the existing elements if needed */ if (C->Count != Index) { memmove (C->Items+Index+1, C->Items+Index, (C->Count-Index) * sizeof (void*)); } ++C->Count; } static void CollInsert (Collection* C, void* Item, unsigned Index) /* Insert the data at the given position in the collection */ { /* Prepare for insertion (free the given slot) */ CollPrepareInsert (C, Index); /* Store the new item */ C->Items[Index].Ptr = Item; } static void CollInsertId (Collection* C, unsigned Id, unsigned Index) /* Insert the data at the given position in the collection */ { /* Prepare for insertion (free the given slot) */ CollPrepareInsert (C, Index); /* Store the new item */ C->Items[Index].Id = Id; } static void CollReplace (Collection* C, void* Item, unsigned Index) /* Replace the item at the given position by a new one */ { /* Check the index */ assert (Index < C->Count); /* Replace the element */ C->Items[Index].Ptr = Item; } static void CollReplaceExpand (Collection* C, void* Item, unsigned Index) /* If Index is a valid index for the collection, replace the item at this * position by the one passed. If the collection is too small, expand it, * filling unused pointers with NULL, then add the new item at the given * position. */ { if (Index < C->Count) { /* Collection is already large enough */ C->Items[Index].Ptr = Item; } else { /* Must expand the collection */ unsigned Size = C->Size; if (Size == 0) { Size = 2; } while (Index >= Size) { Size *= 2; } CollGrow (C, Size); /* Fill up unused slots with NULL */ while (C->Count < Index) { C->Items[C->Count++].Ptr = 0; } /* Fill in the item */ C->Items[C->Count++].Ptr = Item; } } static void CollAppend (Collection* C, void* Item) /* Append an item to the end of the collection */ { /* Insert the item at the end of the current list */ CollInsert (C, Item, C->Count); } static void CollAppendId (Collection* C, unsigned Id) /* Append an id to the end of the collection */ { /* Insert the id at the end of the current list */ CollInsertId (C, Id, C->Count); } static void* CollAt (const Collection* C, unsigned Index) /* Return the item at the given index */ { /* Check the index */ assert (Index < C->Count); /* Return the element */ return C->Items[Index].Ptr; } static unsigned CollIdAt (const Collection* C, unsigned Index) /* Return the id at the given index */ { /* Check the index */ assert (Index < C->Count); /* Return the element */ return C->Items[Index].Id; } static void CollQuickSort (Collection* C, int Lo, int Hi, int (*Compare) (const void*, const void*)) /* Internal recursive sort function. */ { /* Get a pointer to the items */ CollEntry* Items = C->Items; /* Quicksort */ while (Hi > Lo) { int I = Lo + 1; int J = Hi; while (I <= J) { while (I <= J && Compare (Items[Lo].Ptr, Items[I].Ptr) >= 0) { ++I; } while (I <= J && Compare (Items[Lo].Ptr, Items[J].Ptr) < 0) { --J; } if (I <= J) { /* Swap I and J */ CollEntry Tmp = Items[I]; Items[I] = Items[J]; Items[J] = Tmp; ++I; --J; } } if (J != Lo) { /* Swap J and Lo */ CollEntry Tmp = Items[J]; Items[J] = Items[Lo]; Items[Lo] = Tmp; } if (J > (Hi + Lo) / 2) { CollQuickSort (C, J + 1, Hi, Compare); Hi = J - 1; } else { CollQuickSort (C, Lo, J - 1, Compare); Lo = J + 1; } } } static void CollSort (Collection* C, int (*Compare) (const void*, const void*)) /* Sort the collection using the given compare function. */ { if (C->Count > 1) { CollQuickSort (C, 0, C->Count-1, Compare); } } /*****************************************************************************/ /* Debugging stuff */ /*****************************************************************************/ #if DEBUG /* Output */ #define DBGPRINT(format, ...) printf ((format), __VA_ARGS__) static void DumpFileInfo (Collection* FileInfos) /* Dump a list of file infos */ { unsigned I; /* File info */ for (I = 0; I < CollCount (FileInfos); ++I) { const FileInfo* FI = CollAt (FileInfos, I); printf ("File info %u:\n" " Name: %s\n" " Size: %lu\n" " MTime: %lu\n", FI->Id, FI->Name, (unsigned long) FI->Size, (unsigned long) FI->MTime); } } static void DumpOneLineInfo (unsigned Num, LineInfo* LI) /* Dump one line info entry */ { printf (" Index: %u\n" " File: %s\n" " Line: %lu\n" " Range: 0x%06lX-0x%06lX\n" " Type: %u\n" " Count: %u\n", Num, LI->File.Info->Name, (unsigned long) LI->Line, (unsigned long) LI->Start, (unsigned long) LI->End, LI->Type, LI->Count); } static void DumpSpanInfo (SpanInfoList* L) /* Dump a list of span infos */ { unsigned I, J; /* Line info */ for (I = 0; I < L->Count; ++I) { const SpanInfoListEntry* E = &L->List[I]; printf ("Addr: %lu\n", (unsigned long) E->Addr); if (E->Count == 1) { DumpOneLineInfo (0, E->Data); } else { for (J = 0; J < E->Count; ++J) { DumpOneLineInfo (J, ((LineInfo**) E->Data)[J]); } } } } static void DumpData (InputData* D) /* Dump internal data to stdout for debugging */ { /* Dump data */ DumpFileInfo (&D->Info->FileInfoById); DumpLineInfo (&D->Info->LineInfoByAddr); } #else /* No output */ #ifdef __WATCOMC__ static void DBGPRINT(const char* format, ...) {} #else #define DBGPRINT(format, ...) #endif #endif /*****************************************************************************/ /* Helper functions */ /*****************************************************************************/ static unsigned GetId (const void* Data) /* Return the id of one of the info structures. All structures have the Id * field as first member, and the C standard allows converting a union pointer * to the data type of the first member, so this is safe and portable. */ { if (Data) { return *(const unsigned*)Data; } else { return CC65_INV_ID; } } static unsigned HexValue (char C) /* Convert the ascii representation of a hex nibble into the hex nibble */ { if (isdigit (C)) { return C - '0'; } else if (islower (C)) { return C - 'a' + 10; } else { return C - 'A' + 10; } } static void ParseError (InputData* D, cc65_error_severity Type, const char* Msg, ...) /* Call the user supplied parse error function */ { va_list ap; int MsgSize; cc65_parseerror* E; /* Test-format the error message so we know how much space to allocate */ va_start (ap, Msg); MsgSize = vsnprintf (0, 0, Msg, ap); va_end (ap); /* Allocate memory */ E = xmalloc (sizeof (*E) + MsgSize); /* Write data to E */ E->type = Type; E->name = D->FileName; E->line = D->SLine; E->column = D->SCol; va_start (ap, Msg); vsnprintf (E->errormsg, MsgSize+1, Msg, ap); va_end (ap); /* Call the caller:-) */ D->Error (E); /* Free the data structure */ xfree (E); /* Count errors */ if (Type == CC65_ERROR) { ++D->Errors; } } static void SkipLine (InputData* D) /* Error recovery routine. Skip tokens until EOL or EOF is reached */ { while (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { NextToken (D); } } static void UnexpectedToken (InputData* D) /* Call ParseError with a message about an unexpected input token */ { ParseError (D, CC65_ERROR, "Unexpected input token %d", D->Tok); SkipLine (D); } static void UnknownKeyword (InputData* D) /* Print a warning about an unknown keyword in the file. Try to do smart * recovery, so if later versions of the debug information add additional * keywords, this code may be able to at least ignore them. */ { /* Output a warning */ ParseError (D, CC65_WARNING, "Unknown keyword \"%s\" - skipping", SB_GetConstBuf (&D->SVal)); /* Skip the identifier */ NextToken (D); /* If an equal sign follows, ignore anything up to the next line end * or comma. If a comma or line end follows, we're already done. If * we have none of both, we ignore the remainder of the line. */ if (D->Tok == TOK_EQUAL) { NextToken (D); while (D->Tok != TOK_COMMA && D->Tok != TOK_EOL && D->Tok != TOK_EOF) { NextToken (D); } } else if (D->Tok != TOK_COMMA && D->Tok != TOK_EOL && D->Tok != TOK_EOF) { SkipLine (D); } } /*****************************************************************************/ /* C symbol info */ /*****************************************************************************/ static CSymInfo* NewCSymInfo (const StrBuf* Name) /* Create a new CSymInfo struct and return it */ { /* Allocate memory */ CSymInfo* S = xmalloc (sizeof (CSymInfo) + SB_GetLen (Name)); /* Initialize it */ memcpy (S->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return S; } static void FreeCSymInfo (CSymInfo* S) /* Free a CSymInfo struct */ { /* Free the structure itself */ xfree (S); } static cc65_csyminfo* new_cc65_csyminfo (unsigned Count) /* Allocate and return a cc65_csyminfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_csyminfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopyCSymInfo (cc65_csymdata* D, const CSymInfo* S) /* Copy data from a CSymInfo struct to a cc65_csymdata struct */ { D->csym_id = S->Id; D->csym_kind = S->Kind; D->csym_sc = S->SC; D->csym_offs = S->Offs; D->type_id = GetId (S->Type.Info); D->symbol_id = GetId (S->Sym.Info); D->scope_id = GetId (S->Scope.Info); D->csym_name = S->Name; } static int CompareCSymInfoByName (const void* L, const void* R) /* Helper function to sort c symbol infos in a collection by name */ { /* Sort by symbol name, then by id */ int Res = strcmp (((const CSymInfo*) L)->Name, ((const CSymInfo*) R)->Name); if (Res == 0) { Res = (int)((const CSymInfo*) L)->Id - (int)((const CSymInfo*) R)->Id; } return Res; } /*****************************************************************************/ /* File info */ /*****************************************************************************/ static FileInfo* NewFileInfo (const StrBuf* Name) /* Create a new FileInfo struct and return it */ { /* Allocate memory */ FileInfo* F = xmalloc (sizeof (FileInfo) + SB_GetLen (Name)); /* Initialize it */ CollInit (&F->ModInfoByName); CollInit (&F->LineInfoByLine); memcpy (F->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return F; } static void FreeFileInfo (FileInfo* F) /* Free a FileInfo struct */ { /* Delete the collections */ CollDone (&F->ModInfoByName); CollDone (&F->LineInfoByLine); /* Free the file info structure itself */ xfree (F); } static cc65_sourceinfo* new_cc65_sourceinfo (unsigned Count) /* Allocate and return a cc65_sourceinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_sourceinfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopyFileInfo (cc65_sourcedata* D, const FileInfo* F) /* Copy data from a FileInfo struct to a cc65_sourcedata struct */ { D->source_id = F->Id; D->source_name = F->Name; D->source_size = F->Size; D->source_mtime = F->MTime; } static int CompareFileInfoByName (const void* L, const void* R) /* Helper function to sort file infos in a collection by name */ { /* Sort by file name. If names are equal, sort by timestamp, * then sort by size. Which means, identical files will go * together. */ int Res = strcmp (((const FileInfo*) L)->Name, ((const FileInfo*) R)->Name); if (Res != 0) { return Res; } if (((const FileInfo*) L)->MTime > ((const FileInfo*) R)->MTime) { return 1; } else if (((const FileInfo*) L)->MTime < ((const FileInfo*) R)->MTime) { return -1; } if (((const FileInfo*) L)->Size > ((const FileInfo*) R)->Size) { return 1; } else if (((const FileInfo*) L)->Size < ((const FileInfo*) R)->Size) { return -1; } else { return 0; } } /*****************************************************************************/ /* Library info */ /*****************************************************************************/ static LibInfo* NewLibInfo (const StrBuf* Name) /* Create a new LibInfo struct, intialize and return it */ { /* Allocate memory */ LibInfo* L = xmalloc (sizeof (LibInfo) + SB_GetLen (Name)); /* Initialize the name */ memcpy (L->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return L; } static void FreeLibInfo (LibInfo* L) /* Free a LibInfo struct */ { xfree (L); } static cc65_libraryinfo* new_cc65_libraryinfo (unsigned Count) /* Allocate and return a cc65_libraryinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_libraryinfo* L = xmalloc (sizeof (*L) - sizeof (L->data[0]) + Count * sizeof (L->data[0])); L->count = Count; return L; } static void CopyLibInfo (cc65_librarydata* D, const LibInfo* L) /* Copy data from a LibInfo struct to a cc65_librarydata struct */ { D->library_id = L->Id; D->library_name = L->Name; } /*****************************************************************************/ /* Line info */ /*****************************************************************************/ static LineInfo* NewLineInfo (void) /* Create a new LineInfo struct and return it */ { /* Allocate memory */ LineInfo* L = xmalloc (sizeof (LineInfo)); /* Initialize and return it */ CollInit (&L->SpanInfoList); return L; } static void FreeLineInfo (LineInfo* L) /* Free a LineInfo struct */ { CollDone (&L->SpanInfoList); xfree (L); } static cc65_lineinfo* new_cc65_lineinfo (unsigned Count) /* Allocate and return a cc65_lineinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_lineinfo* L = xmalloc (sizeof (*L) - sizeof (L->data[0]) + Count * sizeof (L->data[0])); L->count = Count; return L; } static void CopyLineInfo (cc65_linedata* D, const LineInfo* L) /* Copy data from a LineInfo struct to a cc65_linedata struct */ { D->line_id = L->Id; D->source_id = L->File.Info->Id; D->source_line = L->Line; D->line_type = L->Type; D->count = L->Count; } static int CompareLineInfoByLine (const void* L, const void* R) /* Helper function to sort line infos in a collection by line. */ { int Left = ((const LineInfo*) L)->Line; int Right = ((const LineInfo*) R)->Line; return Left - Right; } /*****************************************************************************/ /* Module info */ /*****************************************************************************/ static ModInfo* NewModInfo (const StrBuf* Name) /* Create a new ModInfo struct, intialize and return it */ { /* Allocate memory */ ModInfo* M = xmalloc (sizeof (ModInfo) + SB_GetLen (Name)); /* Initialize it */ M->MainScope = 0; CollInit (&M->CSymFuncByName); CollInit (&M->FileInfoByName); CollInit (&M->ScopeInfoByName); memcpy (M->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return M; } static void FreeModInfo (ModInfo* M) /* Free a ModInfo struct */ { /* Free the collections */ CollDone (&M->CSymFuncByName); CollDone (&M->FileInfoByName); CollDone (&M->ScopeInfoByName); /* Free the structure itself */ xfree (M); } static cc65_moduleinfo* new_cc65_moduleinfo (unsigned Count) /* Allocate and return a cc65_moduleinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_moduleinfo* M = xmalloc (sizeof (*M) - sizeof (M->data[0]) + Count * sizeof (M->data[0])); M->count = Count; return M; } static void CopyModInfo (cc65_moduledata* D, const ModInfo* M) /* Copy data from a ModInfo struct to a cc65_moduledata struct */ { D->module_id = M->Id; D->module_name = M->Name; D->source_id = M->File.Info->Id; D->library_id = GetId (M->Lib.Info); D->scope_id = GetId (M->MainScope); } static int CompareModInfoByName (const void* L, const void* R) /* Helper function to sort module infos in a collection by name */ { /* Compare module name */ return strcmp (((const ModInfo*) L)->Name, ((const ModInfo*) R)->Name); } /*****************************************************************************/ /* Scope info */ /*****************************************************************************/ static ScopeInfo* NewScopeInfo (const StrBuf* Name) /* Create a new ScopeInfo struct, intialize and return it */ { /* Allocate memory */ ScopeInfo* S = xmalloc (sizeof (ScopeInfo) + SB_GetLen (Name)); /* Initialize the fields as necessary */ S->CSymFunc = 0; CollInit (&S->SpanInfoList); CollInit (&S->SymInfoByName); S->CSymInfoByName = 0; S->ChildScopeList = 0; memcpy (S->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return S; } static void FreeScopeInfo (ScopeInfo* S) /* Free a ScopeInfo struct */ { CollDone (&S->SpanInfoList); CollDone (&S->SymInfoByName); CollFree (S->CSymInfoByName); CollFree (S->ChildScopeList); xfree (S); } static cc65_scopeinfo* new_cc65_scopeinfo (unsigned Count) /* Allocate and return a cc65_scopeinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_scopeinfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopyScopeInfo (cc65_scopedata* D, const ScopeInfo* S) /* Copy data from a ScopeInfo struct to a cc65_scopedata struct */ { D->scope_id = S->Id; D->scope_name = S->Name; D->scope_type = S->Type; D->scope_size = S->Size; D->parent_id = GetId (S->Parent.Info); D->symbol_id = GetId (S->Label.Info); D->module_id = S->Mod.Info->Id; } static int CompareScopeInfoByName (const void* L, const void* R) /* Helper function to sort scope infos in a collection by name */ { const ScopeInfo* Left = L; const ScopeInfo* Right = R; /* Compare scope name, then id */ int Res = strcmp (Left->Name, Right->Name); if (Res == 0) { Res = (int)Left->Id - (int)Right->Id; } return Res; } /*****************************************************************************/ /* Segment info */ /*****************************************************************************/ static SegInfo* NewSegInfo (const StrBuf* Name, unsigned Id, cc65_addr Start, cc65_addr Size, const StrBuf* OutputName, unsigned long OutputOffs) /* Create a new SegInfo struct and return it */ { /* Allocate memory */ SegInfo* S = xmalloc (sizeof (SegInfo) + SB_GetLen (Name)); /* Initialize it */ S->Id = Id; S->Start = Start; S->Size = Size; if (SB_GetLen (OutputName) > 0) { /* Output file given */ S->OutputName = SB_StrDup (OutputName); S->OutputOffs = OutputOffs; } else { /* No output file given */ S->OutputName = 0; S->OutputOffs = 0; } memcpy (S->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return S; } static void FreeSegInfo (SegInfo* S) /* Free a SegInfo struct */ { xfree (S->OutputName); xfree (S); } static cc65_segmentinfo* new_cc65_segmentinfo (unsigned Count) /* Allocate and return a cc65_segmentinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_segmentinfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopySegInfo (cc65_segmentdata* D, const SegInfo* S) /* Copy data from a SegInfo struct to a cc65_segmentdata struct */ { D->segment_id = S->Id; D->segment_name = S->Name; D->segment_start = S->Start; D->segment_size = S->Size; D->output_name = S->OutputName; D->output_offs = S->OutputOffs; } static int CompareSegInfoByName (const void* L, const void* R) /* Helper function to sort segment infos in a collection by name */ { /* Sort by file name */ return strcmp (((const SegInfo*) L)->Name, ((const SegInfo*) R)->Name); } /*****************************************************************************/ /* Span info */ /*****************************************************************************/ static SpanInfo* NewSpanInfo (void) /* Create a new SpanInfo struct, intialize and return it */ { /* Allocate memory */ SpanInfo* S = xmalloc (sizeof (SpanInfo)); /* Initialize and return it */ S->ScopeInfoList = 0; S->LineInfoList = 0; return S; } static void FreeSpanInfo (SpanInfo* S) /* Free a SpanInfo struct */ { CollFree (S->ScopeInfoList); CollFree (S->LineInfoList); xfree (S); } static cc65_spaninfo* new_cc65_spaninfo (unsigned Count) /* Allocate and return a cc65_spaninfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_spaninfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopySpanInfo (cc65_spandata* D, const SpanInfo* S) /* Copy data from a SpanInfo struct to a cc65_spandata struct */ { D->span_id = S->Id; D->span_start = S->Start; D->span_end = S->End; D->segment_id = S->Seg.Info->Id; D->type_id = GetId (S->Type.Info); D->scope_count = CollCount (S->ScopeInfoList); D->line_count = CollCount (S->LineInfoList); } static int CompareSpanInfoByAddr (const void* L, const void* R) /* Helper function to sort span infos in a collection by address. Span infos * with smaller start address are considered smaller. If start addresses are * equal, line spans with smaller end address are considered smaller. This * means, that when CompareSpanInfoByAddr is used for sorting, a range with * identical start addresses will have smaller spans first, followed by * larger spans. */ { /* Sort by start of span */ if (((const SpanInfo*) L)->Start > ((const SpanInfo*) R)->Start) { return 1; } else if (((const SpanInfo*) L)->Start < ((const SpanInfo*) R)->Start) { return -1; } else if (((const SpanInfo*) L)->End > ((const SpanInfo*) R)->End) { return 1; } else if (((const SpanInfo*) L)->End < ((const SpanInfo*) R)->End) { return -1; } else { return 0; } } /*****************************************************************************/ /* Symbol info */ /*****************************************************************************/ static SymInfo* NewSymInfo (const StrBuf* Name) /* Create a new SymInfo struct, intialize and return it */ { /* Allocate memory */ SymInfo* S = xmalloc (sizeof (SymInfo) + SB_GetLen (Name)); /* Initialize it as necessary */ S->CSym = 0; S->ImportList = 0; S->CheapLocals = 0; CollInit (&S->DefLineInfoList); CollInit (&S->RefLineInfoList); memcpy (S->Name, SB_GetConstBuf (Name), SB_GetLen (Name) + 1); /* Return it */ return S; } static void FreeSymInfo (SymInfo* S) /* Free a SymInfo struct */ { CollFree (S->ImportList); CollFree (S->CheapLocals); CollDone (&S->DefLineInfoList); CollDone (&S->RefLineInfoList); xfree (S); } static cc65_symbolinfo* new_cc65_symbolinfo (unsigned Count) /* Allocate and return a cc65_symbolinfo struct that is able to hold Count * entries. Initialize the count field of the returned struct. */ { cc65_symbolinfo* S = xmalloc (sizeof (*S) - sizeof (S->data[0]) + Count * sizeof (S->data[0])); S->count = Count; return S; } static void CopySymInfo (cc65_symboldata* D, const SymInfo* S) /* Copy data from a SymInfo struct to a cc65_symboldata struct */ { SegInfo* Seg; D->symbol_id = S->Id; D->symbol_name = S->Name; D->symbol_type = S->Type; D->symbol_size = S->Size; /* If this is an import, it doesn't have a value or segment. Use the data * from the matching export instead. */ if (S->Exp.Info) { /* This is an import, because it has a matching export */ D->export_id = S->Exp.Info->Id; D->symbol_value = S->Exp.Info->Value; Seg = S->Exp.Info->Seg.Info; } else { D->export_id = CC65_INV_ID; D->symbol_value = S->Value; Seg = S->Seg.Info; } if (Seg) { D->segment_id = Seg->Id; } else { D->segment_id = CC65_INV_ID; } D->scope_id = S->Scope.Info->Id; if (S->Parent.Info) { D->parent_id = S->Parent.Info->Id; } else { D->parent_id = CC65_INV_ID; } } static int CompareSymInfoByName (const void* L, const void* R) /* Helper function to sort symbol infos in a collection by name */ { /* Sort by symbol name */ return strcmp (((const SymInfo*) L)->Name, ((const SymInfo*) R)->Name); } static int CompareSymInfoByVal (const void* L, const void* R) /* Helper function to sort symbol infos in a collection by value */ { /* Sort by symbol value. If both are equal, sort by symbol name so it * looks nice when such a list is returned. */ if (((const SymInfo*) L)->Value > ((const SymInfo*) R)->Value) { return 1; } else if (((const SymInfo*) L)->Value < ((const SymInfo*) R)->Value) { return -1; } else { return CompareSymInfoByName (L, R); } } /*****************************************************************************/ /* Type info */ /*****************************************************************************/ /* The following definitions are actually just taken from gentype.h */ /* Size of a data type */ #define GT_SIZE_1 0x00U #define GT_SIZE_2 0x01U #define GT_SIZE_3 0x02U #define GT_SIZE_4 0x03U #define GT_SIZE_MASK 0x07U #define GT_GET_SIZE(x) (((x) & GT_SIZE_MASK) + 1U) /* Sign of the data type */ #define GT_UNSIGNED 0x00U #define GT_SIGNED 0x08U #define GT_SIGN_MASK 0x08U #define GT_HAS_SIGN(x) (((x) & GT_SIZE_MASK) == GT_SIGNED) /* Byte order */ #define GT_LITTLE_ENDIAN 0x00U #define GT_BIG_ENDIAN 0x10U #define GT_BYTEORDER_MASK 0x10U #define GT_IS_LITTLE_ENDIAN(x) (((x) & GT_BYTEORDER_MASK) == GT_LITTLE_ENDIAN) #define GT_IS_BIG_ENDIAN(x) (((x) & GT_BYTEORDER_MASK) == GT_BIG_ENDIAN) /* Type of the data. */ #define GT_TYPE_VOID 0x00U #define GT_TYPE_INT 0x20U #define GT_TYPE_PTR 0x40U #define GT_TYPE_FLOAT 0x60U #define GT_TYPE_ARRAY 0x80U #define GT_TYPE_FUNC 0xA0U #define GT_TYPE_STRUCT 0xC0U #define GT_TYPE_UNION 0xE0U #define GT_TYPE_MASK 0xE0U #define GT_GET_TYPE(x) ((x) & GT_TYPE_MASK) #define GT_IS_INTEGER(x) (GT_GET_TYPE(x) == GT_TYPE_INTEGER) #define GT_IS_POINTER(x) (GT_GET_TYPE(x) == GT_TYPE_POINTER) #define GT_IS_FLOAT(x) (GT_GET_TYPE(x) == GT_TYPE_FLOAT) #define GT_IS_ARRAY(x) (GT_GET_TYPE(x) == GT_TYPE_ARRAY) #define GT_IS_FUNCTION(x) (GT_GET_TYPE(x) == GT_TYPE_FUNCTION) #define GT_IS_STRUCT(x) (GT_GET_TYPE(x) == GT_TYPE_STRUCT) #define GT_IS_UNION(x) (GT_GET_TYPE(x) == GT_TYPE_UNION) /* Combined values for the 6502 family */ #define GT_VOID (GT_TYPE_VOID) #define GT_BYTE (GT_TYPE_INT | GT_LITTLE_ENDIAN | GT_UNSIGNED | GT_SIZE_1) #define GT_WORD (GT_TYPE_INT | GT_LITTLE_ENDIAN | GT_UNSIGNED | GT_SIZE_2) #define GT_DWORD (GT_TYPE_INT | GT_LITTLE_ENDIAN | GT_UNSIGNED | GT_SIZE_4) #define GT_DBYTE (GT_TYPE_PTR | GT_BIG_ENDIAN | GT_UNSIGNED | GT_SIZE_2) #define GT_PTR (GT_TYPE_PTR | GT_LITTLE_ENDIAN | GT_UNSIGNED | GT_SIZE_2) #define GT_FAR_PTR (GT_TYPE_PTR | GT_LITTLE_ENDIAN | GT_UNSIGNED | GT_SIZE_3) #define GT_ARRAY(size) (GT_TYPE_ARRAY | ((size) - 1)) static void FreeTypeInfo (TypeInfo* T) /* Free a TypeInfo struct */ { xfree (T); } static void InitTypeParseData (TypeParseData* P, const StrBuf* Type, unsigned ItemCount) /* Initialize a TypeParseData structure */ { P->Info = xmalloc (sizeof (*P->Info) - sizeof (P->Info->Data[0]) + ItemCount * sizeof (P->Info->Data[0])); P->ItemCount = ItemCount; P->ItemIndex = 0; P->ItemData = P->Info->Data; P->Type = Type; P->Pos = 0; P->Error = 0; } static cc65_typedata* TypeFromString (TypeParseData* P) /* Parse a type string and return a set of typedata structures. Will be called * recursively. Will set P->Error and return NULL in case of problems. */ { cc65_typedata* Data; unsigned char B; unsigned I; unsigned Count; /* Allocate a new entry */ if (P->ItemIndex >= P->ItemCount) { P->Error = 1; return 0; } Data = &P->ItemData[P->ItemIndex++]; /* Assume no following node */ Data->next = 0; /* Get the next char, then skip it */ if (P->Pos >= SB_GetLen (P->Type)) { P->Error = 1; return 0; } B = SB_At (P->Type, P->Pos++); switch (B) { /* We only handle those that are currently in use */ case GT_VOID: Data->what = CC65_TYPE_VOID; Data->size = 0; break; case GT_BYTE: Data->what = CC65_TYPE_BYTE; Data->size = GT_GET_SIZE (B); break; case GT_WORD: Data->what = CC65_TYPE_WORD; Data->size = GT_GET_SIZE (B); break; case GT_DWORD: Data->what = CC65_TYPE_DWORD; Data->size = GT_GET_SIZE (B); break; case GT_DBYTE: Data->what = CC65_TYPE_DBYTE; Data->size = GT_GET_SIZE (B); break; case GT_PTR: Data->what = CC65_TYPE_PTR; Data->data.ptr.ind_type = TypeFromString (P); Data->size = GT_GET_SIZE (B); break; case GT_FAR_PTR: Data->what = CC65_TYPE_FARPTR; Data->data.ptr.ind_type = TypeFromString (P); Data->size = GT_GET_SIZE (B); break; default: if (GT_GET_TYPE (B) == GT_TYPE_ARRAY) { Count = 0; I = GT_GET_SIZE (B); if (I == 0 || I > 4) { P->Error = 1; break; } P->Pos += I; if (P->Pos > SB_GetLen (P->Type)) { P->Error = 1; break; } while (I) { Count <<= 8; Count |= (unsigned char) SB_At (P->Type, P->Pos - I); --I; } Data->what = CC65_TYPE_ARRAY; Data->data.array.ele_count = Count; Data->data.array.ele_type = TypeFromString (P); if (!P->Error) { Data->size = Data->data.array.ele_count * Data->data.array.ele_type->size; } } else { /* OOPS! */ P->Error = 1; } break; } /* Return our structure or NULL in case of errors */ return P->Error? 0 : Data; } static TypeInfo* ParseTypeString (InputData* D, StrBuf* Type) /* Check if the string T contains a valid type string. Convert it from readable * to binary. Calculate how many cc65_typedata structures are necessary when it * is converted. Convert the string into a set of cc65_typedata structures and * return them. */ { unsigned I; unsigned Count; const char* A; char* B; TypeParseData P; /* The length must not be zero and divideable by two */ unsigned Length = SB_GetLen (Type); if (Length < 2 || (Length & 0x01) != 0) { ParseError (D, CC65_ERROR, "Type value has invalid length"); return 0; } /* The string must consist completely of hex digit chars */ A = SB_GetConstBuf (Type); for (I = 0; I < Length; ++I) { if (!isxdigit (A[I])) { ParseError (D, CC65_ERROR, "Type value contains invalid characters"); return 0; } } /* Convert the type to binary */ B = SB_GetBuf (Type); while (A < SB_GetConstBuf (Type) + Length) { /* Since we know, there are only hex digits, there can't be any errors */ *B++ = (HexValue (A[0]) << 4) | HexValue (A[1]); A += 2; } Type->Len = (Length /= 2); /* Get a pointer to the type data, then count the number of cc65_typedata * items needed. */ A = SB_GetConstBuf (Type); Count = 0; I = 0; while (I < Length) { switch (A[I]) { /* We only handle those that are currently in use */ case GT_VOID: case GT_BYTE: case GT_WORD: case GT_DWORD: case GT_DBYTE: case GT_PTR: case GT_FAR_PTR: ++Count; ++I; break; default: if (GT_GET_TYPE (A[I]) == GT_TYPE_ARRAY) { ++Count; I += GT_GET_SIZE (A[I]) + 1; } else { /* Unknown type in type string */ ParseError (D, CC65_ERROR, "Unkown type in type value"); return 0; } break; } } /* Check that we're even */ if (I != Length) { ParseError (D, CC65_ERROR, "Syntax error in type in type value"); return 0; } /* Initialize the data structure for parsing the type string */ InitTypeParseData (&P, Type, Count); /* Parse the type string and check for errors */ if (TypeFromString (&P) == 0 || P.ItemCount != P.ItemIndex) { ParseError (D, CC65_ERROR, "Error parsing the type value"); FreeTypeInfo (P.Info); return 0; } /* Return the result of the parse operation */ return P.Info; } /*****************************************************************************/ /* SpanInfoList */ /*****************************************************************************/ static void InitSpanInfoList (SpanInfoList* L) /* Initialize a span info list */ { L->Count = 0; L->List = 0; } static void CreateSpanInfoList (SpanInfoList* L, Collection* SpanInfos) /* Create a SpanInfoList from a Collection with span infos. The collection * must be sorted by ascending start addresses. */ { unsigned I, J; SpanInfo* S; SpanInfoListEntry* List; unsigned StartIndex; cc65_addr Start; cc65_addr Addr; cc65_addr End; /* Initialize and check if there's something to do */ L->Count = 0; L->List = 0; if (CollCount (SpanInfos) == 0) { /* No entries */ return; } /* Step 1: Determine the number of unique address entries needed */ S = CollAt (SpanInfos, 0); L->Count += (S->End - S->Start) + 1; End = S->End; for (I = 1; I < CollCount (SpanInfos); ++I) { /* Get next entry */ S = CollAt (SpanInfos, I); /* Check for additional unique addresses in this span info */ if (S->Start > End) { L->Count += (S->End - S->Start) + 1; End = S->End; } else if (S->End > End) { L->Count += (S->End - End); End = S->End; } } /* Step 2: Allocate memory and initialize it */ L->List = List = xmalloc (L->Count * sizeof (*List)); for (I = 0; I < L->Count; ++I) { List[I].Count = 0; List[I].Data = 0; } /* Step 3: Determine the number of entries per unique address */ List = L->List; S = CollAt (SpanInfos, 0); StartIndex = 0; Start = S->Start; End = S->End; for (J = StartIndex, Addr = S->Start; Addr <= S->End; ++J, ++Addr) { List[J].Addr = Addr; ++List[J].Count; } for (I = 1; I < CollCount (SpanInfos); ++I) { /* Get next entry */ S = CollAt (SpanInfos, I); /* Determine the start index of the next range. Line infos are sorted * by ascending start address, so the start address of the next entry * is always larger than the previous one - we don't need to check * that. */ if (S->Start <= End) { /* Range starts within out already known linear range */ StartIndex += (unsigned) (S->Start - Start); Start = S->Start; if (S->End > End) { End = S->End; } } else { /* Range starts after the already known */ StartIndex += (unsigned) (End - Start) + 1; Start = S->Start; End = S->End; } for (J = StartIndex, Addr = S->Start; Addr <= S->End; ++J, ++Addr) { List[J].Addr = Addr; ++List[J].Count; } } /* Step 4: Allocate memory for the indirect tables */ for (I = 0, List = L->List; I < L->Count; ++I, ++List) { /* For a count of 1, we store the pointer to the lineinfo for this * address in the Data pointer directly. For counts > 1, we allocate * an array of pointers and reset the counter, so we can use it as * an index later. This is dangerous programming since it disables * all possible checks! */ if (List->Count > 1) { List->Data = xmalloc (List->Count * sizeof (SpanInfo*)); List->Count = 0; } } /* Step 5: Enter the data into the table */ List = L->List; S = CollAt (SpanInfos, 0); StartIndex = 0; Start = S->Start; End = S->End; for (J = StartIndex, Addr = S->Start; Addr <= S->End; ++J, ++Addr) { assert (List[J].Addr == Addr); if (List[J].Count == 1 && List[J].Data == 0) { List[J].Data = S; } else { ((SpanInfo**) List[J].Data)[List[J].Count++] = S; } } for (I = 1; I < CollCount (SpanInfos); ++I) { /* Get next entry */ S = CollAt (SpanInfos, I); /* Determine the start index of the next range. Line infos are sorted * by ascending start address, so the start address of the next entry * is always larger than the previous one - we don't need to check * that. */ if (S->Start <= End) { /* Range starts within out already known linear range */ StartIndex += (unsigned) (S->Start - Start); Start = S->Start; if (S->End > End) { End = S->End; } } else { /* Range starts after the already known */ StartIndex += (unsigned) (End - Start) + 1; Start = S->Start; End = S->End; } for (J = StartIndex, Addr = S->Start; Addr <= S->End; ++J, ++Addr) { assert (List[J].Addr == Addr); if (List[J].Count == 1 && List[J].Data == 0) { List[J].Data = S; } else { ((SpanInfo**) List[J].Data)[List[J].Count++] = S; } } } } static void DoneSpanInfoList (SpanInfoList* L) /* Delete the contents of a span info list */ { unsigned I; /* Delete the span info and the indirect data */ for (I = 0; I < L->Count; ++I) { /* Get a pointer to the entry */ SpanInfoListEntry* E = &L->List[I]; /* Check for indirect memory */ if (E->Count > 1) { /* SpanInfo addressed indirectly */ xfree (E->Data); } } /* Delete the list */ xfree (L->List); } /*****************************************************************************/ /* Debug info */ /*****************************************************************************/ static DbgInfo* NewDbgInfo (const char* FileName) /* Create a new DbgInfo struct and return it */ { /* Get the length of the name */ unsigned Len = strlen (FileName); /* Allocate memory */ DbgInfo* Info = xmalloc (sizeof (DbgInfo) + Len); /* Initialize it */ CollInit (&Info->CSymInfoById); CollInit (&Info->FileInfoById); CollInit (&Info->LibInfoById); CollInit (&Info->LineInfoById); CollInit (&Info->ModInfoById); CollInit (&Info->ScopeInfoById); CollInit (&Info->SegInfoById); CollInit (&Info->SpanInfoById); CollInit (&Info->SymInfoById); CollInit (&Info->TypeInfoById); CollInit (&Info->CSymFuncByName); CollInit (&Info->FileInfoByName); CollInit (&Info->ModInfoByName); CollInit (&Info->ScopeInfoByName); CollInit (&Info->SegInfoByName); CollInit (&Info->SymInfoByName); CollInit (&Info->SymInfoByVal); InitSpanInfoList (&Info->SpanInfoByAddr); Info->MemUsage = 0; Info->MajorVersion = 0; Info->MinorVersion = 0; memcpy (&Info->FileName, FileName, Len+1); /* Return it */ return Info; } static void FreeDbgInfo (DbgInfo* Info) /* Free a DbgInfo struct */ { unsigned I; /* First, free the items in the collections */ for (I = 0; I < CollCount (&Info->CSymInfoById); ++I) { FreeCSymInfo (CollAt (&Info->CSymInfoById, I)); } for (I = 0; I < CollCount (&Info->FileInfoById); ++I) { FreeFileInfo (CollAt (&Info->FileInfoById, I)); } for (I = 0; I < CollCount (&Info->LibInfoById); ++I) { FreeLibInfo (CollAt (&Info->LibInfoById, I)); } for (I = 0; I < CollCount (&Info->LineInfoById); ++I) { FreeLineInfo (CollAt (&Info->LineInfoById, I)); } for (I = 0; I < CollCount (&Info->ModInfoById); ++I) { FreeModInfo (CollAt (&Info->ModInfoById, I)); } for (I = 0; I < CollCount (&Info->ScopeInfoById); ++I) { FreeScopeInfo (CollAt (&Info->ScopeInfoById, I)); } for (I = 0; I < CollCount (&Info->SegInfoById); ++I) { FreeSegInfo (CollAt (&Info->SegInfoById, I)); } for (I = 0; I < CollCount (&Info->SpanInfoById); ++I) { FreeSpanInfo (CollAt (&Info->SpanInfoById, I)); } for (I = 0; I < CollCount (&Info->SymInfoById); ++I) { FreeSymInfo (CollAt (&Info->SymInfoById, I)); } for (I = 0; I < CollCount (&Info->TypeInfoById); ++I) { FreeTypeInfo (CollAt (&Info->TypeInfoById, I)); } /* Free the memory used by the id collections */ CollDone (&Info->CSymInfoById); CollDone (&Info->FileInfoById); CollDone (&Info->LibInfoById); CollDone (&Info->LineInfoById); CollDone (&Info->ModInfoById); CollDone (&Info->ScopeInfoById); CollDone (&Info->SegInfoById); CollDone (&Info->SpanInfoById); CollDone (&Info->SymInfoById); CollDone (&Info->TypeInfoById); /* Free the memory used by the other collections */ CollDone (&Info->CSymFuncByName); CollDone (&Info->FileInfoByName); CollDone (&Info->ModInfoByName); CollDone (&Info->ScopeInfoByName); CollDone (&Info->SegInfoByName); CollDone (&Info->SymInfoByName); CollDone (&Info->SymInfoByVal); /* Free span info */ DoneSpanInfoList (&Info->SpanInfoByAddr); /* Free the structure itself */ xfree (Info); } /*****************************************************************************/ /* Scanner and parser */ /*****************************************************************************/ static int DigitVal (int C) /* Return the value for a numeric digit. Return -1 if C is invalid */ { if (isdigit (C)) { return C - '0'; } else if (isxdigit (C)) { return toupper (C) - 'A' + 10; } else { return -1; } } static void NextChar (InputData* D) /* Read the next character from the input. Count lines and columns */ { /* Check if we've encountered EOF before */ if (D->C >= 0) { if (D->C == '\n') { ++D->Line; D->Col = 0; } D->C = fgetc (D->F); ++D->Col; } } static void NextToken (InputData* D) /* Read the next token from the input stream */ { static const struct KeywordEntry { const char Keyword[12]; Token Tok; } KeywordTable[] = { { "abs", TOK_ABSOLUTE }, { "addrsize", TOK_ADDRSIZE }, { "auto", TOK_AUTO }, { "count", TOK_COUNT }, { "csym", TOK_CSYM }, { "def", TOK_DEF }, { "enum", TOK_ENUM }, { "equ", TOK_EQUATE }, { "exp", TOK_EXPORT }, { "ext", TOK_EXTERN }, { "file", TOK_FILE }, { "func", TOK_FUNC }, { "global", TOK_GLOBAL }, { "id", TOK_ID }, { "imp", TOK_IMPORT }, { "info", TOK_INFO }, { "lab", TOK_LABEL }, { "lib", TOK_LIBRARY }, { "line", TOK_LINE }, { "long", TOK_LONG }, { "major", TOK_MAJOR }, { "minor", TOK_MINOR }, { "mod", TOK_MODULE }, { "mtime", TOK_MTIME }, { "name", TOK_NAME }, { "offs", TOK_OFFS }, { "oname", TOK_OUTPUTNAME }, { "ooffs", TOK_OUTPUTOFFS }, { "parent", TOK_PARENT }, { "ref", TOK_REF }, { "reg", TOK_REGISTER }, { "ro", TOK_RO }, { "rw", TOK_RW }, { "sc", TOK_SC }, { "scope", TOK_SCOPE }, { "seg", TOK_SEGMENT }, { "size", TOK_SIZE }, { "span", TOK_SPAN }, { "start", TOK_START }, { "static", TOK_STATIC }, { "struct", TOK_STRUCT }, { "sym", TOK_SYM }, { "type", TOK_TYPE }, { "val", TOK_VALUE }, { "var", TOK_VAR }, { "version", TOK_VERSION }, { "zp", TOK_ZEROPAGE }, }; /* Skip whitespace */ while (D->C == ' ' || D->C == '\t' || D->C == '\r') { NextChar (D); } /* Remember the current position as start of the next token */ D->SLine = D->Line; D->SCol = D->Col; /* Identifier? */ if (D->C == '_' || isalpha (D->C)) { const struct KeywordEntry* Entry; /* Read the identifier */ SB_Clear (&D->SVal); while (D->C == '_' || isalnum (D->C)) { SB_AppendChar (&D->SVal, D->C); NextChar (D); } SB_Terminate (&D->SVal); /* Search the identifier in the keyword table */ Entry = bsearch (SB_GetConstBuf (&D->SVal), KeywordTable, sizeof (KeywordTable) / sizeof (KeywordTable[0]), sizeof (KeywordTable[0]), (int (*)(const void*, const void*)) strcmp); if (Entry == 0) { D->Tok = TOK_IDENT; } else { D->Tok = Entry->Tok; } return; } /* Number? */ if (isdigit (D->C)) { int Base = 10; int Val; if (D->C == '0') { NextChar (D); if (toupper (D->C) == 'X') { NextChar (D); Base = 16; } else { Base = 8; } } else { Base = 10; } D->IVal = 0; while ((Val = DigitVal (D->C)) >= 0 && Val < Base) { D->IVal = D->IVal * Base + Val; NextChar (D); } D->Tok = TOK_INTCON; return; } /* Other characters */ switch (D->C) { case '-': NextChar (D); D->Tok = TOK_MINUS; break; case '+': NextChar (D); D->Tok = TOK_PLUS; break; case ',': NextChar (D); D->Tok = TOK_COMMA; break; case '=': NextChar (D); D->Tok = TOK_EQUAL; break; case '\"': SB_Clear (&D->SVal); NextChar (D); while (1) { if (D->C == '\n' || D->C == EOF) { ParseError (D, CC65_ERROR, "Unterminated string constant"); break; } if (D->C == '\"') { NextChar (D); break; } SB_AppendChar (&D->SVal, D->C); NextChar (D); } SB_Terminate (&D->SVal); D->Tok = TOK_STRCON; break; case '\n': NextChar (D); D->Tok = TOK_EOL; break; case EOF: D->Tok = TOK_EOF; break; default: ParseError (D, CC65_ERROR, "Invalid input character `%c'", D->C); } } static int TokenIsKeyword (Token Tok) /* Return true if the given token is a keyword */ { return (Tok >= TOK_FIRST_KEYWORD && Tok <= TOK_LAST_KEYWORD); } static int TokenFollows (InputData* D, Token Tok, const char* Name) /* Check for a specific token that follows. */ { if (D->Tok != Tok) { ParseError (D, CC65_ERROR, "%s expected", Name); SkipLine (D); return 0; } else { return 1; } } static int IntConstFollows (InputData* D) /* Check for an integer constant */ { return TokenFollows (D, TOK_INTCON, "Integer constant"); } static int StrConstFollows (InputData* D) /* Check for a string literal */ { return TokenFollows (D, TOK_STRCON, "String literal"); } static int Consume (InputData* D, Token Tok, const char* Name) /* Check for a token and consume it. Return true if the token was comsumed, * return false otherwise. */ { if (TokenFollows (D, Tok, Name)) { NextToken (D); return 1; } else { return 0; } } static int ConsumeEqual (InputData* D) /* Consume an equal sign */ { return Consume (D, TOK_EQUAL, "'='"); } static void ConsumeEOL (InputData* D) /* Consume an end-of-line token, if we aren't at end-of-file */ { if (D->Tok != TOK_EOF) { if (D->Tok != TOK_EOL) { ParseError (D, CC65_ERROR, "Extra tokens in line"); SkipLine (D); } NextToken (D); } } static void ParseCSym (InputData* D) /* Parse a CSYM line */ { /* Most of the following variables are initialized with a value that is * overwritten later. This is just to avoid compiler warnings. */ unsigned Id = 0; StrBuf Name = STRBUF_INITIALIZER; int Offs = 0; cc65_csym_sc SC = CC65_CSYM_AUTO; unsigned ScopeId = 0; unsigned SymId = CC65_INV_ID; unsigned TypeId = CC65_INV_ID; CSymInfo* S; enum { ibNone = 0x0000, ibId = 0x0001, ibOffs = 0x0002, ibName = 0x0004, ibSC = 0x0008, ibScopeId = 0x0010, ibSymId = 0x0020, ibType = 0x0040, ibRequired = ibId | ibName | ibSC | ibScopeId | ibType, } InfoBits = ibNone; /* Skip the CSYM token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_NAME && D->Tok != TOK_OFFS && D->Tok != TOK_SC && D->Tok != TOK_SCOPE && D->Tok != TOK_SYM && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; NextToken (D); InfoBits |= ibId; break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_OFFS: Offs = 1; if (D->Tok == TOK_MINUS) { Offs = -1; NextToken (D); } if (!IntConstFollows (D)) { goto ErrorExit; } Offs *= (int) D->IVal; InfoBits |= ibOffs; NextToken (D); break; case TOK_SC: switch (D->Tok) { case TOK_AUTO: SC = CC65_CSYM_AUTO; break; case TOK_EXTERN: SC = CC65_CSYM_EXTERN; break; case TOK_REGISTER: SC = CC65_CSYM_REG; break; case TOK_STATIC: SC = CC65_CSYM_STATIC; break; default: ParseError (D, CC65_ERROR, "Invalid storage class token"); break; } InfoBits |= ibSC; NextToken (D); break; case TOK_SCOPE: if (!IntConstFollows (D)) { goto ErrorExit; } ScopeId = D->IVal; NextToken (D); InfoBits |= ibScopeId; break; case TOK_SYM: if (!IntConstFollows (D)) { goto ErrorExit; } SymId = D->IVal; NextToken (D); InfoBits |= ibSymId; break; case TOK_TYPE: if (!IntConstFollows (D)) { goto ErrorExit; } TypeId = D->IVal; NextToken (D); InfoBits |= ibType; break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Symbol only valid if storage class not auto */ if (((InfoBits & ibSymId) != 0) != (SC != CC65_CSYM_AUTO)) { ParseError (D, CC65_ERROR, "Only non auto symbols can have a symbol attached"); goto ErrorExit; } /* Create the symbol info */ S = NewCSymInfo (&Name); S->Id = Id; S->Kind = CC65_CSYM_VAR; S->SC = SC; S->Offs = Offs; S->Sym.Id = SymId; S->Type.Id = TypeId; S->Scope.Id = ScopeId; /* Remember it */ CollReplaceExpand (&D->Info->CSymInfoById, S, Id); ErrorExit: /* Entry point in case of errors */ SB_Done (&Name); return; } static void ParseFile (InputData* D) /* Parse a FILE line */ { unsigned Id = 0; unsigned long Size = 0; unsigned long MTime = 0; Collection ModIds = COLLECTION_INITIALIZER; StrBuf Name = STRBUF_INITIALIZER; FileInfo* F; enum { ibNone = 0x00, ibId = 0x01, ibName = 0x02, ibSize = 0x04, ibMTime = 0x08, ibModId = 0x10, ibRequired = ibId | ibName | ibSize | ibMTime | ibModId, } InfoBits = ibNone; /* Skip the FILE token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_MODULE && D->Tok != TOK_MTIME && D->Tok != TOK_NAME && D->Tok != TOK_SIZE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_MTIME: if (!IntConstFollows (D)) { goto ErrorExit; } MTime = D->IVal; NextToken (D); InfoBits |= ibMTime; break; case TOK_MODULE: while (1) { if (!IntConstFollows (D)) { goto ErrorExit; } CollAppendId (&ModIds, (unsigned) D->IVal); NextToken (D); if (D->Tok != TOK_PLUS) { break; } NextToken (D); } InfoBits |= ibModId; break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_SIZE: if (!IntConstFollows (D)) { goto ErrorExit; } Size = D->IVal; NextToken (D); InfoBits |= ibSize; break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the file info and remember it */ F = NewFileInfo (&Name); F->Id = Id; F->Size = Size; F->MTime = MTime; CollMove (&ModIds, &F->ModInfoByName); CollReplaceExpand (&D->Info->FileInfoById, F, Id); CollAppend (&D->Info->FileInfoByName, F); ErrorExit: /* Entry point in case of errors */ CollDone (&ModIds); SB_Done (&Name); return; } static void ParseInfo (InputData* D) /* Parse an INFO line */ { /* Skip the INFO token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_CSYM && D->Tok != TOK_FILE && D->Tok != TOK_LIBRARY && D->Tok != TOK_LINE && D->Tok != TOK_MODULE && D->Tok != TOK_SCOPE && D->Tok != TOK_SEGMENT && D->Tok != TOK_SPAN && D->Tok != TOK_SYM && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal, check for an integer * constant. */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } if (!IntConstFollows (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_CSYM: CollGrow (&D->Info->CSymInfoById, D->IVal); break; case TOK_FILE: CollGrow (&D->Info->FileInfoById, D->IVal); CollGrow (&D->Info->FileInfoByName, D->IVal); break; case TOK_LIBRARY: CollGrow (&D->Info->LibInfoById, D->IVal); break; case TOK_LINE: CollGrow (&D->Info->LineInfoById, D->IVal); break; case TOK_MODULE: CollGrow (&D->Info->ModInfoById, D->IVal); CollGrow (&D->Info->ModInfoByName, D->IVal); break; case TOK_SCOPE: CollGrow (&D->Info->ScopeInfoById, D->IVal); CollGrow (&D->Info->ScopeInfoByName, D->IVal); break; case TOK_SEGMENT: CollGrow (&D->Info->SegInfoById, D->IVal); CollGrow (&D->Info->SegInfoByName, D->IVal); break; case TOK_SPAN: CollGrow (&D->Info->SpanInfoById, D->IVal); break; case TOK_SYM: CollGrow (&D->Info->SymInfoById, D->IVal); CollGrow (&D->Info->SymInfoByName, D->IVal); CollGrow (&D->Info->SymInfoByVal, D->IVal); break; case TOK_TYPE: CollGrow (&D->Info->TypeInfoById, D->IVal); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Skip the number */ NextToken (D); /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } ErrorExit: /* Entry point in case of errors */ return; } static void ParseLibrary (InputData* D) /* Parse a LIBRARY line */ { unsigned Id = 0; StrBuf Name = STRBUF_INITIALIZER; LibInfo* L; enum { ibNone = 0x00, ibId = 0x01, ibName = 0x02, ibRequired = ibId | ibName, } InfoBits = ibNone; /* Skip the LIBRARY token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_NAME) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the library info and remember it */ L = NewLibInfo (&Name); L->Id = Id; CollReplaceExpand (&D->Info->LibInfoById, L, Id); ErrorExit: /* Entry point in case of errors */ SB_Done (&Name); return; } static void ParseLine (InputData* D) /* Parse a LINE line */ { unsigned Id = CC65_INV_ID; unsigned FileId = CC65_INV_ID; Collection SpanIds = COLLECTION_INITIALIZER; cc65_line Line = 0; cc65_line_type Type = CC65_LINE_ASM; unsigned Count = 0; LineInfo* L; enum { ibNone = 0x00, ibCount = 0x01, ibFileId = 0x02, ibId = 0x04, ibLine = 0x08, ibSpanId = 0x20, ibType = 0x40, ibRequired = ibFileId | ibId | ibLine, } InfoBits = ibNone; /* Skip the LINE token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_COUNT && D->Tok != TOK_FILE && D->Tok != TOK_ID && D->Tok != TOK_LINE && D->Tok != TOK_SPAN && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_FILE: if (!IntConstFollows (D)) { goto ErrorExit; } FileId = D->IVal; InfoBits |= ibFileId; NextToken (D); break; case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_LINE: if (!IntConstFollows (D)) { goto ErrorExit; } Line = (cc65_line) D->IVal; NextToken (D); InfoBits |= ibLine; break; case TOK_SPAN: while (1) { if (!IntConstFollows (D)) { goto ErrorExit; } CollAppendId (&SpanIds, (unsigned) D->IVal); NextToken (D); if (D->Tok != TOK_PLUS) { break; } NextToken (D); } InfoBits |= ibSpanId; break; case TOK_TYPE: if (!IntConstFollows (D)) { goto ErrorExit; } Type = (cc65_line_type) D->IVal; InfoBits |= ibType; NextToken (D); break; case TOK_COUNT: if (!IntConstFollows (D)) { goto ErrorExit; } Count = D->IVal; InfoBits |= ibCount; NextToken (D); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the line info and remember it */ L = NewLineInfo (); L->Id = Id; L->Line = Line; L->File.Id = FileId; L->Type = Type; L->Count = Count; CollMove (&SpanIds, &L->SpanInfoList); CollReplaceExpand (&D->Info->LineInfoById, L, Id); ErrorExit: /* Entry point in case of errors */ CollDone (&SpanIds); return; } static void ParseModule (InputData* D) /* Parse a MODULE line */ { /* Most of the following variables are initialized with a value that is * overwritten later. This is just to avoid compiler warnings. */ unsigned Id = CC65_INV_ID; StrBuf Name = STRBUF_INITIALIZER; unsigned FileId = CC65_INV_ID; unsigned LibId = CC65_INV_ID; ModInfo* M; enum { ibNone = 0x000, ibFileId = 0x001, ibId = 0x002, ibName = 0x004, ibLibId = 0x008, ibRequired = ibId | ibName | ibFileId, } InfoBits = ibNone; /* Skip the MODULE token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_FILE && D->Tok != TOK_ID && D->Tok != TOK_NAME && D->Tok != TOK_LIBRARY) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_FILE: if (!IntConstFollows (D)) { goto ErrorExit; } FileId = D->IVal; InfoBits |= ibFileId; NextToken (D); break; case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_LIBRARY: if (!IntConstFollows (D)) { goto ErrorExit; } LibId = D->IVal; InfoBits |= ibLibId; NextToken (D); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the scope info */ M = NewModInfo (&Name); M->File.Id = FileId; M->Id = Id; M->Lib.Id = LibId; /* ... and remember it */ CollReplaceExpand (&D->Info->ModInfoById, M, Id); CollAppend (&D->Info->ModInfoByName, M); ErrorExit: /* Entry point in case of errors */ SB_Done (&Name); return; } static void ParseScope (InputData* D) /* Parse a SCOPE line */ { /* Most of the following variables are initialized with a value that is * overwritten later. This is just to avoid compiler warnings. */ unsigned Id = CC65_INV_ID; cc65_scope_type Type = CC65_SCOPE_MODULE; cc65_size Size = 0; StrBuf Name = STRBUF_INITIALIZER; unsigned ModId = CC65_INV_ID; unsigned ParentId = CC65_INV_ID; Collection SpanIds = COLLECTION_INITIALIZER; unsigned SymId = CC65_INV_ID; ScopeInfo* S; enum { ibNone = 0x000, ibId = 0x001, ibModId = 0x002, ibName = 0x004, ibParentId = 0x008, ibSize = 0x010, ibSpanId = 0x020, ibSymId = 0x040, ibType = 0x080, ibRequired = ibId | ibModId | ibName, } InfoBits = ibNone; /* Skip the SCOPE token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_MODULE && D->Tok != TOK_NAME && D->Tok != TOK_PARENT && D->Tok != TOK_SIZE && D->Tok != TOK_SPAN && D->Tok != TOK_SYM && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_MODULE: if (!IntConstFollows (D)) { goto ErrorExit; } ModId = D->IVal; InfoBits |= ibModId; NextToken (D); break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_PARENT: if (!IntConstFollows (D)) { goto ErrorExit; } ParentId = D->IVal; NextToken (D); InfoBits |= ibParentId; break; case TOK_SIZE: if (!IntConstFollows (D)) { goto ErrorExit; } Size = (cc65_size) D->IVal; InfoBits |= ibSize; NextToken (D); break; case TOK_SPAN: while (1) { if (!IntConstFollows (D)) { goto ErrorExit; } CollAppendId (&SpanIds, (unsigned) D->IVal); NextToken (D); if (D->Tok != TOK_PLUS) { break; } NextToken (D); } InfoBits |= ibSpanId; break; case TOK_SYM: if (!IntConstFollows (D)) { goto ErrorExit; } SymId = D->IVal; NextToken (D); InfoBits |= ibSymId; break; case TOK_TYPE: switch (D->Tok) { case TOK_GLOBAL: Type = CC65_SCOPE_GLOBAL; break; case TOK_FILE: Type = CC65_SCOPE_MODULE; break; case TOK_SCOPE: Type = CC65_SCOPE_SCOPE; break; case TOK_STRUCT: Type = CC65_SCOPE_STRUCT; break; case TOK_ENUM: Type = CC65_SCOPE_ENUM; break; default: ParseError (D, CC65_ERROR, "Unknown value for attribute \"type\""); SkipLine (D); goto ErrorExit; } NextToken (D); InfoBits |= ibType; break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the scope info ... */ S = NewScopeInfo (&Name); S->Id = Id; S->Type = Type; S->Size = Size; S->Mod.Id = ModId; S->Parent.Id = ParentId; S->Label.Id = SymId; CollMove (&SpanIds, &S->SpanInfoList); /* ... and remember it */ CollReplaceExpand (&D->Info->ScopeInfoById, S, Id); CollAppend (&D->Info->ScopeInfoByName, S); ErrorExit: /* Entry point in case of errors */ CollDone (&SpanIds); SB_Done (&Name); return; } static void ParseSegment (InputData* D) /* Parse a SEGMENT line */ { unsigned Id = 0; cc65_addr Start = 0; cc65_addr Size = 0; StrBuf Name = STRBUF_INITIALIZER; StrBuf OutputName = STRBUF_INITIALIZER; unsigned long OutputOffs = 0; SegInfo* S; enum { ibNone = 0x000, ibAddrSize = 0x001, ibId = 0x002, ibOutputName= 0x004, ibOutputOffs= 0x008, ibName = 0x010, ibSize = 0x020, ibStart = 0x040, ibType = 0x080, ibRequired = ibId | ibName | ibStart | ibSize | ibAddrSize | ibType, } InfoBits = ibNone; /* Skip the SEGMENT token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ADDRSIZE && D->Tok != TOK_ID && D->Tok != TOK_NAME && D->Tok != TOK_OUTPUTNAME && D->Tok != TOK_OUTPUTOFFS && D->Tok != TOK_SIZE && D->Tok != TOK_START && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ADDRSIZE: NextToken (D); InfoBits |= ibAddrSize; break; case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_OUTPUTNAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&OutputName, &D->SVal); SB_Terminate (&OutputName); InfoBits |= ibOutputName; NextToken (D); break; case TOK_OUTPUTOFFS: if (!IntConstFollows (D)) { goto ErrorExit; } OutputOffs = D->IVal; NextToken (D); InfoBits |= ibOutputOffs; break; case TOK_SIZE: if (!IntConstFollows (D)) { goto ErrorExit; } Size = D->IVal; NextToken (D); InfoBits |= ibSize; break; case TOK_START: if (!IntConstFollows (D)) { goto ErrorExit; } Start = (cc65_addr) D->IVal; NextToken (D); InfoBits |= ibStart; break; case TOK_TYPE: NextToken (D); InfoBits |= ibType; break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } InfoBits &= (ibOutputName | ibOutputOffs); if (InfoBits != ibNone && InfoBits != (ibOutputName | ibOutputOffs)) { ParseError (D, CC65_ERROR, "Attributes \"outputname\" and \"outputoffs\" must be paired"); goto ErrorExit; } /* Fix OutputOffs if not given */ if (InfoBits == ibNone) { OutputOffs = 0; } /* Create the segment info and remember it */ S = NewSegInfo (&Name, Id, Start, Size, &OutputName, OutputOffs); CollReplaceExpand (&D->Info->SegInfoById, S, Id); CollAppend (&D->Info->SegInfoByName, S); ErrorExit: /* Entry point in case of errors */ SB_Done (&Name); SB_Done (&OutputName); return; } static void ParseSpan (InputData* D) /* Parse a SPAN line */ { unsigned Id = 0; cc65_addr Start = 0; cc65_addr Size = 0; unsigned SegId = CC65_INV_ID; unsigned TypeId = CC65_INV_ID; SpanInfo* S; enum { ibNone = 0x000, ibId = 0x01, ibSegId = 0x02, ibSize = 0x04, ibStart = 0x08, ibType = 0x10, ibRequired = ibId | ibSegId | ibSize | ibStart, } InfoBits = ibNone; /* Skip the SEGMENT token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_SEGMENT && D->Tok != TOK_SIZE && D->Tok != TOK_START && D->Tok != TOK_TYPE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; InfoBits |= ibId; NextToken (D); break; case TOK_SEGMENT: if (!IntConstFollows (D)) { goto ErrorExit; } SegId = D->IVal; InfoBits |= ibSegId; NextToken (D); break; case TOK_SIZE: if (!IntConstFollows (D)) { goto ErrorExit; } Size = D->IVal; NextToken (D); InfoBits |= ibSize; break; case TOK_START: if (!IntConstFollows (D)) { goto ErrorExit; } Start = (cc65_addr) D->IVal; NextToken (D); InfoBits |= ibStart; break; case TOK_TYPE: if (!IntConstFollows (D)) { goto ErrorExit; } TypeId = D->IVal; NextToken (D); InfoBits |= ibType; break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Create the span info and remember it */ S = NewSpanInfo (); S->Id = Id; S->Start = Start; S->End = Start + Size - 1; S->Seg.Id = SegId; S->Type.Id = TypeId; CollReplaceExpand (&D->Info->SpanInfoById, S, Id); ErrorExit: /* Entry point in case of errors */ return; } static void ParseSym (InputData* D) /* Parse a SYM line */ { /* Most of the following variables are initialized with a value that is * overwritten later. This is just to avoid compiler warnings. */ Collection DefLineIds = COLLECTION_INITIALIZER; unsigned ExportId = CC65_INV_ID; unsigned FileId = CC65_INV_ID; unsigned Id = CC65_INV_ID; StrBuf Name = STRBUF_INITIALIZER; unsigned ParentId = CC65_INV_ID; Collection RefLineIds = COLLECTION_INITIALIZER; unsigned ScopeId = CC65_INV_ID; unsigned SegId = CC65_INV_ID; cc65_size Size = 0; cc65_symbol_type Type = CC65_SYM_EQUATE; long Value = 0; SymInfo* S; enum { ibNone = 0x0000, ibAddrSize = 0x0001, ibDefLineId = 0x0002, ibExportId = 0x0004, ibFileId = 0x0008, ibId = 0x0010, ibParentId = 0x0020, ibRefLineId = 0x0040, ibScopeId = 0x0080, ibSegId = 0x0100, ibSize = 0x0200, ibName = 0x0400, ibType = 0x0800, ibValue = 0x1000, ibRequired = ibAddrSize | ibId | ibName, } InfoBits = ibNone; /* Skip the SYM token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ADDRSIZE && D->Tok != TOK_DEF && D->Tok != TOK_EXPORT && D->Tok != TOK_FILE && D->Tok != TOK_ID && D->Tok != TOK_NAME && D->Tok != TOK_PARENT && D->Tok != TOK_REF && D->Tok != TOK_SCOPE && D->Tok != TOK_SEGMENT && D->Tok != TOK_SIZE && D->Tok != TOK_TYPE && D->Tok != TOK_VALUE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ADDRSIZE: NextToken (D); InfoBits |= ibAddrSize; break; case TOK_DEF: while (1) { if (!IntConstFollows (D)) { goto ErrorExit; } CollAppendId (&DefLineIds, (unsigned) D->IVal); NextToken (D); if (D->Tok != TOK_PLUS) { break; } NextToken (D); } InfoBits |= ibDefLineId; break; case TOK_EXPORT: if (!IntConstFollows (D)) { goto ErrorExit; } ExportId = D->IVal; InfoBits |= ibExportId; NextToken (D); break; case TOK_FILE: if (!IntConstFollows (D)) { goto ErrorExit; } FileId = D->IVal; InfoBits |= ibFileId; NextToken (D); break; case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; NextToken (D); InfoBits |= ibId; break; case TOK_NAME: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Name, &D->SVal); SB_Terminate (&Name); InfoBits |= ibName; NextToken (D); break; case TOK_PARENT: if (!IntConstFollows (D)) { goto ErrorExit; } ParentId = D->IVal; NextToken (D); InfoBits |= ibParentId; break; case TOK_REF: while (1) { if (!IntConstFollows (D)) { goto ErrorExit; } CollAppendId (&RefLineIds, (unsigned) D->IVal); NextToken (D); if (D->Tok != TOK_PLUS) { break; } NextToken (D); } InfoBits |= ibRefLineId; break; case TOK_SCOPE: if (!IntConstFollows (D)) { goto ErrorExit; } ScopeId = D->IVal; NextToken (D); InfoBits |= ibScopeId; break; case TOK_SEGMENT: if (!IntConstFollows (D)) { goto ErrorExit; } SegId = (unsigned) D->IVal; InfoBits |= ibSegId; NextToken (D); break; case TOK_SIZE: if (!IntConstFollows (D)) { goto ErrorExit; } Size = (cc65_size) D->IVal; InfoBits |= ibSize; NextToken (D); break; case TOK_TYPE: switch (D->Tok) { case TOK_EQUATE: Type = CC65_SYM_EQUATE; break; case TOK_IMPORT: Type = CC65_SYM_IMPORT; break; case TOK_LABEL: Type = CC65_SYM_LABEL; break; default: ParseError (D, CC65_ERROR, "Unknown value for attribute \"type\""); SkipLine (D); goto ErrorExit; } NextToken (D); InfoBits |= ibType; break; case TOK_VALUE: if (!IntConstFollows (D)) { goto ErrorExit; } Value = D->IVal; InfoBits |= ibValue; NextToken (D); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } if ((InfoBits & (ibScopeId | ibParentId)) == 0 || (InfoBits & (ibScopeId | ibParentId)) == (ibScopeId | ibParentId)) { ParseError (D, CC65_ERROR, "Only one of \"parent\", \"scope\" must be specified"); goto ErrorExit; } /* Create the symbol info */ S = NewSymInfo (&Name); S->Id = Id; S->Type = Type; S->Value = Value; S->Size = Size; S->Exp.Id = ExportId; S->Seg.Id = SegId; S->Scope.Id = ScopeId; S->Parent.Id = ParentId; CollMove (&DefLineIds, &S->DefLineInfoList); CollMove (&RefLineIds, &S->RefLineInfoList); /* Remember it */ CollReplaceExpand (&D->Info->SymInfoById, S, Id); CollAppend (&D->Info->SymInfoByName, S); CollAppend (&D->Info->SymInfoByVal, S); ErrorExit: /* Entry point in case of errors */ CollDone (&DefLineIds); CollDone (&RefLineIds); SB_Done (&Name); return; } static void ParseType (InputData* D) /* Parse a TYPE line */ { /* Most of the following variables are initialized with a value that is * overwritten later. This is just to avoid compiler warnings. */ unsigned Id = CC65_INV_ID; StrBuf Value = STRBUF_INITIALIZER; TypeInfo* T; enum { ibNone = 0x0000, ibId = 0x01, ibValue = 0x02, ibRequired = ibId | ibValue, } InfoBits = ibNone; /* Skip the SYM token */ NextToken (D); /* More stuff follows */ while (1) { Token Tok; /* Something we know? */ if (D->Tok != TOK_ID && D->Tok != TOK_VALUE) { /* Try smart error recovery */ if (D->Tok == TOK_IDENT || TokenIsKeyword (D->Tok)) { UnknownKeyword (D); continue; } /* Done */ break; } /* Remember the token, skip it, check for equal */ Tok = D->Tok; NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } /* Check what the token was */ switch (Tok) { case TOK_ID: if (!IntConstFollows (D)) { goto ErrorExit; } Id = D->IVal; NextToken (D); InfoBits |= ibId; break; case TOK_VALUE: if (!StrConstFollows (D)) { goto ErrorExit; } SB_Copy (&Value, &D->SVal); InfoBits |= ibValue; NextToken (D); break; default: /* NOTREACHED */ UnexpectedToken (D); goto ErrorExit; } /* Comma or done */ if (D->Tok != TOK_COMMA) { break; } NextToken (D); } /* Check for end of line */ if (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Check for required and/or matched information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } /* Parse the type string to create the type info */ T = ParseTypeString (D, &Value); if (T == 0) { goto ErrorExit; } T->Id = Id; /* Remember it */ CollReplaceExpand (&D->Info->TypeInfoById, T, Id); ErrorExit: /* Entry point in case of errors */ SB_Done (&Value); return; } static void ParseVersion (InputData* D) /* Parse a VERSION line */ { enum { ibNone = 0x00, ibMajor = 0x01, ibMinor = 0x02, ibRequired = ibMajor | ibMinor, } InfoBits = ibNone; /* Skip the VERSION token */ NextToken (D); /* More stuff follows */ while (D->Tok != TOK_EOL && D->Tok != TOK_EOF) { switch (D->Tok) { case TOK_MAJOR: NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } if (!IntConstFollows (D)) { goto ErrorExit; } D->Info->MajorVersion = D->IVal; NextToken (D); InfoBits |= ibMajor; break; case TOK_MINOR: NextToken (D); if (!ConsumeEqual (D)) { goto ErrorExit; } if (!IntConstFollows (D)) { goto ErrorExit; } D->Info->MinorVersion = D->IVal; NextToken (D); InfoBits |= ibMinor; break; case TOK_IDENT: /* Try to skip unknown keywords that may have been added by * a later version. */ UnknownKeyword (D); break; default: UnexpectedToken (D); SkipLine (D); goto ErrorExit; } /* Comma follows before next attribute */ if (D->Tok == TOK_COMMA) { NextToken (D); } else if (D->Tok == TOK_EOL || D->Tok == TOK_EOF) { break; } else { UnexpectedToken (D); goto ErrorExit; } } /* Check for required information */ if ((InfoBits & ibRequired) != ibRequired) { ParseError (D, CC65_ERROR, "Required attributes missing"); goto ErrorExit; } ErrorExit: /* Entry point in case of errors */ return; } /*****************************************************************************/ /* Data processing */ /*****************************************************************************/ static int FindCSymInfoByName (const Collection* CSymInfos, const char* Name, unsigned* Index) /* Find the C symbol info with a given file name. The function returns true if * the name was found. In this case, Index contains the index of the first item * that matches. If the item wasn't found, the function returns false and * Index contains the insert position for Name. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (CSymInfos) - 1; int Found = 0; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ const CSymInfo* CurItem = CollAt (CSymInfos, Cur); /* Compare */ int Res = strcmp (CurItem->Name, Name); /* Found? */ if (Res < 0) { Lo = Cur + 1; } else { Hi = Cur - 1; /* Since we may have duplicates, repeat the search until we've * the first item that has a match. */ if (Res == 0) { Found = 1; } } } /* Pass back the index. This is also the insert position */ *Index = Lo; return Found; } static int FindFileInfoByName (const Collection* FileInfos, const char* Name, unsigned* Index) /* Find the FileInfo for a given file name. The function returns true if the * name was found. In this case, Index contains the index of the first item * that matches. If the item wasn't found, the function returns false and * Index contains the insert position for Name. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (FileInfos) - 1; int Found = 0; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ const FileInfo* CurItem = CollAt (FileInfos, Cur); /* Compare */ int Res = strcmp (CurItem->Name, Name); /* Found? */ if (Res < 0) { Lo = Cur + 1; } else { Hi = Cur - 1; /* Since we may have duplicates, repeat the search until we've * the first item that has a match. */ if (Res == 0) { Found = 1; } } } /* Pass back the index. This is also the insert position */ *Index = Lo; return Found; } static SpanInfoListEntry* FindSpanInfoByAddr (const SpanInfoList* L, cc65_addr Addr) /* Find the index of a SpanInfo for a given address. Returns 0 if no such * SpanInfo was found. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) L->Count - 1; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ SpanInfoListEntry* CurItem = &L->List[Cur]; /* Found? */ if (CurItem->Addr > Addr) { Hi = Cur - 1; } else if (CurItem->Addr < Addr) { Lo = Cur + 1; } else { /* Found */ return CurItem; } } /* Not found */ return 0; } static LineInfo* FindLineInfoByLine (const Collection* LineInfos, cc65_line Line) /* Find the LineInfo for a given line number. The function returns the line * info or NULL if none was found. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (LineInfos) - 1; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ LineInfo* CurItem = CollAt (LineInfos, Cur); /* Found? */ if (Line > CurItem->Line) { Lo = Cur + 1; } else if (Line < CurItem->Line) { Hi = Cur - 1; } else { /* Found */ return CurItem; } } /* Not found */ return 0; } static SegInfo* FindSegInfoByName (const Collection* SegInfos, const char* Name) /* Find the SegInfo for a given segment name. The function returns the segment * info or NULL if none was found. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (SegInfos) - 1; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ SegInfo* CurItem = CollAt (SegInfos, Cur); /* Compare */ int Res = strcmp (CurItem->Name, Name); /* Found? */ if (Res < 0) { Lo = Cur + 1; } else if (Res > 0) { Hi = Cur - 1; } else { /* Found */ return CurItem; } } /* Not found */ return 0; } static int FindScopeInfoByName (const Collection* ScopeInfos, const char* Name, unsigned* Index) /* Find the ScopeInfo for a given scope name. The function returns true if the * name was found. In this case, Index contains the index of the first item * that matches. If the item wasn't found, the function returns false and * Index contains the insert position for Name. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (ScopeInfos) - 1; int Found = 0; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ const ScopeInfo* CurItem = CollAt (ScopeInfos, Cur); /* Compare */ int Res = strcmp (CurItem->Name, Name); /* Found? */ if (Res < 0) { Lo = Cur + 1; } else { Hi = Cur - 1; /* Since we may have duplicates, repeat the search until we've * the first item that has a match. */ if (Res == 0) { Found = 1; } } } /* Pass back the index. This is also the insert position */ *Index = Lo; return Found; } static int FindSymInfoByName (const Collection* SymInfos, const char* Name, unsigned* Index) /* Find the SymInfo for a given file name. The function returns true if the * name was found. In this case, Index contains the index of the first item * that matches. If the item wasn't found, the function returns false and * Index contains the insert position for Name. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (SymInfos) - 1; int Found = 0; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ const SymInfo* CurItem = CollAt (SymInfos, Cur); /* Compare */ int Res = strcmp (CurItem->Name, Name); /* Found? */ if (Res < 0) { Lo = Cur + 1; } else { Hi = Cur - 1; /* Since we may have duplicates, repeat the search until we've * the first item that has a match. */ if (Res == 0) { Found = 1; } } } /* Pass back the index. This is also the insert position */ *Index = Lo; return Found; } static int FindSymInfoByValue (const Collection* SymInfos, long Value, unsigned* Index) /* Find the SymInfo for a given value. The function returns true if the * value was found. In this case, Index contains the index of the first item * that matches. If the item wasn't found, the function returns false and * Index contains the insert position for the given value. */ { /* Do a binary search */ int Lo = 0; int Hi = (int) CollCount (SymInfos) - 1; int Found = 0; while (Lo <= Hi) { /* Mid of range */ int Cur = (Lo + Hi) / 2; /* Get item */ SymInfo* CurItem = CollAt (SymInfos, Cur); /* Found? */ if (Value > CurItem->Value) { Lo = Cur + 1; } else { Hi = Cur - 1; /* Since we may have duplicates, repeat the search until we've * the first item that has a match. */ if (Value == CurItem->Value) { Found = 1; } } } /* Pass back the index. This is also the insert position */ *Index = Lo; return Found; } static void ProcessCSymInfo (InputData* D) /* Postprocess c symbol infos */ { unsigned I; /* Walk over all c symbols. Resolve the ids and add the c symbols to the * corresponding asm symbols. */ for (I = 0; I < CollCount (&D->Info->CSymInfoById); ++I) { /* Get this c symbol info */ CSymInfo* S = CollAt (&D->Info->CSymInfoById, I); /* Resolve the asm symbol */ if (S->Sym.Id == CC65_INV_ID) { S->Sym.Info = 0; } else if (S->Sym.Id >= CollCount (&D->Info->SymInfoById)) { ParseError (D, CC65_ERROR, "Invalid symbol id %u for c symbol with id %u", S->Sym.Id, S->Id); S->Sym.Info = 0; } else { S->Sym.Info = CollAt (&D->Info->SymInfoById, S->Sym.Id); /* For normal (=static) symbols, add a backlink to the symbol but * check that there is not more than one. */ if (S->SC != CC65_CSYM_AUTO && S->SC != CC65_CSYM_REG) { if (S->Sym.Info->CSym) { ParseError (D, CC65_ERROR, "Asm symbol id %u has more than one C symbol attached", S->Sym.Info->Id); S->Sym.Info = 0; } else { S->Sym.Info->CSym = S; } } } /* Resolve the type */ if (S->Type.Id >= CollCount (&D->Info->TypeInfoById)) { ParseError (D, CC65_ERROR, "Invalid type id %u for c symbol with id %u", S->Type.Id, S->Id); S->Type.Info = 0; } else { S->Type.Info = CollAt (&D->Info->TypeInfoById, S->Type.Id); } /* Resolve the scope */ if (S->Scope.Id >= CollCount (&D->Info->ScopeInfoById)) { ParseError (D, CC65_ERROR, "Invalid scope id %u for c symbol with id %u", S->Scope.Id, S->Id); S->Scope.Info = 0; } else { S->Scope.Info = CollAt (&D->Info->ScopeInfoById, S->Scope.Id); /* Add the c symbol to the list of all c symbols for this scope */ if (S->Scope.Info->CSymInfoByName == 0) { S->Scope.Info->CSymInfoByName = CollNew (); } CollAppend (S->Scope.Info->CSymInfoByName, S); /* If the scope has an owner symbol, it's a .PROC scope. If this * symbol is identical to the one attached to the C symbol, this * is actuallay a C function and the scope is the matching scope. * Remember the C symbol in the scope in this case. * Beware: Scopes haven't been postprocessed, so we don't have a * pointer but just an id. */ if (S->Sym.Info && S->Scope.Info->Label.Id == S->Sym.Info->Id) { /* This scope is our function scope */ S->Scope.Info->CSymFunc = S; /* Add it to the list of all c functions */ CollAppend (&D->Info->CSymFuncByName, S); } } } /* Walk over all scopes and sort the c symbols by name. */ for (I = 0; I < CollCount (&D->Info->ScopeInfoById); ++I) { /* Get this scope */ ScopeInfo* S = CollAt (&D->Info->ScopeInfoById, I); /* Ignore scopes without C symbols */ if (CollCount (S->CSymInfoByName) > 1) { /* Sort the c symbols for this scope by name */ CollSort (S->CSymInfoByName, CompareCSymInfoByName); } } /* Sort the main list of all C functions by name */ CollSort (&D->Info->CSymFuncByName, CompareCSymInfoByName); } static void ProcessFileInfo (InputData* D) /* Postprocess file infos */ { /* Walk over all file infos and resolve the module ids */ unsigned I; for (I = 0; I < CollCount (&D->Info->FileInfoById); ++I) { /* Get this file info */ FileInfo* F = CollAt (&D->Info->FileInfoById, I); /* Resolve the module ids */ unsigned J; for (J = 0; J < CollCount (&F->ModInfoByName); ++J) { /* Get the id of this module */ unsigned ModId = CollIdAt (&F->ModInfoByName, J); if (ModId >= CollCount (&D->Info->ModInfoById)) { ParseError (D, CC65_ERROR, "Invalid module id %u for file with id %u", ModId, F->Id); CollReplace (&F->ModInfoByName, 0, J); } else { /* Get a pointer to the module */ ModInfo* M = CollAt (&D->Info->ModInfoById, ModId); /* Replace the id by the pointer */ CollReplace (&F->ModInfoByName, M, J); /* Insert a backpointer into the module */ CollAppend (&M->FileInfoByName, F); } } /* If we didn't have any errors, sort the modules by name */ if (D->Errors == 0) { CollSort (&F->ModInfoByName, CompareModInfoByName); } } /* Now walk over all modules and sort the file infos by name */ for (I = 0; I < CollCount (&D->Info->ModInfoById); ++I) { /* Get this module info */ ModInfo* M = CollAt (&D->Info->ModInfoById, I); /* Sort the files by name */ CollSort (&M->FileInfoByName, CompareFileInfoByName); } /* Sort the file infos by name, so we can do a binary search */ CollSort (&D->Info->FileInfoByName, CompareFileInfoByName); } static void ProcessLineInfo (InputData* D) /* Postprocess line infos */ { unsigned I, J; /* Get pointers to the collections */ Collection* LineInfos = &D->Info->LineInfoById; Collection* FileInfos = &D->Info->FileInfoById; /* Walk over the line infos and replace the id numbers of file and segment * with pointers to the actual structs. Add the line info to each file * where it is defined. Resolve the spans and add backpointers to the * spans. */ for (I = 0; I < CollCount (LineInfos); ++I) { /* Get LineInfo struct */ LineInfo* L = CollAt (LineInfos, I); /* Replace the file id by a pointer to the FileInfo. Add a back * pointer */ if (L->File.Id >= CollCount (FileInfos)) { ParseError (D, CC65_ERROR, "Invalid file id %u for line with id %u", L->File.Id, L->Id); L->File.Info = 0; } else { L->File.Info = CollAt (FileInfos, L->File.Id); CollAppend (&L->File.Info->LineInfoByLine, L); } /* Resolve the spans ids */ for (J = 0; J < CollCount (&L->SpanInfoList); ++J) { /* Get the id of this span */ unsigned SpanId = CollIdAt (&L->SpanInfoList, J); if (SpanId >= CollCount (&D->Info->SpanInfoById)) { ParseError (D, CC65_ERROR, "Invalid span id %u for line with id %u", SpanId, L->Id); CollReplace (&L->SpanInfoList, 0, J); } else { /* Get a pointer to the span */ SpanInfo* SP = CollAt (&D->Info->SpanInfoById, SpanId); /* Replace the id by the pointer */ CollReplace (&L->SpanInfoList, SP, J); /* Insert a backpointer into the span */ if (SP->LineInfoList == 0) { SP->LineInfoList = CollNew (); } CollAppend (SP->LineInfoList, L); } } } /* Walk over all files and sort the line infos for each file so we can * do a binary search later. */ for (I = 0; I < CollCount (FileInfos); ++I) { /* Get a pointer to this file info */ FileInfo* F = CollAt (FileInfos, I); /* Sort the line infos for this file */ CollSort (&F->LineInfoByLine, CompareLineInfoByLine); } } static void ProcessModInfo (InputData* D) /* Postprocess module infos */ { unsigned I; /* Walk over all scopes and resolve the ids */ for (I = 0; I < CollCount (&D->Info->ModInfoById); ++I) { /* Get this module info */ ModInfo* M = CollAt (&D->Info->ModInfoById, I); /* Resolve the main file */ if (M->File.Id >= CollCount (&D->Info->FileInfoById)) { ParseError (D, CC65_ERROR, "Invalid file id %u for module with id %u", M->File.Id, M->Id); M->File.Info = 0; } else { M->File.Info = CollAt (&D->Info->FileInfoById, M->File.Id); } /* Resolve the library */ if (M->Lib.Id == CC65_INV_ID) { M->Lib.Info = 0; } else if (M->Lib.Id >= CollCount (&D->Info->LibInfoById)) { ParseError (D, CC65_ERROR, "Invalid library id %u for module with id %u", M->Lib.Id, M->Id); M->Lib.Info = 0; } else { M->Lib.Info = CollAt (&D->Info->LibInfoById, M->Lib.Id); } } /* Sort the collection that contains the module info by name */ CollSort (&D->Info->ModInfoByName, CompareModInfoByName); } static void ProcessScopeInfo (InputData* D) /* Postprocess scope infos */ { unsigned I, J; /* Walk over all scopes. Resolve the ids and add the scopes to the list * of scopes for a module. */ for (I = 0; I < CollCount (&D->Info->ScopeInfoById); ++I) { /* Get this scope info */ ScopeInfo* S = CollAt (&D->Info->ScopeInfoById, I); /* Resolve the module */ if (S->Mod.Id >= CollCount (&D->Info->ModInfoById)) { ParseError (D, CC65_ERROR, "Invalid module id %u for scope with id %u", S->Mod.Id, S->Id); S->Mod.Info = 0; } else { S->Mod.Info = CollAt (&D->Info->ModInfoById, S->Mod.Id); /* Add the scope to the list of scopes for this module */ CollAppend (&S->Mod.Info->ScopeInfoByName, S); /* If this is a main scope, add a pointer to the corresponding * module. */ if (S->Parent.Id == CC65_INV_ID) { /* No parent means main scope */ S->Mod.Info->MainScope = S; } /* If this is the scope that implements a C function, add the * function to the list of all functions in this module. */ if (S->CSymFunc) { CollAppend (&S->Mod.Info->CSymFuncByName, S->CSymFunc); } } /* Resolve the parent scope */ if (S->Parent.Id == CC65_INV_ID) { S->Parent.Info = 0; } else if (S->Parent.Id >= CollCount (&D->Info->ScopeInfoById)) { ParseError (D, CC65_ERROR, "Invalid parent scope id %u for scope with id %u", S->Parent.Id, S->Id); S->Parent.Info = 0; } else { S->Parent.Info = CollAt (&D->Info->ScopeInfoById, S->Parent.Id); /* Set a backpointer in the parent */ if (S->Parent.Info->ChildScopeList == 0) { S->Parent.Info->ChildScopeList = CollNew (); } CollAppend (S->Parent.Info->ChildScopeList, S); } /* Resolve the label */ if (S->Label.Id == CC65_INV_ID) { S->Label.Info = 0; } else if (S->Label.Id >= CollCount (&D->Info->SymInfoById)) { ParseError (D, CC65_ERROR, "Invalid label id %u for scope with id %u", S->Label.Id, S->Id); S->Label.Info = 0; } else { S->Label.Info = CollAt (&D->Info->SymInfoById, S->Label.Id); } /* Resolve the spans ids */ for (J = 0; J < CollCount (&S->SpanInfoList); ++J) { /* Get the id of this span */ unsigned SpanId = CollIdAt (&S->SpanInfoList, J); if (SpanId >= CollCount (&D->Info->SpanInfoById)) { ParseError (D, CC65_ERROR, "Invalid span id %u for scope with id %u", SpanId, S->Id); CollReplace (&S->SpanInfoList, 0, J); } else { /* Get a pointer to the span */ SpanInfo* SP = CollAt (&D->Info->SpanInfoById, SpanId); /* Replace the id by the pointer */ CollReplace (&S->SpanInfoList, SP, J); /* Insert a backpointer into the span */ if (SP->ScopeInfoList == 0) { SP->ScopeInfoList = CollNew (); } CollAppend (SP->ScopeInfoList, S); } } } /* Walk over all modules. If a module doesn't have scopes, it wasn't * compiled with debug info which is ok. If it has debug info, it must * also have a main scope. If there are scopes, sort them by name. Do * also sort C functions in this module by name. */ for (I = 0; I < CollCount (&D->Info->ModInfoById); ++I) { /* Get this module */ ModInfo* M = CollAt (&D->Info->ModInfoById, I); /* Ignore modules without any scopes (no debug info) */ if (CollCount (&M->ScopeInfoByName) == 0) { continue; } /* Must have a main scope */ if (M->MainScope == 0) { ParseError (D, CC65_ERROR, "Module with id %u has no main scope", M->Id); } /* Sort the scopes for this module by name */ CollSort (&M->ScopeInfoByName, CompareScopeInfoByName); /* Sort the C functions in this module by name */ CollSort (&M->CSymFuncByName, CompareCSymInfoByName); } /* Sort the scope infos */ CollSort (&D->Info->ScopeInfoByName, CompareScopeInfoByName); } static void ProcessSegInfo (InputData* D) /* Postprocess segment infos */ { /* Sort the segment infos by name */ CollSort (&D->Info->SegInfoByName, CompareSegInfoByName); } static void ProcessSpanInfo (InputData* D) /* Postprocess span infos */ { unsigned I; /* Temporary collection with span infos sorted by address */ Collection SpanInfoByAddr = COLLECTION_INITIALIZER; /* Resize the temporary collection */ CollGrow (&SpanInfoByAddr, CollCount (&D->Info->SpanInfoById)); /* Walk over all spans and resolve the ids */ for (I = 0; I < CollCount (&D->Info->SpanInfoById); ++I) { /* Get this span info */ SpanInfo* S = CollAt (&D->Info->SpanInfoById, I); /* Resolve the segment and relocate the span */ if (S->Seg.Id >= CollCount (&D->Info->SegInfoById)) { ParseError (D, CC65_ERROR, "Invalid segment id %u for span with id %u", S->Seg.Id, S->Id); S->Seg.Info = 0; } else { S->Seg.Info = CollAt (&D->Info->SegInfoById, S->Seg.Id); S->Start += S->Seg.Info->Start; S->End += S->Seg.Info->Start; } /* Resolve the type if we have it */ if (S->Type.Id == CC65_INV_ID) { S->Type.Info = 0; } else if (S->Type.Id >= CollCount (&D->Info->TypeInfoById)) { ParseError (D, CC65_ERROR, "Invalid type id %u for span with id %u", S->Type.Id, S->Id); S->Type.Info = 0; } else { S->Type.Info = CollAt (&D->Info->TypeInfoById, S->Type.Id); } /* Append this span info to the temporary collection that is later * sorted by address. */ CollAppend (&SpanInfoByAddr, S); } /* Sort the collection with all span infos by address */ CollSort (&SpanInfoByAddr, CompareSpanInfoByAddr); /* Create the span info list from the span info collection */ CreateSpanInfoList (&D->Info->SpanInfoByAddr, &SpanInfoByAddr); /* Remove the temporary collection */ CollDone (&SpanInfoByAddr); } static void ProcessSymInfo (InputData* D) /* Postprocess symbol infos */ { unsigned I, J; /* Walk over the symbols and resolve the references */ for (I = 0; I < CollCount (&D->Info->SymInfoById); ++I) { /* Get the symbol info */ SymInfo* S = CollAt (&D->Info->SymInfoById, I); /* Resolve export */ if (S->Exp.Id == CC65_INV_ID) { S->Exp.Info = 0; } else if (S->Exp.Id >= CollCount (&D->Info->SymInfoById)) { ParseError (D, CC65_ERROR, "Invalid export id %u for symbol with id %u", S->Exp.Id, S->Id); S->Exp.Info = 0; } else { S->Exp.Info = CollAt (&D->Info->SymInfoById, S->Exp.Id); /* Add a backpointer, so the export knows its imports */ if (S->Exp.Info->ImportList == 0) { S->Exp.Info->ImportList = CollNew (); } CollAppend (S->Exp.Info->ImportList, S); } /* Resolve segment */ if (S->Seg.Id == CC65_INV_ID) { S->Seg.Info = 0; } else if (S->Seg.Id >= CollCount (&D->Info->SegInfoById)) { ParseError (D, CC65_ERROR, "Invalid segment id %u for symbol with id %u", S->Seg.Id, S->Id); S->Seg.Info = 0; } else { S->Seg.Info = CollAt (&D->Info->SegInfoById, S->Seg.Id); } /* Resolve the scope */ if (S->Scope.Id == CC65_INV_ID) { S->Scope.Info = 0; } else if (S->Scope.Id >= CollCount (&D->Info->ScopeInfoById)) { ParseError (D, CC65_ERROR, "Invalid scope id %u for symbol with id %u", S->Scope.Id, S->Id); S->Scope.Info = 0; } else { S->Scope.Info = CollAt (&D->Info->ScopeInfoById, S->Scope.Id); /* Place a backpointer to the symbol in the scope */ CollAppend (&S->Scope.Info->SymInfoByName, S); } /* Resolve the parent for cheap locals */ if (S->Parent.Id == CC65_INV_ID) { S->Parent.Info = 0; } else if (S->Parent.Id >= CollCount (&D->Info->SymInfoById)) { ParseError (D, CC65_ERROR, "Invalid parent id %u for symbol with id %u", S->Parent.Id, S->Id); S->Parent.Info = 0; } else { S->Parent.Info = CollAt (&D->Info->SymInfoById, S->Parent.Id); /* Place a backpointer to the cheap local into the parent */ if (S->Parent.Info->CheapLocals == 0) { S->Parent.Info->CheapLocals = CollNew (); } CollAppend (S->Parent.Info->CheapLocals, S); } /* Resolve the line infos for the symbol definition */ for (J = 0; J < CollCount (&S->DefLineInfoList); ++J) { /* Get the id of this line info */ unsigned LineId = CollIdAt (&S->DefLineInfoList, J); if (LineId >= CollCount (&D->Info->LineInfoById)) { ParseError (D, CC65_ERROR, "Invalid line id %u for symbol with id %u", LineId, S->Id); CollReplace (&S->DefLineInfoList, 0, J); } else { /* Get a pointer to the line info */ LineInfo* LI = CollAt (&D->Info->LineInfoById, LineId); /* Replace the id by the pointer */ CollReplace (&S->DefLineInfoList, LI, J); } } /* Resolve the line infos for symbol references */ for (J = 0; J < CollCount (&S->RefLineInfoList); ++J) { /* Get the id of this line info */ unsigned LineId = CollIdAt (&S->RefLineInfoList, J); if (LineId >= CollCount (&D->Info->LineInfoById)) { ParseError (D, CC65_ERROR, "Invalid line id %u for symbol with id %u", LineId, S->Id); CollReplace (&S->RefLineInfoList, 0, J); } else { /* Get a pointer to the line info */ LineInfo* LI = CollAt (&D->Info->LineInfoById, LineId); /* Replace the id by the pointer */ CollReplace (&S->RefLineInfoList, LI, J); } } } /* Second run. Resolve scopes for cheap locals */ for (I = 0; I < CollCount (&D->Info->SymInfoById); ++I) { /* Get the symbol info */ SymInfo* S = CollAt (&D->Info->SymInfoById, I); /* Resolve the scope */ if (S->Scope.Info == 0) { /* No scope - must have a parent */ if (S->Parent.Info == 0) { ParseError (D, CC65_ERROR, "Symbol with id %u has no parent and no scope", S->Id); } else if (S->Parent.Info->Scope.Info == 0) { ParseError (D, CC65_ERROR, "Symbol with id %u has parent %u without a scope", S->Id, S->Parent.Info->Id); } else { S->Scope.Info = S->Parent.Info->Scope.Info; } } } /* Walk over the scopes and sort the symbols in the scope by name */ for (I = 0; I < CollCount (&D->Info->ScopeInfoById); ++I) { /* Get the scope info */ ScopeInfo* S = CollAt (&D->Info->ScopeInfoById, I); /* Sort the symbols in this scope by name */ CollSort (&S->SymInfoByName, CompareSymInfoByName); } /* Sort the symbol infos */ CollSort (&D->Info->SymInfoByName, CompareSymInfoByName); CollSort (&D->Info->SymInfoByVal, CompareSymInfoByVal); } /*****************************************************************************/ /* Debug info files */ /*****************************************************************************/ cc65_dbginfo cc65_read_dbginfo (const char* FileName, cc65_errorfunc ErrFunc) /* Parse the debug info file with the given name. On success, the function * will return a pointer to an opaque cc65_dbginfo structure, that must be * passed to the other functions in this module to retrieve information. * errorfunc is called in case of warnings and errors. If the file cannot be * read successfully, NULL is returned. */ { /* Data structure used to control scanning and parsing */ InputData D = { 0, /* Name of input file */ 1, /* Line number */ 0, /* Input file */ 0, /* Line at start of current token */ 0, /* Column at start of current token */ 0, /* Number of errors */ 0, /* Input file */ ' ', /* Input character */ TOK_INVALID, /* Input token */ 0, /* Integer constant */ STRBUF_INITIALIZER, /* String constant */ 0, /* Function called in case of errors */ 0, /* Pointer to debug info */ }; D.FileName = FileName; D.Error = ErrFunc; /* Open the input file */ D.F = fopen (FileName, "rt"); if (D.F == 0) { /* Cannot open */ ParseError (&D, CC65_ERROR, "Cannot open input file \"%s\": %s", FileName, strerror (errno)); return 0; } /* Create a new debug info struct */ D.Info = NewDbgInfo (FileName); /* Prime the pump */ NextToken (&D); /* The first line in the file must specify version information */ if (D.Tok != TOK_VERSION) { ParseError (&D, CC65_ERROR, "\"version\" keyword missing in first line - this is not " "a valid debug info file"); goto CloseAndExit; } /* Parse the version directive */ ParseVersion (&D); /* Do several checks on the version number */ if (D.Info->MajorVersion < VER_MAJOR) { ParseError ( &D, CC65_ERROR, "This is an old version of the debug info format that is no " "longer supported. Version found = %u.%u, version supported " "= %u.%u", D.Info->MajorVersion, D.Info->MinorVersion, VER_MAJOR, VER_MINOR ); goto CloseAndExit; } else if (D.Info->MajorVersion == VER_MAJOR && D.Info->MinorVersion > VER_MINOR) { ParseError ( &D, CC65_ERROR, "This is a slightly newer version of the debug info format. " "It might work, but you may get errors about unknown keywords " "and similar. Version found = %u.%u, version supported = %u.%u", D.Info->MajorVersion, D.Info->MinorVersion, VER_MAJOR, VER_MINOR ); } else if (D.Info->MajorVersion > VER_MAJOR) { ParseError ( &D, CC65_WARNING, "The format of this debug info file is newer than what we " "know. Will proceed but probably fail. Version found = %u.%u, " "version supported = %u.%u", D.Info->MajorVersion, D.Info->MinorVersion, VER_MAJOR, VER_MINOR ); } ConsumeEOL (&D); /* Parse lines */ while (D.Tok != TOK_EOF) { switch (D.Tok) { case TOK_CSYM: ParseCSym (&D); break; case TOK_FILE: ParseFile (&D); break; case TOK_INFO: ParseInfo (&D); break; case TOK_LIBRARY: ParseLibrary (&D); break; case TOK_LINE: ParseLine (&D); break; case TOK_MODULE: ParseModule (&D); break; case TOK_SCOPE: ParseScope (&D); break; case TOK_SEGMENT: ParseSegment (&D); break; case TOK_SPAN: ParseSpan (&D); break; case TOK_SYM: ParseSym (&D); break; case TOK_TYPE: ParseType (&D); break; case TOK_IDENT: /* Output a warning, then skip the line with the unknown * keyword that may have been added by a later version. */ ParseError (&D, CC65_WARNING, "Unknown keyword \"%s\" - skipping", SB_GetConstBuf (&D.SVal)); SkipLine (&D); break; default: UnexpectedToken (&D); } /* EOL or EOF must follow */ ConsumeEOL (&D); } CloseAndExit: /* Close the file */ fclose (D.F); /* Free memory allocated for SVal */ SB_Done (&D.SVal); /* In case of errors, delete the debug info already allocated and * return NULL */ if (D.Errors > 0) { /* Free allocated stuff */ FreeDbgInfo (D.Info); return 0; } /* We do now have all the information from the input file. Do * postprocessing. Beware: Some of the following postprocessing * depends on the order of the calls. */ ProcessCSymInfo (&D); ProcessFileInfo (&D); ProcessLineInfo (&D); ProcessModInfo (&D); ProcessScopeInfo (&D); ProcessSegInfo (&D); ProcessSpanInfo (&D); ProcessSymInfo (&D); #if DEBUG /* Debug output */ DumpData (&D); #endif /* Return the debug info struct that was created */ return D.Info; } void cc65_free_dbginfo (cc65_dbginfo Handle) /* Free debug information read from a file */ { if (Handle) { FreeDbgInfo ((DbgInfo*) Handle); } } /*****************************************************************************/ /* C symbols */ /*****************************************************************************/ const cc65_csyminfo* cc65_get_csymlist (cc65_dbginfo Handle) /* Return a list of all c symbols */ { const DbgInfo* Info; cc65_csyminfo* S; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ S = new_cc65_csyminfo (CollCount (&Info->CSymInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->CSymInfoById); ++I) { /* Copy the data */ CopyCSymInfo (S->data + I, CollAt (&Info->CSymInfoById, I)); } /* Return the result */ return S; } const cc65_csyminfo* cc65_csym_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a c symbol with a specific id. The function * returns NULL if the id is invalid (no such c symbol) and otherwise a * cc65_csyminfo structure with one entry that contains the requested * symbol information. */ { const DbgInfo* Info; cc65_csyminfo* S; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->CSymInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ S = new_cc65_csyminfo (1); /* Fill in the data */ CopyCSymInfo (S->data, CollAt (&Info->CSymInfoById, Id)); /* Return the result */ return S; } const cc65_csyminfo* cc65_cfunc_bymodule (cc65_dbginfo Handle, unsigned ModId) /* Return the list of C functions (not symbols!) for a specific module. If * the module id is invalid, the function will return NULL, otherwise a * (possibly empty) c symbol list. */ { const DbgInfo* Info; const ModInfo* M; cc65_csyminfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the module id is valid */ if (ModId >= CollCount (&Info->ModInfoById)) { return 0; } /* Get a pointer to the module info */ M = CollAt (&Info->ModInfoById, ModId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_csyminfo (CollCount (&M->CSymFuncByName)); /* Fill in the data */ for (I = 0; I < CollCount (&M->CSymFuncByName); ++I) { CopyCSymInfo (D->data + I, CollAt (&M->CSymFuncByName, I)); } /* Return the result */ return D; } const cc65_csyminfo* cc65_cfunc_byname (cc65_dbginfo Handle, const char* Name) /* Return a list of all C functions with the given name that have a * definition. */ { const DbgInfo* Info; unsigned Index; unsigned Count; const CSymInfo* S; cc65_csyminfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for a function with the given name */ if (!FindCSymInfoByName (&Info->CSymFuncByName, Name, &Index)) { return 0; } /* Count functions with this name */ Count = 1; I = Index; while (1) { if (++I >= CollCount (&Info->CSymFuncByName)) { break; } S = CollAt (&Info->CSymFuncByName, I); if (strcmp (S->Name, Name) != 0) { /* Next symbol has another name */ break; } ++Count; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_csyminfo (Count); /* Fill in the data */ for (I = 0; I < Count; ++I, ++Index) { CopyCSymInfo (D->data + I, CollAt (&Info->CSymFuncByName, Index)); } /* Return the result */ return D; } const cc65_csyminfo* cc65_csym_byscope (cc65_dbginfo Handle, unsigned ScopeId) /* Return all C symbols for a scope. The function will return NULL if the * given id is invalid. */ { const DbgInfo* Info; const ScopeInfo* S; cc65_csyminfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the scope id is valid */ if (ScopeId >= CollCount (&Info->ScopeInfoById)) { return 0; } /* Get a pointer to the scope */ S = CollAt (&Info->ScopeInfoById, ScopeId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_csyminfo (CollCount (S->CSymInfoByName)); /* Fill in the data */ for (I = 0; I < CollCount (S->CSymInfoByName); ++I) { CopyCSymInfo (D->data + I, CollAt (S->CSymInfoByName, I)); } /* Return the result */ return D; } void cc65_free_csyminfo (cc65_dbginfo Handle, const cc65_csyminfo* Info) /* Free a c symbol info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Just free the memory */ xfree ((cc65_csyminfo*) Info); } /*****************************************************************************/ /* Libraries */ /*****************************************************************************/ const cc65_libraryinfo* cc65_get_librarylist (cc65_dbginfo Handle) /* Return a list of all libraries */ { const DbgInfo* Info; cc65_libraryinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ D = new_cc65_libraryinfo (CollCount (&Info->LibInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->LibInfoById); ++I) { /* Copy the data */ CopyLibInfo (D->data + I, CollAt (&Info->LibInfoById, I)); } /* Return the result */ return D; } const cc65_libraryinfo* cc65_library_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a library with a specific id. The function * returns NULL if the id is invalid (no such library) and otherwise a * cc65_libraryinfo structure with one entry that contains the requested * library information. */ { const DbgInfo* Info; cc65_libraryinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->LibInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_libraryinfo (1); /* Fill in the data */ CopyLibInfo (D->data, CollAt (&Info->LibInfoById, Id)); /* Return the result */ return D; } void cc65_free_libraryinfo (cc65_dbginfo Handle, const cc65_libraryinfo* Info) /* Free a library info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Just free the memory */ xfree ((cc65_libraryinfo*) Info); } /*****************************************************************************/ /* Line info */ /*****************************************************************************/ const cc65_lineinfo* cc65_line_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a line with a specific id. The function * returns NULL if the id is invalid (no such line) and otherwise a * cc65_lineinfo structure with one entry that contains the requested * module information. */ { const DbgInfo* Info; cc65_lineinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->LineInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_lineinfo (1); /* Fill in the data */ CopyLineInfo (D->data, CollAt (&Info->LineInfoById, Id)); /* Return the result */ return D; } const cc65_lineinfo* cc65_line_bynumber (cc65_dbginfo Handle, unsigned FileId, cc65_line Line) /* Return line information for a source file/line number combination. The * function returns NULL if no line information was found. */ { const DbgInfo* Info; const FileInfo* F; cc65_lineinfo* D; LineInfo* L = 0; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the source file id is valid */ if (FileId >= CollCount (&Info->FileInfoById)) { return 0; } /* Get the file */ F = CollAt (&Info->FileInfoById, FileId); /* Search in the file for the given line */ L = FindLineInfoByLine (&F->LineInfoByLine, Line); /* Bail out if we didn't find the line */ if (L == 0) { return 0; } /* Prepare the struct we will return to the caller */ D = new_cc65_lineinfo (1); /* Copy the data */ CopyLineInfo (D->data, L); /* Return the allocated struct */ return D; } const cc65_lineinfo* cc65_line_bysource (cc65_dbginfo Handle, unsigned FileId) /* Return line information for a source file. The function returns NULL if the * file id is invalid. */ { const DbgInfo* Info; const FileInfo* F; cc65_lineinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the source file id is valid */ if (FileId >= CollCount (&Info->FileInfoById)) { return 0; } /* Get the file */ F = CollAt (&Info->FileInfoById, FileId); /* Prepare the struct we will return to the caller */ D = new_cc65_lineinfo (CollCount (&F->LineInfoByLine)); /* Fill in the data */ for (I = 0; I < CollCount (&F->LineInfoByLine); ++I) { /* Copy the data */ CopyLineInfo (D->data + I, CollAt (&F->LineInfoByLine, I)); } /* Return the allocated struct */ return D; } const cc65_lineinfo* cc65_line_bysymdef (cc65_dbginfo Handle, unsigned SymId) /* Return line information for the definition of a symbol. The function * returns NULL if the symbol id is invalid, otherwise a list of line infos. */ { const DbgInfo* Info; const SymInfo* S; cc65_lineinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the symbol id is valid */ if (SymId >= CollCount (&Info->SymInfoById)) { return 0; } /* Get the symbol */ S = CollAt (&Info->SymInfoById, SymId); /* Prepare the struct we will return to the caller */ D = new_cc65_lineinfo (CollCount (&S->DefLineInfoList)); /* Fill in the data */ for (I = 0; I < CollCount (&S->DefLineInfoList); ++I) { /* Copy the data */ CopyLineInfo (D->data + I, CollAt (&S->DefLineInfoList, I)); } /* Return the allocated struct */ return D; } const cc65_lineinfo* cc65_line_bysymref (cc65_dbginfo Handle, unsigned SymId) /* Return line information for all references of a symbol. The function * returns NULL if the symbol id is invalid, otherwise a list of line infos. */ { const DbgInfo* Info; const SymInfo* S; cc65_lineinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the symbol id is valid */ if (SymId >= CollCount (&Info->SymInfoById)) { return 0; } /* Get the symbol */ S = CollAt (&Info->SymInfoById, SymId); /* Prepare the struct we will return to the caller */ D = new_cc65_lineinfo (CollCount (&S->RefLineInfoList)); /* Fill in the data */ for (I = 0; I < CollCount (&S->RefLineInfoList); ++I) { /* Copy the data */ CopyLineInfo (D->data + I, CollAt (&S->RefLineInfoList, I)); } /* Return the allocated struct */ return D; } const cc65_lineinfo* cc65_line_byspan (cc65_dbginfo Handle, unsigned SpanId) /* Return line information for a a span. The function returns NULL if the * span id is invalid, otherwise a list of line infos. */ { const DbgInfo* Info; const SpanInfo* S; cc65_lineinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the span id is valid */ if (SpanId >= CollCount (&Info->SpanInfoById)) { return 0; } /* Get the span */ S = CollAt (&Info->SpanInfoById, SpanId); /* Prepare the struct we will return to the caller */ D = new_cc65_lineinfo (CollCount (S->LineInfoList)); /* Fill in the data. Since S->LineInfoList may be NULL, we will use the * count field of the returned data struct instead. */ for (I = 0; I < D->count; ++I) { /* Copy the data */ CopyLineInfo (D->data + I, CollAt (S->LineInfoList, I)); } /* Return the allocated struct */ return D; } void cc65_free_lineinfo (cc65_dbginfo Handle, const cc65_lineinfo* Info) /* Free line info returned by one of the other functions */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Just free the memory */ xfree ((cc65_lineinfo*) Info); } /*****************************************************************************/ /* Modules */ /*****************************************************************************/ const cc65_moduleinfo* cc65_get_modulelist (cc65_dbginfo Handle) /* Return a list of all modules */ { const DbgInfo* Info; cc65_moduleinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ D = new_cc65_moduleinfo (CollCount (&Info->ModInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->ModInfoById); ++I) { /* Copy the data */ CopyModInfo (D->data + I, CollAt (&Info->ModInfoById, I)); } /* Return the result */ return D; } const cc65_moduleinfo* cc65_module_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a module with a specific id. The function * returns NULL if the id is invalid (no such module) and otherwise a * cc65_moduleinfo structure with one entry that contains the requested * module information. */ { const DbgInfo* Info; cc65_moduleinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->ModInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_moduleinfo (1); /* Fill in the data */ CopyModInfo (D->data, CollAt (&Info->ModInfoById, Id)); /* Return the result */ return D; } void cc65_free_moduleinfo (cc65_dbginfo Handle, const cc65_moduleinfo* Info) /* Free a module info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Just free the memory */ xfree ((cc65_moduleinfo*) Info); } /*****************************************************************************/ /* Spans */ /*****************************************************************************/ const cc65_spaninfo* cc65_get_spanlist (cc65_dbginfo Handle) /* Return a list of all spans */ { const DbgInfo* Info; cc65_spaninfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ D = new_cc65_spaninfo (CollCount (&Info->SpanInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->SpanInfoById); ++I) { /* Copy the data */ CopySpanInfo (D->data + I, CollAt (&Info->SpanInfoById, I)); } /* Return the result */ return D; } const cc65_spaninfo* cc65_span_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a span with a specific id. The function * returns NULL if the id is invalid (no such span) and otherwise a * cc65_spaninfo structure with one entry that contains the requested * span information. */ { const DbgInfo* Info; cc65_spaninfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->SpanInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_spaninfo (1); /* Fill in the data */ CopySpanInfo (D->data, CollAt (&Info->SpanInfoById, Id)); /* Return the result */ return D; } const cc65_spaninfo* cc65_span_byaddr (cc65_dbginfo Handle, unsigned long Addr) /* Return span information for the given address. The function returns NULL * if no spans were found for this address. */ { const DbgInfo* Info; SpanInfoListEntry* E; cc65_spaninfo* D = 0; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for spans that cover this address */ E = FindSpanInfoByAddr (&Info->SpanInfoByAddr, Addr); /* Do we have spans? */ if (E != 0) { unsigned I; /* Prepare the struct we will return to the caller */ D = new_cc65_spaninfo (E->Count); if (E->Count == 1) { CopySpanInfo (D->data, E->Data); } else { for (I = 0; I < D->count; ++I) { /* Copy data */ CopySpanInfo (D->data + I, ((SpanInfo**) E->Data)[I]); } } } /* Return the struct we've created */ return D; } const cc65_spaninfo* cc65_span_byline (cc65_dbginfo Handle, unsigned LineId) /* Return span information for the given source line. The function returns NULL * if the line id is invalid, otherwise the spans for this line (possibly zero). */ { const DbgInfo* Info; const LineInfo* L; cc65_spaninfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the line id is valid */ if (LineId >= CollCount (&Info->LineInfoById)) { return 0; } /* Get the line with this id */ L = CollAt (&Info->LineInfoById, LineId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_spaninfo (CollCount (&L->SpanInfoList)); /* Fill in the data */ for (I = 0; I < CollCount (&L->SpanInfoList); ++I) { /* Copy the data */ CopySpanInfo (D->data + I, CollAt (&L->SpanInfoList, I)); } /* Return the result */ return D; } const cc65_spaninfo* cc65_span_byscope (cc65_dbginfo Handle, unsigned ScopeId) /* Return span information for the given scope. The function returns NULL if * the scope id is invalid, otherwise the spans for this scope (possibly zero). */ { const DbgInfo* Info; const ScopeInfo* S; cc65_spaninfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the scope id is valid */ if (ScopeId >= CollCount (&Info->ScopeInfoById)) { return 0; } /* Get the scope with this id */ S = CollAt (&Info->ScopeInfoById, ScopeId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_spaninfo (CollCount (&S->SpanInfoList)); /* Fill in the data */ for (I = 0; I < CollCount (&S->SpanInfoList); ++I) { /* Copy the data */ CopySpanInfo (D->data + I, CollAt (&S->SpanInfoList, I)); } /* Return the result */ return D; } void cc65_free_spaninfo (cc65_dbginfo Handle, const cc65_spaninfo* Info) /* Free a span info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Just free the memory */ xfree ((cc65_spaninfo*) Info); } /*****************************************************************************/ /* Source files */ /*****************************************************************************/ const cc65_sourceinfo* cc65_get_sourcelist (cc65_dbginfo Handle) /* Return a list of all source files */ { const DbgInfo* Info; cc65_sourceinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller. */ D = new_cc65_sourceinfo (CollCount (&Info->FileInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->FileInfoById); ++I) { /* Copy the data */ CopyFileInfo (D->data + I, CollAt (&Info->FileInfoById, I)); } /* Return the result */ return D; } const cc65_sourceinfo* cc65_source_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a source file with a specific id. The function * returns NULL if the id is invalid (no such source file) and otherwise a * cc65_sourceinfo structure with one entry that contains the requested * source file information. */ { const DbgInfo* Info; cc65_sourceinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->FileInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_sourceinfo (1); /* Fill in the data */ CopyFileInfo (D->data, CollAt (&Info->FileInfoById, Id)); /* Return the result */ return D; } const cc65_sourceinfo* cc65_source_bymodule (cc65_dbginfo Handle, unsigned Id) /* Return information about the source files used to build a module. The * function returns NULL if the module id is invalid (no such module) and * otherwise a cc65_sourceinfo structure with one entry per source file. */ { const DbgInfo* Info; const ModInfo* M; cc65_sourceinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the module id is valid */ if (Id >= CollCount (&Info->ModInfoById)) { return 0; } /* Get a pointer to the module info */ M = CollAt (&Info->ModInfoById, Id); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_sourceinfo (CollCount (&M->FileInfoByName)); /* Fill in the data */ for (I = 0; I < CollCount (&M->FileInfoByName); ++I) { CopyFileInfo (D->data + I, CollAt (&M->FileInfoByName, I)); } /* Return the result */ return D; } void cc65_free_sourceinfo (cc65_dbginfo Handle, const cc65_sourceinfo* Info) /* Free a source info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Free the memory */ xfree ((cc65_sourceinfo*) Info); } /*****************************************************************************/ /* Scopes */ /*****************************************************************************/ const cc65_scopeinfo* cc65_get_scopelist (cc65_dbginfo Handle) /* Return a list of all scopes in the debug information */ { const DbgInfo* Info; cc65_scopeinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ D = new_cc65_scopeinfo (CollCount (&Info->ScopeInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->ScopeInfoById); ++I) { /* Copy the data */ CopyScopeInfo (D->data + I, CollAt (&Info->ScopeInfoById, I)); } /* Return the result */ return D; } const cc65_scopeinfo* cc65_scope_byid (cc65_dbginfo Handle, unsigned Id) /* Return the scope with a given id. The function returns NULL if no scope * with this id was found. */ { const DbgInfo* Info; cc65_scopeinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->ScopeInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_scopeinfo (1); /* Fill in the data */ CopyScopeInfo (D->data, CollAt (&Info->ScopeInfoById, Id)); /* Return the result */ return D; } const cc65_scopeinfo* cc65_scope_bymodule (cc65_dbginfo Handle, unsigned ModId) /* Return the list of scopes for one module. The function returns NULL if no * scope with the given id was found. */ { const DbgInfo* Info; const ModInfo* M; cc65_scopeinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the module id is valid */ if (ModId >= CollCount (&Info->ModInfoById)) { return 0; } /* Get a pointer to the module info */ M = CollAt (&Info->ModInfoById, ModId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_scopeinfo (CollCount (&M->ScopeInfoByName)); /* Fill in the data */ for (I = 0; I < CollCount (&M->ScopeInfoByName); ++I) { CopyScopeInfo (D->data + I, CollAt (&M->ScopeInfoByName, I)); } /* Return the result */ return D; } const cc65_scopeinfo* cc65_scope_byname (cc65_dbginfo Handle, const char* Name) /* Return the list of scopes with a given name. Returns NULL if no scope with * the given name was found, otherwise a non empty scope list. */ { const DbgInfo* Info; unsigned Index; const ScopeInfo* S; cc65_scopeinfo* D; unsigned Count; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for the first item with the given name */ if (!FindScopeInfoByName (&Info->ScopeInfoByName, Name, &Index)) { /* Not found */ return 0; } /* Count scopes with this name */ Count = 1; I = Index; while (1) { if (++I >= CollCount (&Info->ScopeInfoByName)) { break; } S = CollAt (&Info->ScopeInfoByName, I); if (strcmp (S->Name, Name) != 0) { /* Next symbol has another name */ break; } ++Count; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_scopeinfo (Count); /* Fill in the data */ for (I = 0; I < Count; ++I, ++Index) { CopyScopeInfo (D->data + I, CollAt (&Info->ScopeInfoByName, Index)); } /* Return the result */ return D; } const cc65_scopeinfo* cc65_scope_byspan (cc65_dbginfo Handle, unsigned SpanId) /* Return scope information for a a span. The function returns NULL if the * span id is invalid, otherwise a list of line scopes. */ { const DbgInfo* Info; const SpanInfo* S; cc65_scopeinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the span id is valid */ if (SpanId >= CollCount (&Info->SpanInfoById)) { return 0; } /* Get the span */ S = CollAt (&Info->SpanInfoById, SpanId); /* Prepare the struct we will return to the caller */ D = new_cc65_scopeinfo (CollCount (S->ScopeInfoList)); /* Fill in the data. Since D->ScopeInfoList may be NULL, we will use the * count field of the returned data struct instead. */ for (I = 0; I < D->count; ++I) { /* Copy the data */ CopyScopeInfo (D->data + I, CollAt (S->ScopeInfoList, I)); } /* Return the allocated struct */ return D; } const cc65_scopeinfo* cc65_childscopes_byid (cc65_dbginfo Handle, unsigned Id) /* Return the direct child scopes of a scope with a given id. The function * returns NULL if no scope with this id was found, otherwise a list of the * direct childs. */ { const DbgInfo* Info; cc65_scopeinfo* D; const ScopeInfo* S; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->ScopeInfoById)) { return 0; } /* Get the scope */ S = CollAt (&Info->ScopeInfoById, Id); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_scopeinfo (CollCount (S->ChildScopeList)); /* Fill in the data */ for (I = 0; I < D->count; ++I) { CopyScopeInfo (D->data + I, CollAt (S->ChildScopeList, I)); } /* Return the result */ return D; } void cc65_free_scopeinfo (cc65_dbginfo Handle, const cc65_scopeinfo* Info) /* Free a scope info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Free the memory */ xfree ((cc65_scopeinfo*) Info); } /*****************************************************************************/ /* Segments */ /*****************************************************************************/ const cc65_segmentinfo* cc65_get_segmentlist (cc65_dbginfo Handle) /* Return a list of all segments referenced in the debug information */ { const DbgInfo* Info; cc65_segmentinfo* D; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Allocate memory for the data structure returned to the caller */ D = new_cc65_segmentinfo (CollCount (&Info->SegInfoById)); /* Fill in the data */ for (I = 0; I < CollCount (&Info->SegInfoById); ++I) { /* Copy the data */ CopySegInfo (D->data + I, CollAt (&Info->SegInfoById, I)); } /* Return the result */ return D; } const cc65_segmentinfo* cc65_segment_byid (cc65_dbginfo Handle, unsigned Id) /* Return information about a segment with a specific id. The function returns * NULL if the id is invalid (no such segment) and otherwise a segmentinfo * structure with one entry that contains the requested segment information. */ { const DbgInfo* Info; cc65_segmentinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->SegInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_segmentinfo (1); /* Fill in the data */ CopySegInfo (D->data, CollAt (&Info->SegInfoById, Id)); /* Return the result */ return D; } const cc65_segmentinfo* cc65_segment_byname (cc65_dbginfo Handle, const char* Name) /* Return information about a segment with a specific name. The function * returns NULL if no segment with this name exists and otherwise a * cc65_segmentinfo structure with one entry that contains the requested * information. */ { const DbgInfo* Info; const SegInfo* S; cc65_segmentinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for the segment */ S = FindSegInfoByName (&Info->SegInfoByName, Name); if (S == 0) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_segmentinfo (1); /* Fill in the data */ CopySegInfo (D->data, S); /* Return the result */ return D; } void cc65_free_segmentinfo (cc65_dbginfo Handle, const cc65_segmentinfo* Info) /* Free a segment info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Free the memory */ xfree ((cc65_segmentinfo*) Info); } /*****************************************************************************/ /* Symbols */ /*****************************************************************************/ const cc65_symbolinfo* cc65_symbol_byid (cc65_dbginfo Handle, unsigned Id) /* Return the symbol with a given id. The function returns NULL if no symbol * with this id was found. */ { const DbgInfo* Info; cc65_symbolinfo* D; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->SymInfoById)) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_symbolinfo (1); /* Fill in the data */ CopySymInfo (D->data, CollAt (&Info->SymInfoById, Id)); /* Return the result */ return D; } const cc65_symbolinfo* cc65_symbol_byname (cc65_dbginfo Handle, const char* Name) /* Return a list of symbols with a given name. The function returns NULL if * no symbol with this name was found. */ { const DbgInfo* Info; cc65_symbolinfo* D; unsigned I; unsigned Index; unsigned Count; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for the symbol */ if (!FindSymInfoByName (&Info->SymInfoByName, Name, &Index)) { /* Not found */ return 0; } /* Index contains the position. Count how many symbols with this name * we have. Skip the first one, since we have at least one. */ Count = 1; while ((unsigned) Index + Count < CollCount (&Info->SymInfoByName)) { const SymInfo* S = CollAt (&Info->SymInfoByName, (unsigned) Index + Count); if (strcmp (S->Name, Name) != 0) { break; } ++Count; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_symbolinfo (Count); /* Fill in the data */ for (I = 0; I < Count; ++I) { /* Copy the data */ CopySymInfo (D->data + I, CollAt (&Info->SymInfoByName, Index++)); } /* Return the result */ return D; } const cc65_symbolinfo* cc65_symbol_byscope (cc65_dbginfo Handle, unsigned ScopeId) /* Return a list of symbols in the given scope. This includes cheap local * symbols, but not symbols in subscopes. The function returns NULL if the * scope id is invalid (no such scope) and otherwise a - possibly empty - * symbol list. */ { const DbgInfo* Info; cc65_symbolinfo* D; const ScopeInfo* S; unsigned I; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (ScopeId >= CollCount (&Info->ScopeInfoById)) { return 0; } /* Get the scope */ S = CollAt (&Info->ScopeInfoById, ScopeId); /* Allocate memory for the data structure returned to the caller */ D = new_cc65_symbolinfo (CollCount (&S->SymInfoByName)); /* Fill in the data */ for (I = 0; I < CollCount (&S->SymInfoByName); ++I) { /* Copy the data */ CopySymInfo (D->data + I, CollAt (&S->SymInfoByName, I)); } /* Return the result */ return D; } const cc65_symbolinfo* cc65_symbol_inrange (cc65_dbginfo Handle, cc65_addr Start, cc65_addr End) /* Return a list of labels in the given range. End is inclusive. The function * return NULL if no symbols within the given range are found. Non label * symbols are ignored and not returned. */ { const DbgInfo* Info; Collection SymInfoList = COLLECTION_INITIALIZER; cc65_symbolinfo* D; unsigned I; unsigned Index; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Search for the symbol. Because we're searching for a range, we cannot * make use of the function result. */ FindSymInfoByValue (&Info->SymInfoByVal, Start, &Index); /* Start from the given index, check all symbols until the end address is * reached. Place all symbols into SymInfoList for later. */ for (I = Index; I < CollCount (&Info->SymInfoByVal); ++I) { /* Get the item */ SymInfo* Item = CollAt (&Info->SymInfoByVal, I); /* The collection is sorted by address, so if we get a value larger * than the end address, we're done. */ if (Item->Value > (long) End) { break; } /* Ignore non-labels (this will also ignore imports) */ if (Item->Type != CC65_SYM_LABEL) { continue; } /* Ok, remember this one */ CollAppend (&SymInfoList, Item); } /* If we don't have any labels within the range, bail out. No memory has * been allocated for SymInfoList. */ if (CollCount (&SymInfoList) == 0) { return 0; } /* Allocate memory for the data structure returned to the caller */ D = new_cc65_symbolinfo (CollCount (&SymInfoList)); /* Fill in the data */ for (I = 0; I < CollCount (&SymInfoList); ++I) { /* Copy the data */ CopySymInfo (D->data + I, CollAt (&SymInfoList, I)); } /* Free the collection */ CollDone (&SymInfoList); /* Return the result */ return D; } void cc65_free_symbolinfo (cc65_dbginfo Handle, const cc65_symbolinfo* Info) /* Free a symbol info record */ { /* Just for completeness, check the handle */ assert (Handle != 0); /* Free the memory */ xfree ((cc65_symbolinfo*) Info); } /*****************************************************************************/ /* Types */ /*****************************************************************************/ const cc65_typedata* cc65_type_byid (cc65_dbginfo Handle, unsigned Id) /* Return the data for the type with the given id. The function returns NULL * if no type with this id was found. */ { const DbgInfo* Info; const TypeInfo* T; /* Check the parameter */ assert (Handle != 0); /* The handle is actually a pointer to a debug info struct */ Info = Handle; /* Check if the id is valid */ if (Id >= CollCount (&Info->TypeInfoById)) { return 0; } /* Get the type info with the given id */ T = CollAt (&Info->TypeInfoById, Id); /* We do already have the type data. Return it. */ return T->Data; } void cc65_free_typedata (cc65_dbginfo Handle, const cc65_typedata* data) /* Free a symbol info record */ { /* Just for completeness, check the handle and the data*/ assert (Handle != 0 && data != 0); /* Nothing to do */ }
882
./cc65/src/common/filestat.c
/*****************************************************************************/ /* */ /* filestat.c */ /* */ /* Replacement for buggy Microsoft code */ /* */ /* */ /* */ /* (C) 2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* This module works around bugs in the time conversion code supplied by * Microsoft. See here for a description of the problem: * http://www.codeproject.com/KB/datetime/dstbugs.aspx * Please let me note that I find it absolutely unacceptable to just declare * buggy behaviour like this "works as designed" as Microsoft does. The * problems did even make it into .NET, where the DateTime builtin data type * has exactly the same problems as described in the article above. */ #include <sys/types.h> #include <sys/stat.h> #if defined(__WATCOMC__) && defined(__NT__) #define BUGGY_OS 1 #include <errno.h> #include <windows.h> #endif /* common */ #include "filestat.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ #if defined(BUGGY_OS) static time_t FileTimeToUnixTime (const FILETIME* T) /* Calculate a unix time_t value from a FILETIME. FILETIME contains a 64 bit * value with point zero at 1600-01-01 00:00:00 and counting 100ns intervals. * time_t is in seconds since 1970-01-01 00:00:00. */ { /* Offset between 1600-01-01 and the Epoch in seconds. Watcom C has no * way to express a number > 32 bit (known to me) but is able to do * calculations with 64 bit integers, so we need to do it this way. */ static const ULARGE_INTEGER Offs = { 0xB6109100UL, 0x00000020UL }; ULARGE_INTEGER V; V.LowPart = T->dwLowDateTime; V.HighPart = T->dwHighDateTime; return (V.QuadPart / 10000000U) - Offs.QuadPart; } int FileStat (const char* Path, struct stat* Buf) /* Replacement function for stat() */ { HANDLE H; BY_HANDLE_FILE_INFORMATION Info; /* First call stat() */ int Error = stat (Path, Buf); if (Error != 0) { return Error; } /* Open the file using backup semantics, so we won't change atime. Then * retrieve the correct times in UTC and replace the ones in Buf. Return * EACCES in case of errors to avoid the hassle of translating windows * error codes to standard ones. */ H = CreateFile (Path, GENERIC_READ, FILE_SHARE_READ, 0, /* Security attributes */ OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); /* Template file */ if (H != INVALID_HANDLE_VALUE) { if (GetFileInformationByHandle (H, &Info)) { Buf->st_ctime = FileTimeToUnixTime (&Info.ftCreationTime); Buf->st_atime = FileTimeToUnixTime (&Info.ftLastAccessTime); Buf->st_mtime = FileTimeToUnixTime (&Info.ftLastWriteTime); } else { Error = EACCES; } (void) CloseHandle (H); } else { Error = EACCES; } /* Done */ return Error; } #else int FileStat (const char* Path, struct stat* Buf) /* Replacement function for stat() */ { /* Just call the function which works without errors */ return stat (Path, Buf); } #endif
883
./cc65/src/common/hashtab.c
/*****************************************************************************/ /* */ /* hashtab.c */ /* */ /* Generic hash table */ /* */ /* */ /* */ /* (C) 2003-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* common */ #include "check.h" #include "hashtab.h" #include "xmalloc.h" /*****************************************************************************/ /* struct HashTable */ /*****************************************************************************/ HashTable* InitHashTable (HashTable* T, unsigned Slots, const HashFunctions* Func) /* Initialize a hash table and return it */ { /* Initialize the fields */ T->Slots = Slots; T->Count = 0; T->Table = 0; T->Func = Func; /* Return the initialized table */ return T; } void DoneHashTable (HashTable* T) /* Destroy the contents of a hash table. Note: This will not free the entries * in the table! */ { /* Just free the array with the table pointers */ xfree (T->Table); } void FreeHashTable (HashTable* T) /* Free a hash table. Note: This will not free the entries in the table! */ { if (T) { /* Free the contents */ DoneHashTable (T); /* Free the table structure itself */ xfree (T); } } static void HT_Alloc (HashTable* T) /* Allocate table memory */ { unsigned I; /* Allocate memory */ T->Table = xmalloc (T->Slots * sizeof (T->Table[0])); /* Initialize the table */ for (I = 0; I < T->Slots; ++I) { T->Table[I] = 0; } } HashNode* HT_FindHash (const HashTable* T, const void* Key, unsigned Hash) /* Find the node with the given key. Differs from HT_Find in that the hash * for the key is precalculated and passed to the function. */ { HashNode* N; /* If we don't have a table, there's nothing to find */ if (T->Table == 0) { return 0; } /* Search for the entry in the given chain */ N = T->Table[Hash % T->Slots]; while (N) { /* First compare the full hash, to avoid calling the compare function * if it is not really necessary. */ if (N->Hash == Hash && T->Func->Compare (Key, T->Func->GetKey (N)) == 0) { /* Found */ break; } /* Not found, next entry */ N = N->Next; } /* Return what we found */ return N; } void* HT_Find (const HashTable* T, const void* Key) /* Find the entry with the given key and return it */ { /* Search for the entry */ return HT_FindHash (T, Key, T->Func->GenHash (Key)); } void HT_Insert (HashTable* T, void* Entry) /* Insert an entry into the given hash table */ { HashNode* N; unsigned RHash; /* If we don't have a table, we need to allocate it now */ if (T->Table == 0) { HT_Alloc (T); } /* The first member of Entry is also the hash node */ N = Entry; /* Generate the hash over the node key. */ N->Hash = T->Func->GenHash (T->Func->GetKey (N)); /* Calculate the reduced hash */ RHash = N->Hash % T->Slots; /* Insert the entry into the correct chain */ N->Next = T->Table[RHash]; T->Table[RHash] = N; /* One more entry */ ++T->Count; } void HT_Remove (HashTable* T, void* Entry) /* Remove an entry from the given hash table */ { /* The first member of Entry is also the hash node */ HashNode* N = Entry; /* Calculate the reduced hash, which is also the slot number */ unsigned Slot = N->Hash % T->Slots; /* Remove the entry from the single linked list */ HashNode** Q = &T->Table[Slot]; while (1) { /* If the pointer is NULL, the node is not in the table which we will * consider a serious error. */ CHECK (*Q != 0); if (*Q == N) { /* Found - remove it */ *Q = N->Next; --T->Count; break; } /* Next node */ Q = &(*Q)->Next; } } void HT_Walk (HashTable* T, int (*F) (void* Entry, void* Data), void* Data) /* Walk over all nodes of a hash table, optionally deleting entries from the * table. For each node, the user supplied function F is called, passing a * pointer to the entry, and the data pointer passed to HT_Walk by the caller. * If F returns true, the node is deleted from the hash table otherwise it's * left in place. While deleting the node, the node is not accessed, so it is * safe for F to free the memory associcated with the entry. */ { unsigned I; /* If we don't have a table there are no entries to walk over */ if (T->Table == 0) { return; } /* Walk over all chains */ for (I = 0; I < T->Slots; ++I) { /* Get the pointer to the first entry of the hash chain */ HashNode** Cur = &T->Table[I]; /* Walk over all entries in this chain */ while (*Cur) { /* Fetch the next node in chain now, because F() may delete it */ HashNode* Next = (*Cur)->Next; /* Call the user function. N is also the pointer to the entry. If * the function returns true, the entry is to be deleted. */ if (F (*Cur, Data)) { /* Delete the node from the chain */ *Cur = Next; --T->Count; } else { /* Next node in chain */ Cur = &(*Cur)->Next; } } } }
884
./cc65/src/common/check.c
/*****************************************************************************/ /* */ /* check.c */ /* */ /* Assert like macros */ /* */ /* */ /* */ /* (C) 1998-2001 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include "abend.h" #include "check.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Predefined messages */ const char* MsgInternalError = "Internal error: "; const char* MsgPrecondition = "Precondition violated: "; const char* MsgCheckFailed = "Check failed: "; const char* MsgProgramAborted = "Program aborted: "; static void DefaultCheckFailed (const char* msg, const char* cond, const char* file, unsigned line) attribute ((noreturn)); void (*CheckFailed) (const char* Msg, const char* Cond, const char* File, unsigned Line) attribute ((noreturn)) = DefaultCheckFailed; /* Function pointer that is called from check if the condition code is true. */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void DefaultCheckFailed (const char* Msg, const char* Cond, const char* File, unsigned Line) { /* Output a diagnostic and abort */ AbEnd ("%s%s, file `%s', line %u", Msg, Cond, File, Line); }
885
./cc65/src/common/exprdefs.c
/*****************************************************************************/ /* */ /* exprdefs.c */ /* */ /* Expression tree definitions */ /* */ /* */ /* */ /* (C) 1998-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include "abend.h" #include "exprdefs.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static void InternalDumpExpr (const ExprNode* Expr, const ExprNode* (*ResolveSym) (const struct SymEntry*)) /* Dump an expression in RPN to stdout */ { if (Expr == 0) { return; } InternalDumpExpr (Expr->Left, ResolveSym); InternalDumpExpr (Expr->Right, ResolveSym); switch (Expr->Op) { case EXPR_LITERAL: case EXPR_ULABEL: printf (" $%04lX", Expr->V.IVal); break; case EXPR_SYMBOL: printf (" SYM("); if (ResolveSym && (Expr = ResolveSym (Expr->V.Sym)) != 0) { InternalDumpExpr (Expr, ResolveSym); } printf (") "); break; case EXPR_SECTION: printf (" SEC"); break; case EXPR_SEGMENT: printf (" SEG"); break; case EXPR_MEMAREA: printf (" MEM"); break; case EXPR_PLUS: printf (" +"); break; case EXPR_MINUS: printf (" -"); break; case EXPR_MUL: printf (" *"); break; case EXPR_DIV: printf (" /"); break; case EXPR_MOD: printf (" MOD"); break; case EXPR_OR: printf (" OR"); break; case EXPR_XOR: printf (" XOR"); break; case EXPR_AND: printf (" AND"); break; case EXPR_SHL: printf (" SHL"); break; case EXPR_SHR: printf (" SHR"); break; case EXPR_EQ: printf (" ="); break; case EXPR_NE: printf ("<>"); break; case EXPR_LT: printf (" <"); break; case EXPR_GT: printf (" >"); break; case EXPR_LE: printf (" <="); break; case EXPR_GE: printf (" >="); break; case EXPR_BOOLAND: printf (" BOOL_AND"); break; case EXPR_BOOLOR: printf (" BOOL_OR"); break; case EXPR_BOOLXOR: printf (" BOOL_XOR"); break; case EXPR_MAX: printf (" MAX"); break; case EXPR_MIN: printf (" MIN"); break; case EXPR_UNARY_MINUS: printf (" NEG"); break; case EXPR_NOT: printf (" ~"); break; case EXPR_SWAP: printf (" SWAP"); break; case EXPR_BOOLNOT: printf (" BOOL_NOT"); break; case EXPR_BANK: printf (" BANK"); break; case EXPR_BYTE0: printf (" BYTE0"); break; case EXPR_BYTE1: printf (" BYTE1"); break; case EXPR_BYTE2: printf (" BYTE2"); break; case EXPR_BYTE3: printf (" BYTE3"); break; case EXPR_WORD0: printf (" WORD0"); break; case EXPR_WORD1: printf (" WORD1"); break; case EXPR_FARADDR: printf (" FARADDR"); break; case EXPR_DWORD: printf (" DWORD"); break; default: AbEnd ("Unknown Op type: %u", Expr->Op); } } void DumpExpr (const ExprNode* Expr, const ExprNode* (*ResolveSym) (const struct SymEntry*)) /* Dump an expression tree to stdout */ { InternalDumpExpr (Expr, ResolveSym); printf ("\n"); }
886
./cc65/src/common/xmalloc.c
/*****************************************************************************/ /* */ /* xmalloc.c */ /* */ /* Memory allocation subroutines */ /* */ /* */ /* */ /* (C) 2000-2006 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "abend.h" #include "debugflag.h" #include "xmalloc.h" /*****************************************************************************/ /* code */ /*****************************************************************************/ void* xmalloc (size_t Size) /* Allocate memory, check for out of memory condition. Do some debugging */ { void* P = 0; /* Allow zero sized requests and return NULL in this case */ if (Size) { /* Allocate memory */ P = malloc (Size); /* Check for errors */ if (P == 0) { AbEnd ("Out of memory - requested block size = %lu", (unsigned long) Size); } } /* Return a pointer to the block */ return P; } void* xrealloc (void* P, size_t Size) /* Reallocate a memory block, check for out of memory */ { /* Reallocate the block */ void* N = realloc (P, Size); /* Check for errors */ if (N == 0 && Size != 0) { AbEnd ("Out of memory in realloc - requested block size = %lu", (unsigned long) Size); } /* Return the pointer to the new block */ return N; } void xfree (void* Block) /* Free the block, do some debugging */ { free (Block); } char* xstrdup (const char* S) /* Duplicate a string on the heap. The function checks for out of memory */ { /* Allow dup'ing of NULL strings */ if (S) { /* Get the length of the string */ unsigned Len = strlen (S) + 1; /* Allocate memory and return a copy */ return memcpy (xmalloc (Len), S, Len); } else { /* Return a NULL pointer */ return 0; } } void* xdup (const void* Buf, size_t Size) /* Create a copy of Buf on the heap and return a pointer to it. */ { return memcpy (xmalloc (Size), Buf, Size); }
887
./cc65/src/common/version.c
/*****************************************************************************/ /* */ /* version.c */ /* */ /* Version information for the cc65 compiler package */ /* */ /* */ /* */ /* (C) 1998-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "version.h" #include "xsprintf.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ #define VER_MAJOR 2U #define VER_MINOR 14U #define VER_PATCH 0U #define VER_RC 0U /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* GetVersionAsString (void) /* Returns the version number as a string in a static buffer */ { static char Buf[20]; #if defined(VER_RC) && (VER_RC > 0U) xsnprintf (Buf, sizeof (Buf), "%u.%u.%u-rc%u", VER_MAJOR, VER_MINOR, VER_PATCH, VER_RC); #else xsnprintf (Buf, sizeof (Buf), "%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH); #endif return Buf; } unsigned GetVersionAsNumber (void) /* Returns the version number as a combined unsigned for use in a #define */ { return ((VER_MAJOR * 0x100) + (VER_MINOR * 0x10) + VER_PATCH); }
888
./cc65/src/common/fname.c
/*****************************************************************************/ /* */ /* fname.c */ /* */ /* File name handling utilities */ /* */ /* */ /* */ /* (C) 2000-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include "xmalloc.h" #include "fname.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ const char* FindExt (const char* Name) /* Return a pointer to the file extension in Name or NULL if there is none */ { const char* S; /* Get the length of the name */ unsigned Len = strlen (Name); if (Len < 2) { return 0; } /* Get a pointer to the last character */ S = Name + Len - 1; /* Search for the dot, beware of subdirectories */ while (S >= Name && *S != '.' && *S != '\\' && *S != '/') { --S; } /* Did we find an extension? */ if (*S == '.') { return S; } else { return 0; } } const char* FindName (const char* Path) /* Return a pointer to the file name in Path. If there is no path leading to * the file, the function returns Path as name. */ { /* Get the length of the name */ int Len = strlen (Path); /* Search for the path separator */ while (Len > 0 && Path[Len-1] != '\\' && Path[Len-1] != '/') { --Len; } /* Return the name or path */ return Path + Len; } char* MakeFilename (const char* Origin, const char* Ext) /* Make a new file name from Origin and Ext. If Origin has an extension, it * is removed and Ext is appended. If Origin has no extension, Ext is simply * appended. The result is placed in a malloc'ed buffer and returned. * The function may be used to create "foo.o" from "foo.s". */ { char* Out; const char* P = FindExt (Origin); if (P == 0) { /* No dot, add the extension */ Out = xmalloc (strlen (Origin) + strlen (Ext) + 1); strcpy (Out, Origin); strcat (Out, Ext); } else { Out = xmalloc (P - Origin + strlen (Ext) + 1); memcpy (Out, Origin, P - Origin); strcpy (Out + (P - Origin), Ext); } return Out; }
889
./cc65/src/common/strutil.c
/*****************************************************************************/ /* */ /* strutil.h */ /* */ /* String utility functions */ /* */ /* */ /* */ /* (C) 2001-2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <ctype.h> /* common */ #include "strutil.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ char* StrCopy (char* Dest, size_t DestSize, const char* Source) /* Copy Source to Dest honouring the maximum size of the target buffer. In * constrast to strncpy, the resulting string will always be NUL terminated. * The function returns the pointer to the destintation buffer. */ { size_t Len = strlen (Source); if (Len >= DestSize) { memcpy (Dest, Source, DestSize-1); Dest[DestSize-1] = '\0'; } else { memcpy (Dest, Source, Len+1); } return Dest; } int StrCaseCmp (const char* S1, const char* S2) /* Compare two strings ignoring case */ { int Diff; while ((Diff = toupper (*S1) - toupper (*S2)) == 0 && *S1) { ++S1; ++S2; } return Diff; }
890
./cc65/src/common/target.c
/*****************************************************************************/ /* */ /* target.c */ /* */ /* Target specification */ /* */ /* */ /* */ /* (C) 2000-2011, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> /* common */ #include "chartype.h" #include "check.h" #include "target.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* Translation table with direct (no) translation */ static unsigned char CTNone[256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; /* Translation table ISO-8859-1 -> ATASCII */ static const unsigned char CTAtari [256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0xFD,0x08,0x7F,0x9B,0x0B,0x7D,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; /* Translation table ISO-8859-1 -> PETSCII */ static const unsigned char CTPET [256] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x14,0x09,0x0D,0x11,0x93,0x0A,0x0E,0x0F, 0x10,0x0B,0x12,0x13,0x08,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0x5B,0xBF,0x5D,0x5E,0xA4, 0xAD,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0xB3,0xDD,0xAB,0xB1,0xDF, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x0C,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; /* One entry in the target map */ typedef struct TargetEntry TargetEntry; struct TargetEntry { char Name[12]; /* Target name */ target_t Id; /* Target id */ }; /* Table that maps target names to ids. Sorted alphabetically for bsearch. * Allows mupltiple entries for one target id (target name aliases). */ static const TargetEntry TargetMap[] = { { "apple2", TGT_APPLE2 }, { "apple2enh", TGT_APPLE2ENH }, { "atari", TGT_ATARI }, { "atarixl", TGT_ATARIXL }, { "atmos", TGT_ATMOS }, { "bbc", TGT_BBC }, { "c128", TGT_C128 }, { "c16", TGT_C16 }, { "c64", TGT_C64 }, { "cbm510", TGT_CBM510 }, { "cbm610", TGT_CBM610 }, { "geos", TGT_GEOS_CBM }, { "geos-apple", TGT_GEOS_APPLE }, { "geos-cbm", TGT_GEOS_CBM }, { "lunix", TGT_LUNIX }, { "lynx", TGT_LYNX }, { "module", TGT_MODULE }, { "nes", TGT_NES }, { "none", TGT_NONE }, { "pet", TGT_PET }, { "plus4", TGT_PLUS4 }, { "sim6502", TGT_SIM6502 }, { "sim65c02", TGT_SIM65C02 }, { "supervision", TGT_SUPERVISION }, { "vc20", TGT_VIC20 }, { "vic20", TGT_VIC20 }, }; #define MAP_ENTRY_COUNT (sizeof (TargetMap) / sizeof (TargetMap[0])) /* Table with target properties by target id */ static const TargetProperties PropertyTable[TGT_COUNT] = { { "none", CPU_6502, BINFMT_BINARY, CTNone }, { "module", CPU_6502, BINFMT_O65, CTNone }, { "atari", CPU_6502, BINFMT_BINARY, CTAtari }, { "atarixl", CPU_6502, BINFMT_BINARY, CTAtari }, { "vic20", CPU_6502, BINFMT_BINARY, CTPET }, { "c16", CPU_6502, BINFMT_BINARY, CTPET }, { "c64", CPU_6502, BINFMT_BINARY, CTPET }, { "c128", CPU_6502, BINFMT_BINARY, CTPET }, { "plus4", CPU_6502, BINFMT_BINARY, CTPET }, { "cbm510", CPU_6502, BINFMT_BINARY, CTPET }, { "cbm610", CPU_6502, BINFMT_BINARY, CTPET }, { "pet", CPU_6502, BINFMT_BINARY, CTPET }, { "bbc", CPU_6502, BINFMT_BINARY, CTNone }, { "apple2", CPU_6502, BINFMT_BINARY, CTNone }, { "apple2enh", CPU_65C02, BINFMT_BINARY, CTNone }, { "geos-cbm", CPU_6502, BINFMT_BINARY, CTNone }, { "geos-apple", CPU_65C02, BINFMT_BINARY, CTNone }, { "lunix", CPU_6502, BINFMT_O65, CTNone }, { "atmos", CPU_6502, BINFMT_BINARY, CTNone }, { "nes", CPU_6502, BINFMT_BINARY, CTNone }, { "supervision", CPU_65SC02, BINFMT_BINARY, CTNone }, { "lynx", CPU_65C02, BINFMT_BINARY, CTNone }, { "sim6502", CPU_6502, BINFMT_BINARY, CTNone }, { "sim65c02", CPU_65C02, BINFMT_BINARY, CTNone }, }; /* Target system */ target_t Target = TGT_NONE; /*****************************************************************************/ /* Code */ /*****************************************************************************/ static int Compare (const void* Key, const void* Entry) /* Compare function for bsearch */ { return strcmp ((const char*) Key, ((const TargetEntry*)Entry)->Name); } target_t FindTarget (const char* Name) /* Find a target by name and return the target id. TGT_UNKNOWN is returned if * the given name is no valid target. */ { /* Search for the name in the map */ const TargetEntry* T; T = bsearch (Name, TargetMap, MAP_ENTRY_COUNT, sizeof (TargetMap[0]), Compare); /* Return the target id */ return (T == 0)? TGT_UNKNOWN : T->Id; } const TargetProperties* GetTargetProperties (target_t Target) /* Return the properties for a target */ { /* Must have a valid target id */ PRECONDITION (Target >= 0 && Target < TGT_COUNT); /* Return the array entry */ return &PropertyTable[Target]; } const char* GetTargetName (target_t Target) /* Return the name of a target */ { /* Return the array entry */ return GetTargetProperties (Target)->Name; }
891
./cc65/src/common/fp.c
/*****************************************************************************/ /* */ /* fp.c */ /* */ /* Floating point support */ /* */ /* */ /* */ /* (C) 2008 Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* The compiler must use the same floating point arithmetic as the target * platform, otherwise expressions will yield a different result when * evaluated in the compiler or on the target platform. Since writing a target * and source library is almost double the work, we will at least add the * hooks here, and define functions for a plug in library that may be added * at a later time. Currently we use the builtin data types of the compiler * that translates cc65. */ #include <string.h> /* common */ #include "fp.h" #include "xmalloc.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ #define F_SIZE sizeof(float) #define D_SIZE sizeof(float) /* NOT double! */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ size_t FP_F_Size (void) /* Return the size of the data type float */ { return F_SIZE; } unsigned char* FP_F_Data (Float Val) /* Return the raw data of a float in a malloc'ed buffer. Free after use. */ { return memcpy (xmalloc (F_SIZE), &Val.V, F_SIZE); } Float FP_F_Make (float Val) /* Make a floating point variable from a float value */ { Float D; D.V = Val; return D; } Float FP_F_FromInt (long Val) /* Convert an integer into a floating point variable */ { Float D; D.V = (float) Val; return D; } float FP_F_ToFloat (Float Val) /* Convert a Float into a native float */ { return Val.V; } Float FP_F_Add (Float Left, Float Right) /* Add two floats */ { Float D; D.V = Left.V + Right.V; return D; } Float FP_F_Sub (Float Left, Float Right) /* Subtract two floats */ { Float D; D.V = Left.V - Right.V; return D; } Float FP_F_Mul (Float Left, Float Right) /* Multiplicate two floats */ { Float D; D.V = Left.V * Right.V; return D; } Float FP_F_Div (Float Left, Float Right) /* Divide two floats */ { Float D; D.V = Left.V / Right.V; return D; } size_t FP_D_Size (void) /* Return the size of the data type double */ { return D_SIZE; } unsigned char* FP_D_Data (Double Val) /* Return the raw data of a double in a malloc'ed buffer. Free after use. */ { float F = (float) Val.V; return memcpy (xmalloc (F_SIZE), &F, F_SIZE); } Double FP_D_Make (double Val) /* Make a floating point variable from a float value */ { Double D; D.V = Val; return D; } Double FP_D_FromInt (long Val) /* Convert an integer into a floating point variable */ { Double D; D.V = Val; return D; } double FP_D_ToFloat (Double Val) /* Convert a Double into a native double */ { return Val.V; } Double FP_D_Add (Double Left, Double Right) /* Add two floats */ { Double D; D.V = Left.V + Right.V; return D; } Double FP_D_Sub (Double Left, Double Right) /* Subtract two floats */ { Double D; D.V = Left.V - Right.V; return D; } Double FP_D_Mul (Double Left, Double Right) /* Multiplicate two floats */ { Double D; D.V = Left.V * Right.V; return D; } Double FP_D_Div (Double Left, Double Right) /* Divide two floats */ { Double D; D.V = Left.V / Right.V; return D; }
892
./cc65/src/common/strbuf.c
/*****************************************************************************/ /* */ /* strbuf.c */ /* */ /* Variable sized string buffers */ /* */ /* */ /* */ /* (C) 2001-2012, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> #include <ctype.h> /* common */ #include "chartype.h" #include "strbuf.h" #include "va_copy.h" #include "xmalloc.h" #include "xsprintf.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ /* An empty string buf */ const StrBuf EmptyStrBuf = STATIC_STRBUF_INITIALIZER; /*****************************************************************************/ /* Code */ /*****************************************************************************/ #if !defined(HAVE_INLINE) StrBuf* SB_Init (StrBuf* B) /* Initialize a string buffer */ { *B = EmptyStrBuf; return B; } #endif StrBuf* SB_InitFromString (StrBuf* B, const char* S) /* Initialize a string buffer from a literal string. Beware: The buffer won't * store a copy but a pointer to the actual string. */ { B->Allocated = 0; B->Len = strlen (S); B->Index = 0; B->Buf = (char*) S; return B; } void SB_Done (StrBuf* B) /* Free the data of a string buffer (but not the struct itself) */ { if (B->Allocated) { xfree (B->Buf); } } StrBuf* NewStrBuf (void) /* Allocate, initialize and return a new StrBuf */ { /* Allocate a new string buffer */ StrBuf* B = xmalloc (sizeof (StrBuf)); /* Initialize the struct... */ SB_Init (B); /* ...and return it */ return B; } void FreeStrBuf (StrBuf* B) /* Free a string buffer */ { /* Allow NULL pointers */ if (B) { SB_Done (B); xfree (B); } } void SB_Realloc (StrBuf* B, unsigned NewSize) /* Reallocate the string buffer space, make sure at least NewSize bytes are * available. */ { /* Get the current size, use a minimum of 8 bytes */ unsigned NewAllocated = B->Allocated; if (NewAllocated == 0) { NewAllocated = 8; } /* Round up to the next power of two */ while (NewAllocated < NewSize) { NewAllocated *= 2; } /* Reallocate the buffer. Beware: The allocated size may be zero while the * length is not. This means that we have a buffer that wasn't allocated * on the heap. */ if (B->Allocated) { /* Just reallocate the block */ B->Buf = xrealloc (B->Buf, NewAllocated); } else { /* Allocate a new block and copy */ B->Buf = memcpy (xmalloc (NewAllocated), B->Buf, B->Len); } /* Remember the new block size */ B->Allocated = NewAllocated; } static void SB_CheapRealloc (StrBuf* B, unsigned NewSize) /* Reallocate the string buffer space, make sure at least NewSize bytes are * available. This function won't copy the old buffer contents over to the new * buffer and may be used if the old contents are overwritten later. */ { /* Get the current size, use a minimum of 8 bytes */ unsigned NewAllocated = B->Allocated; if (NewAllocated == 0) { NewAllocated = 8; } /* Round up to the next power of two */ while (NewAllocated < NewSize) { NewAllocated *= 2; } /* Free the old buffer if there is one */ if (B->Allocated) { xfree (B->Buf); } /* Allocate a fresh block */ B->Buf = xmalloc (NewAllocated); /* Remember the new block size */ B->Allocated = NewAllocated; } #if !defined(HAVE_INLINE) char SB_At (const StrBuf* B, unsigned Index) /* Get a character from the buffer */ { PRECONDITION (Index < B->Len); return B->Buf[Index]; } #endif void SB_Drop (StrBuf* B, unsigned Count) /* Drop characters from the end of the string. */ { PRECONDITION (Count <= B->Len); B->Len -= Count; if (B->Index > B->Len) { B->Index = B->Len; } } void SB_Terminate (StrBuf* B) /* Zero terminate the given string buffer. NOTE: The terminating zero is not * accounted for in B->Len, if you want that, you have to use AppendChar! */ { unsigned NewLen = B->Len + 1; if (NewLen > B->Allocated) { SB_Realloc (B, NewLen); } B->Buf[B->Len] = '\0'; } void SB_CopyBuf (StrBuf* Target, const char* Buf, unsigned Size) /* Copy Buf to Target, discarding the old contents of Target */ { if (Size) { if (Target->Allocated < Size) { SB_CheapRealloc (Target, Size); } memcpy (Target->Buf, Buf, Size); } Target->Len = Size; } #if !defined(HAVE_INLINE) void SB_CopyStr (StrBuf* Target, const char* S) /* Copy S to Target, discarding the old contents of Target */ { SB_CopyBuf (Target, S, strlen (S)); } #endif #if !defined(HAVE_INLINE) void SB_Copy (StrBuf* Target, const StrBuf* Source) /* Copy Source to Target, discarding the old contents of Target */ { SB_CopyBuf (Target, Source->Buf, Source->Len); Target->Index = Source->Index; } #endif void SB_AppendChar (StrBuf* B, int C) /* Append a character to a string buffer */ { unsigned NewLen = B->Len + 1; if (NewLen > B->Allocated) { SB_Realloc (B, NewLen); } B->Buf[B->Len] = (char) C; B->Len = NewLen; } void SB_AppendBuf (StrBuf* B, const char* S, unsigned Size) /* Append a character buffer to the end of the string buffer */ { unsigned NewLen = B->Len + Size; if (NewLen > B->Allocated) { SB_Realloc (B, NewLen); } memcpy (B->Buf + B->Len, S, Size); B->Len = NewLen; } #if !defined(HAVE_INLINE) void SB_AppendStr (StrBuf* B, const char* S) /* Append a string to the end of the string buffer */ { SB_AppendBuf (B, S, strlen (S)); } #endif #if !defined(HAVE_INLINE) void SB_Append (StrBuf* Target, const StrBuf* Source) /* Append the contents of Source to Target */ { SB_AppendBuf (Target, Source->Buf, Source->Len); } #endif #if !defined(HAVE_INLINE) void SB_Cut (StrBuf* B, unsigned Len) /* Cut the contents of B at the given length. If the current length of the * buffer is smaller than Len, nothing will happen. */ { if (Len < B->Len) { B->Len = Len; } } #endif void SB_Slice (StrBuf* Target, const StrBuf* Source, unsigned Start, unsigned Len) /* Copy a slice from Source into Target. The current contents of Target are * destroyed. If Start is greater than the length of Source, or if Len * characters aren't available, the result will be a buffer with less than Len * bytes. */ { /* Calculate the length of the resulting buffer */ if (Start >= Source->Len) { /* Target will be empty */ SB_Clear (Target); return; } if (Start + Len > Source->Len) { Len = Source->Len - Start; } /* Make sure we have enough room in the target string buffer */ if (Len > Target->Allocated) { SB_Realloc (Target, Len); } /* Copy the slice */ memcpy (Target->Buf, Source->Buf + Start, Len); Target->Len = Len; } void SB_Move (StrBuf* Target, StrBuf* Source) /* Move the complete contents of Source to target. This will delete the old * contents of Target, and Source will be empty after the call. */ { /* Free the target string */ if (Target->Allocated) { xfree (Target->Buf); } /* Move all data from Source to Target */ *Target = *Source; /* Clear Source */ SB_Init (Source); } void SB_ToLower (StrBuf* S) /* Convert all characters in S to lower case */ { unsigned I; char* B = S->Buf; for (I = 0; I < S->Len; ++I, ++B) { if (IsUpper (*B)) { *B = tolower (*B); } } } void SB_ToUpper (StrBuf* S) /* Convert all characters in S to upper case */ { unsigned I; char* B = S->Buf; for (I = 0; I < S->Len; ++I, ++B) { if (IsLower (*B)) { *B = toupper (*B); } } } int SB_Compare (const StrBuf* S1, const StrBuf* S2) /* Do a lexical compare of S1 and S2. See strcmp for result codes. */ { int Result; if (S1->Len < S2->Len) { Result = memcmp (S1->Buf, S2->Buf, S1->Len); if (Result == 0) { /* S1 considered lesser because it's shorter */ Result = -1; } } else if (S1->Len > S2->Len) { Result = memcmp (S1->Buf, S2->Buf, S2->Len); if (Result == 0) { /* S2 considered lesser because it's shorter */ Result = 1; } } else { Result = memcmp (S1->Buf, S2->Buf, S1->Len); } return Result; } int SB_CompareStr (const StrBuf* S1, const char* S2) /* Do a lexical compare of S1 and S2. See strcmp for result codes. */ { int Result; unsigned S2Len = strlen (S2); if (S1->Len < S2Len) { Result = memcmp (S1->Buf, S2, S1->Len); if (Result == 0) { /* S1 considered lesser because it's shorter */ Result = -1; } } else if (S1->Len > S2Len) { Result = memcmp (S1->Buf, S2, S2Len); if (Result == 0) { /* S2 considered lesser because it's shorter */ Result = 1; } } else { Result = memcmp (S1->Buf, S2, S1->Len); } return Result; } void SB_VPrintf (StrBuf* S, const char* Format, va_list ap) /* printf function with S as target. The function is safe, which means that * the current contents of S are discarded, and are allocated again with * a matching size for the output. The function will call FAIL when problems * are detected (anything that let xsnprintf return -1). */ { va_list tmp; int SizeNeeded; /* Since we must determine the space needed anyway, we will try with * the currently allocated memory. If the call succeeds, we've saved * an allocation. If not, we have to reallocate and try again. */ va_copy (tmp, ap); SizeNeeded = xvsnprintf (S->Buf, S->Allocated, Format, tmp); va_end (tmp); /* Check the result, the xvsnprintf function should not fail */ CHECK (SizeNeeded >= 0); /* Check if we must reallocate */ if ((unsigned) SizeNeeded >= S->Allocated) { /* Must retry. Use CheapRealloc to avoid copying */ SB_CheapRealloc (S, SizeNeeded + 1); /* Account for '\0' */ (void) xvsnprintf (S->Buf, S->Allocated, Format, ap); } /* Update string buffer variables */ S->Len = SizeNeeded; S->Index = 0; } void SB_Printf (StrBuf* S, const char* Format, ...) /* vprintf function with S as target. The function is safe, which means that * the current contents of S are discarded, and are allocated again with * a matching size for the output. The function will call FAIL when problems * are detected (anything that let xsnprintf return -1). */ { va_list ap; va_start (ap, Format); SB_VPrintf (S, Format, ap); va_end (ap); }
893
./cc65/src/common/searchpath.c
/*****************************************************************************/ /* */ /* searchpath.h */ /* */ /* Handling of search paths */ /* */ /* */ /* */ /* (C) 2000-2013, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdlib.h> #include <string.h> #if defined(_MSC_VER) /* Microsoft compiler */ # include <io.h> # pragma warning(disable : 4996) #else /* Anyone else */ # include <unistd.h> #endif /* common */ #include "coll.h" #include "searchpath.h" #include "strbuf.h" #include "xmalloc.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ static char* CleanupPath (const char* Path) /* Prepare and return a clean copy of Path */ { unsigned Len; char* NewPath; /* Get the length of the path */ Len = strlen (Path); /* Check for a trailing path separator and remove it */ if (Len > 0 && (Path[Len-1] == '\\' || Path[Len-1] == '/')) { --Len; } /* Allocate memory for the new string */ NewPath = (char*) xmalloc (Len + 1); /* Copy the path and terminate it, then return the copy */ memcpy (NewPath, Path, Len); NewPath [Len] = '\0'; return NewPath; } static void Add (SearchPath* P, const char* New) /* Cleanup a new search path and add it to the list */ { /* Add a clean copy of the path to the collection */ CollAppend (P, CleanupPath (New)); } SearchPath* NewSearchPath (void) /* Create a new, empty search path list */ { return NewCollection (); } void AddSearchPath (SearchPath* P, const char* NewPath) /* Add a new search path to the end of an existing list */ { /* Allow a NULL path */ if (NewPath) { Add (P, NewPath); } } void AddSearchPathFromEnv (SearchPath* P, const char* EnvVar) /* Add a search path from an environment variable to the end of an existing * list. */ { AddSearchPath (P, getenv (EnvVar)); } void AddSubSearchPathFromEnv (SearchPath* P, const char* EnvVar, const char* SubDir) /* Add a search path from an environment variable, adding a subdirectory to * the environment variable value. */ { StrBuf Dir = AUTO_STRBUF_INITIALIZER; const char* EnvVal = getenv (EnvVar); if (EnvVal == 0) { /* Not found */ return; } /* Copy the environment variable to the buffer */ SB_CopyStr (&Dir, EnvVal); /* Add a path separator if necessary */ if (SB_NotEmpty (&Dir)) { if (SB_LookAtLast (&Dir) != '\\' && SB_LookAtLast (&Dir) != '/') { SB_AppendChar (&Dir, '/'); } } /* Add the subdirectory and terminate the string */ SB_AppendStr (&Dir, SubDir); SB_Terminate (&Dir); /* Add the search path */ AddSearchPath (P, SB_GetConstBuf (&Dir)); /* Free the temp buffer */ SB_Done (&Dir); } void AddSubSearchPathFromWinBin (SearchPath* P, const char* SubDir) { /* Windows only: * Add a search path from the running binary, adding a subdirectory to * the parent directory of the directory containing the binary. */ #if defined(_MSC_VER) char Dir[_MAX_PATH]; char* Ptr; if (_get_pgmptr (&Ptr) != 0) { return; } strcpy (Dir, Ptr); /* Remove binary name */ Ptr = strrchr (Dir, '\\'); if (Ptr == 0) { return; } *Ptr = '\0'; /* Check for 'bin' directory */ Ptr = strrchr (Dir, '\\'); if (Ptr == 0) { return; } if (strcmp (Ptr++, "\\bin") != 0) { return; } /* Append SubDir */ strcpy (Ptr, SubDir); /* Add the search path */ AddSearchPath (P, Dir); #else (void) P; (void) SubDir; #endif } int PushSearchPath (SearchPath* P, const char* NewPath) /* Add a new search path to the head of an existing search path list, provided * that it's not already there. If the path is already at the first position, * return zero, otherwise return a non zero value. */ { /* Generate a clean copy of NewPath */ char* Path = CleanupPath (NewPath); /* If we have paths, check if Path is already at position zero */ if (CollCount (P) > 0 && strcmp (CollConstAt (P, 0), Path) == 0) { /* Match. Delete the copy and return to the caller */ xfree (Path); return 0; } /* Insert a clean copy of the path at position 0, return success */ CollInsert (P, Path, 0); return 1; } void PopSearchPath (SearchPath* P) /* Remove a search path from the head of an existing search path list */ { /* Remove the path at position 0 */ xfree (CollAt (P, 0)); CollDelete (P, 0); } char* SearchFile (const SearchPath* P, const char* File) /* Search for a file in a list of directories. Return a pointer to a malloced * area that contains the complete path, if found, return 0 otherwise. */ { char* Name = 0; StrBuf PathName = AUTO_STRBUF_INITIALIZER; /* Start the search */ unsigned I; for (I = 0; I < CollCount (P); ++I) { /* Copy the next path element into the buffer */ SB_CopyStr (&PathName, CollConstAt (P, I)); /* Add a path separator and the filename */ if (SB_NotEmpty (&PathName)) { SB_AppendChar (&PathName, '/'); } SB_AppendStr (&PathName, File); SB_Terminate (&PathName); /* Check if this file exists */ if (access (SB_GetBuf (&PathName), 0) == 0) { /* The file exists, we're done */ Name = xstrdup (SB_GetBuf (&PathName)); break; } } /* Cleanup and return the result of the search */ SB_Done (&PathName); return Name; }
894
./cc65/src/common/assertion.c
/*****************************************************************************/ /* */ /* assertion.c */ /* */ /* Definitions for linker assertions */ /* */ /* */ /* */ /* (C) 2003-2009, Ullrich von Bassewitz */ /* Roemerstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "assertion.h" #include "attrib.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int AssertAtLinkTime (AssertAction A attribute ((unused))) /* Return true if this assertion should be evaluated at link time */ { /* Currently all assertions are evaluated at link time */ return 1; } int AssertAtAsmTime (AssertAction A) /* Return true if this assertion should be evaluated at assembly time */ { return (A & 0x02U) == 0; }
895
./cc65/src/common/segnames.c
/*****************************************************************************/ /* */ /* segnames.h */ /* */ /* Default segment names */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "chartype.h" #include "segnames.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ int ValidSegName (const char* Name) /* Return true if the given segment name is valid, return false otherwise */ { /* Must start with '_' or a letter */ if ((*Name != '_' && !IsAlpha(*Name)) || strlen(Name) > 80) { return 0; } /* Can have letters, digits or the underline */ while (*++Name) { if (*Name != '_' && !IsAlNum(*Name)) { return 0; } } /* Name is ok */ return 1; }
896
./cc65/src/common/bitops.c
/*****************************************************************************/ /* */ /* bitops.c */ /* */ /* Single bit operations */ /* */ /* */ /* */ /* (C) 1998 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include "bitops.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ unsigned BitFind (unsigned long Val) /* Find the first bit that is set in Val. Val must *not* be zero */ { unsigned long Mask; unsigned Bit; /* Search for the bits */ Mask = 1; Bit = 0; while (1) { if (Val & Mask) { return Bit; } Mask <<= 1; ++Bit; } } void BitSet (void* Data, unsigned Bit) /* Set a bit in a char array */ { /* Make a char pointer */ unsigned char* D = Data; /* Set the bit */ D [Bit / 8] |= 0x01 << (Bit % 8); } void BitReset (void* Data, unsigned Bit) /* Reset a bit in a char array */ { /* Make a char pointer */ unsigned char* D = Data; /* Set the bit */ D [Bit / 8] &= ~(0x01 << (Bit % 8)); } int BitIsSet (void* Data, unsigned Bit) /* Check if a bit is set in a char array */ { /* Make a char pointer */ unsigned char* D = Data; /* Check the bit state */ return (D [Bit / 8] & (0x01 << (Bit % 8))) != 0; } int BitIsReset (void* Data, unsigned Bit) /* Check if a bit is reset in a char array */ { /* Make a char pointer */ unsigned char* D = Data; /* Check the bit state */ return (D [Bit / 8] & (0x01 << (Bit % 8))) == 0; } void BitMerge (void* Target, const void* Source, unsigned Size) /* Merge the bits of two char arrays (that is, do an or for the full array) */ { /* Make char arrays */ unsigned char* T = Target; const unsigned char* S = Source; /* Merge the arrays */ while (Size--) { *T++ |= *S++; } }
897
./cc65/src/common/shift.c
/*****************************************************************************/ /* */ /* shift.c */ /* */ /* Safe shift routines */ /* */ /* */ /* */ /* (C) 2003 Ullrich von Bassewitz */ /* R÷merstra▀e 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ /* According to the C standard, shifting a data type by the number of bits it * has causes undefined behaviour. So * * unsigned long l = 1; * unsigned u =32; * l <<= u; * * maybe illegal. The functions in this module behave safely in this respect, * and they use proper casting to distinguish signed from unsigned shifts. * They are not a general purpose replacement for the shift operator! */ #include <limits.h> /* common */ #include "shift.h" /*****************************************************************************/ /* Code */ /*****************************************************************************/ long asl_l (long l, unsigned count) /* Arithmetic shift left l by count. */ { while (1) { if (count >= CHAR_BIT * sizeof (l)) { l <<= (CHAR_BIT * sizeof (l) - 1); count -= (CHAR_BIT * sizeof (l) - 1); } else { l <<= count; break; } } return l; } long asr_l (long l, unsigned count) /* Arithmetic shift right l by count */ { while (1) { if (count >= CHAR_BIT * sizeof (l)) { l >>= (CHAR_BIT * sizeof (l) - 1); count -= (CHAR_BIT * sizeof (l) - 1); } else { l >>= count; break; } } return l; } unsigned long shl_l (unsigned long l, unsigned count) /* Logical shift left l by count */ { while (1) { if (count >= CHAR_BIT * sizeof (l)) { l <<= (CHAR_BIT * sizeof (l) - 1); count -= (CHAR_BIT * sizeof (l) - 1); } else { l <<= count; break; } } return l; } unsigned long shr_l (unsigned long l, unsigned count) /* Logical shift right l by count */ { while (1) { if (count >= CHAR_BIT * sizeof (l)) { l >>= (CHAR_BIT * sizeof (l) - 1); count -= (CHAR_BIT * sizeof (l) - 1); } else { l >>= count; break; } } return l; }
898
./cc65/src/common/xsprintf.c
/*****************************************************************************/ /* */ /* xsprintf.c */ /* */ /* Replacement sprintf function */ /* */ /* */ /* */ /* (C) 2000-2004 Ullrich von Bassewitz */ /* R÷merstrasse 52 */ /* D-70794 Filderstadt */ /* EMail: uz@cc65.org */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdio.h> #include <stddef.h> #include <string.h> #include <limits.h> /* common */ #include "chartype.h" #include "check.h" #include "inttypes.h" #include "strbuf.h" #include "va_copy.h" #include "xsprintf.h" /*****************************************************************************/ /* vsnprintf */ /*****************************************************************************/ /* The following is a very basic vsnprintf like function called xvsnprintf. It * features only the basic format specifiers (especially the floating point * stuff is missing), but may be extended if required. Reason for supplying * my own implementation is that vsnprintf is standard but not implemented by * older compilers, and some that implement it, don't adhere to the standard * (for example Microsoft with its _vsnprintf). */ typedef struct { /* Variable argument list pointer */ va_list ap; /* Output buffer */ char* Buf; size_t BufSize; size_t BufFill; /* Argument string buffer and string buffer pointer. The string buffer * must be big enough to hold a converted integer of the largest type * including an optional sign and terminating zero. */ char ArgBuf[256]; int ArgLen; /* Flags */ enum { fNone = 0x0000, fMinus = 0x0001, fPlus = 0x0002, fSpace = 0x0004, fHash = 0x0008, fZero = 0x0010, fWidth = 0x0020, fPrec = 0x0040, fUnsigned = 0x0080, fUpcase = 0x0100 } Flags; /* Conversion base and table */ unsigned Base; const char* CharTable; /* Field width */ int Width; /* Precision */ int Prec; /* Length modifier */ enum { lmChar, lmShort, lmInt, lmLong, lmIntMax, lmSizeT, lmPtrDiffT, lmLongDouble, /* Unsupported modifiers */ lmLongLong = lmLong, /* Default length is integer */ lmDefault = lmInt } LengthMod; } PrintfCtrl; static void AddChar (PrintfCtrl* P, char C) /* Store one character in the output buffer if there's enough room. */ { if (++P->BufFill <= P->BufSize) { *P->Buf++ = C; } } static void AddPadding (PrintfCtrl* P, char C, unsigned Count) /* Add some amount of padding */ { while (Count--) { AddChar (P, C); } } static intmax_t NextIVal (PrintfCtrl*P) /* Read the next integer value from the variable argument list */ { switch (P->LengthMod) { case lmChar: return (char) va_arg (P->ap, int); case lmShort: return (short) va_arg (P->ap, int); case lmInt: return (int) va_arg (P->ap, int); case lmLong: return (long) va_arg (P->ap, long); case lmIntMax: return va_arg (P->ap, intmax_t); case lmSizeT: return (uintmax_t) va_arg (P->ap, size_t); case lmPtrDiffT: return (long) va_arg (P->ap, ptrdiff_t); default: FAIL ("Invalid type size in NextIVal"); return 0; } } static uintmax_t NextUVal (PrintfCtrl*P) /* Read the next unsigned integer value from the variable argument list */ { switch (P->LengthMod) { case lmChar: return (unsigned char) va_arg (P->ap, unsigned); case lmShort: return (unsigned short) va_arg (P->ap, unsigned); case lmInt: return (unsigned int) va_arg (P->ap, unsigned int); case lmLong: return (unsigned long) va_arg (P->ap, unsigned long); case lmIntMax: return va_arg (P->ap, uintmax_t); case lmSizeT: return va_arg (P->ap, size_t); case lmPtrDiffT: return (intmax_t) va_arg (P->ap, ptrdiff_t); default: FAIL ("Invalid type size in NextUVal"); return 0; } } static void ToStr (PrintfCtrl* P, uintmax_t Val) /* Convert the given value to a (reversed) string */ { char* S = P->ArgBuf; while (Val) { *S++ = P->CharTable[Val % P->Base]; Val /= P->Base; } P->ArgLen = S - P->ArgBuf; } static void FormatInt (PrintfCtrl* P, uintmax_t Val) /* Convert the integer value */ { char Lead[5]; unsigned LeadCount = 0; unsigned PrecPadding; unsigned WidthPadding; unsigned I; /* Determine the translation table */ P->CharTable = (P->Flags & fUpcase)? "0123456789ABCDEF" : "0123456789abcdef"; /* Check if the value is negative */ if ((P->Flags & fUnsigned) == 0 && ((intmax_t) Val) < 0) { Val = -((intmax_t) Val); Lead[LeadCount++] = '-'; } else if ((P->Flags & fPlus) != 0) { Lead[LeadCount++] = '+'; } else if ((P->Flags & fSpace) != 0) { Lead[LeadCount++] = ' '; } /* Convert the value into a (reversed string). */ ToStr (P, Val); /* The default precision for all integer conversions is one. This means * that the fPrec flag is always set and does not need to be checked * later on. */ if ((P->Flags & fPrec) == 0) { P->Flags |= fPrec; P->Prec = 1; } /* Determine the leaders for alternative forms */ if ((P->Flags & fHash) != 0) { if (P->Base == 16) { /* Start with 0x */ Lead[LeadCount++] = '0'; Lead[LeadCount++] = (P->Flags & fUpcase)? 'X' : 'x'; } else if (P->Base == 8) { /* Alternative form for 'o': always add a leading zero. */ if (P->Prec <= P->ArgLen) { Lead[LeadCount++] = '0'; } } } /* Determine the amount of precision padding needed */ if (P->ArgLen < P->Prec) { PrecPadding = P->Prec - P->ArgLen; } else { PrecPadding = 0; } /* Determine the width padding needed */ if ((P->Flags & fWidth) != 0) { int CurWidth = LeadCount + PrecPadding + P->ArgLen; if (CurWidth < P->Width) { WidthPadding = P->Width - CurWidth; } else { WidthPadding = 0; } } else { WidthPadding = 0; } /* Output left space padding if any */ if ((P->Flags & (fMinus | fZero)) == 0 && WidthPadding > 0) { AddPadding (P, ' ', WidthPadding); WidthPadding = 0; } /* Leader */ for (I = 0; I < LeadCount; ++I) { AddChar (P, Lead[I]); } /* Left zero padding if any */ if ((P->Flags & fZero) != 0 && WidthPadding > 0) { AddPadding (P, '0', WidthPadding); WidthPadding = 0; } /* Precision padding */ if (PrecPadding > 0) { AddPadding (P, '0', PrecPadding); } /* The number itself. Beware: It's reversed! */ while (P->ArgLen > 0) { AddChar (P, P->ArgBuf[--P->ArgLen]); } /* Right width padding if any */ if (WidthPadding > 0) { AddPadding (P, ' ', WidthPadding); } } static void FormatStr (PrintfCtrl* P, const char* Val) /* Convert the string */ { unsigned WidthPadding; /* Get the string length limited to the precision. Beware: We cannot use * strlen here, because if a precision is given, the string may not be * zero terminated. */ int Len; if ((P->Flags & fPrec) != 0) { const char* S = memchr (Val, '\0', P->Prec); if (S == 0) { /* Not zero terminated */ Len = P->Prec; } else { /* Terminating zero found */ Len = S - Val; } } else { Len = strlen (Val); } /* Determine the width padding needed */ if ((P->Flags & fWidth) != 0 && P->Width > Len) { WidthPadding = P->Width - Len; } else { WidthPadding = 0; } /* Output left padding */ if ((P->Flags & fMinus) != 0 && WidthPadding > 0) { AddPadding (P, ' ', WidthPadding); WidthPadding = 0; } /* Output the string */ while (Len--) { AddChar (P, *Val++); } /* Output right padding if any */ if (WidthPadding > 0) { AddPadding (P, ' ', WidthPadding); } } static void StoreOffset (PrintfCtrl* P) /* Store the current output offset (%n format spec) */ { switch (P->LengthMod) { case lmChar: *va_arg (P->ap, int*) = P->BufFill; case lmShort: *va_arg (P->ap, int*) = P->BufFill; case lmInt: *va_arg (P->ap, int*) = P->BufFill; case lmLong: *va_arg (P->ap, long*) = P->BufFill; case lmIntMax: *va_arg (P->ap, intmax_t*) = P->BufFill; case lmSizeT: *va_arg (P->ap, size_t*) = P->BufFill; case lmPtrDiffT: *va_arg (P->ap, ptrdiff_t*) = P->BufFill; default: FAIL ("Invalid size modifier for %n format spec in xvsnprintf"); } } int xvsnprintf (char* Buf, size_t Size, const char* Format, va_list ap) /* A basic vsnprintf implementation. Does currently only support integer * formats. */ { PrintfCtrl P; int Done; char F; char SBuf[2]; const char* SPtr; int UseStrBuf = 0; /* Initialize the control structure */ va_copy (P.ap, ap); P.Buf = Buf; P.BufSize = Size; P.BufFill = 0; /* Parse the format string */ while ((F = *Format++) != '\0') { if (F != '%') { /* Not a format specifier, just copy */ AddChar (&P, F); continue; } /* Check for %% */ if (*Format == '%') { ++Format; AddChar (&P, '%'); continue; } /* It's a format specifier. Check for flags. */ F = *Format++; P.Flags = fNone; Done = 0; while (F != '\0' && !Done) { switch (F) { case '-': P.Flags |= fMinus; F = *Format++; break; case '+': P.Flags |= fPlus; F = *Format++; break; case ' ': P.Flags |= fSpace; F = *Format++; break; case '#': P.Flags |= fHash; F = *Format++; break; case '0': P.Flags |= fZero; F = *Format++; break; default: Done = 1; break; } } /* Optional field width */ if (F == '*') { P.Width = va_arg (P.ap, int); /* A negative field width argument is taken as a - flag followed * by a positive field width. */ if (P.Width < 0) { P.Flags |= fMinus; P.Width = -P.Width; } F = *Format++; P.Flags |= fWidth; } else if (IsDigit (F)) { P.Width = F - '0'; while (1) { F = *Format++; if (!IsDigit (F)) { break; } P.Width = P.Width * 10 + (F - '0'); } P.Flags |= fWidth; } /* Optional precision */ if (F == '.') { F = *Format++; P.Flags |= fPrec; if (F == '*') { P.Prec = va_arg (P.ap, int); /* A negative precision argument is taken as if the precision * were omitted. */ if (P.Prec < 0) { P.Flags &= ~fPrec; } F = *Format++; /* Skip the '*' */ } else if (IsDigit (F)) { P.Prec = F - '0'; while (1) { F = *Format++; if (!IsDigit (F)) { break; } P.Prec = P.Prec * 10 + (F - '0'); } } else if (F == '-') { /* A negative precision argument is taken as if the precision * were omitted. */ F = *Format++; /* Skip the minus */ while (IsDigit (F = *Format++)) ; P.Flags &= ~fPrec; } else { P.Prec = 0; } } /* Optional length modifier */ P.LengthMod = lmDefault; switch (F) { case 'h': F = *Format++; if (F == 'h') { F = *Format++; P.LengthMod = lmChar; } else { P.LengthMod = lmShort; } break; case 'l': F = *Format++; if (F == 'l') { F = *Format++; P.LengthMod = lmLongLong; } else { P.LengthMod = lmLong; } break; case 'j': P.LengthMod = lmIntMax; F = *Format++; break; case 'z': P.LengthMod = lmSizeT; F = *Format++; break; case 't': P.LengthMod = lmPtrDiffT; F = *Format++; break; case 'L': P.LengthMod = lmLongDouble; F = *Format++; break; } /* If the space and + flags both appear, the space flag is ignored */ if ((P.Flags & (fSpace | fPlus)) == (fSpace | fPlus)) { P.Flags &= ~fSpace; } /* If the 0 and - flags both appear, the 0 flag is ignored */ if ((P.Flags & (fZero | fMinus)) == (fZero | fMinus)) { P.Flags &= ~fZero; } /* If a precision is specified, the 0 flag is ignored */ if (P.Flags & fPrec) { P.Flags &= ~fZero; } /* Conversion specifier */ switch (F) { case 'd': case 'i': P.Base = 10; FormatInt (&P, NextIVal (&P)); break; case 'o': P.Flags |= fUnsigned; P.Base = 8; FormatInt (&P, NextUVal (&P)); break; case 'u': P.Flags |= fUnsigned; P.Base = 10; FormatInt (&P, NextUVal (&P)); break; case 'X': P.Flags |= (fUnsigned | fUpcase); /* FALLTHROUGH */ case 'x': P.Base = 16; FormatInt (&P, NextUVal (&P)); break; case 'c': SBuf[0] = (char) va_arg (P.ap, int); SBuf[1] = '\0'; FormatStr (&P, SBuf); break; case 's': SPtr = va_arg (P.ap, const char*); CHECK (SPtr != 0); FormatStr (&P, SPtr); break; case 'p': /* See comment at top of header file */ if (UseStrBuf) { /* Argument is StrBuf */ const StrBuf* S = va_arg (P.ap, const StrBuf*); CHECK (S != 0); /* Handle the length by using a precision */ if ((P.Flags & fPrec) != 0) { /* Precision already specified, use length of string * if less. */ if ((unsigned) P.Prec > SB_GetLen (S)) { P.Prec = SB_GetLen (S); } } else { /* No precision, add it */ P.Flags |= fPrec; P.Prec = SB_GetLen (S); } FormatStr (&P, SB_GetConstBuf (S)); UseStrBuf = 0; /* Reset flag */ } else { /* Use hex format for pointers */ P.Flags |= (fUnsigned | fPrec); P.Prec = ((sizeof (void*) * CHAR_BIT) + 3) / 4; P.Base = 16; FormatInt (&P, (uintptr_t) va_arg (P.ap, void*)); } break; case 'm': /* See comment at top of header file */ UseStrBuf = 1; break; case 'n': StoreOffset (&P); break; default: /* Invalid format spec */ FAIL ("Invalid format specifier in xvsnprintf"); } } /* We don't need P.ap any longer */ va_end (P.ap); /* Terminate the output string and return the number of chars that had * been written if the buffer was large enough. * Beware: The terminating zero is not counted for the function result! */ AddChar (&P, '\0'); return P.BufFill - 1; } int xsnprintf (char* Buf, size_t Size, const char* Format, ...) /* A basic snprintf implementation. Does currently only support integer * formats. */ { int Res; va_list ap; va_start (ap, Format); Res = xvsnprintf (Buf, Size, Format, ap); va_end (ap); return Res; } /*****************************************************************************/ /* Code */ /*****************************************************************************/ int xsprintf (char* Buf, size_t BufSize, const char* Format, ...) /* Replacement function for sprintf */ { int Res; va_list ap; va_start (ap, Format); Res = xvsprintf (Buf, BufSize, Format, ap); va_end (ap); return Res; } int xvsprintf (char* Buf, size_t BufSize, const char* Format, va_list ap) /* Replacement function for sprintf */ { int Res = xvsnprintf (Buf, BufSize, Format, ap); CHECK (Res >= 0 && (unsigned) (Res+1) < BufSize); return Res; }
899
./cc65/src/common/print.c
/*****************************************************************************/ /* */ /* print.c */ /* */ /* Program output */ /* */ /* */ /* */ /* (C) 2001 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <stdarg.h> /* common */ #include "print.h" /*****************************************************************************/ /* Data */ /*****************************************************************************/ unsigned char Verbosity = 0; /* Verbose operation flag */ /*****************************************************************************/ /* Code */ /*****************************************************************************/ void Print (FILE* F, unsigned V, const char* Format, ...) /* Output according to Verbosity */ { va_list ap; /* Check the verbosity */ if (V > Verbosity) { /* Don't output this message */ return; } /* Output */ va_start (ap, Format); vfprintf (F, Format, ap); va_end (ap); }
900
./cc65/src/common/matchpat.c
/*****************************************************************************/ /* */ /* matchpat.c */ /* */ /* Unix shell like pattern matching */ /* */ /* */ /* */ /* (C) 2002 Ullrich von Bassewitz */ /* Wacholderweg 14 */ /* D-70597 Stuttgart */ /* EMail: uz@musoftware.de */ /* */ /* */ /* This software is provided 'as-is', without any expressed or implied */ /* warranty. In no event will the authors be held liable for any damages */ /* arising from the use of this software. */ /* */ /* Permission is granted to anyone to use this software for any purpose, */ /* including commercial applications, and to alter it and redistribute it */ /* freely, subject to the following restrictions: */ /* */ /* 1. The origin of this software must not be misrepresented; you must not */ /* claim that you wrote the original software. If you use this software */ /* in a product, an acknowledgment in the product documentation would be */ /* appreciated but is not required. */ /* 2. Altered source versions must be plainly marked as such, and must not */ /* be misrepresented as being the original software. */ /* 3. This notice may not be removed or altered from any source */ /* distribution. */ /* */ /*****************************************************************************/ #include <string.h> /* common */ #include "matchpat.h" /*****************************************************************************/ /* Character bit set implementation */ /*****************************************************************************/ typedef unsigned char CharSet[32]; /* 256 bits */ /* Clear a character set */ #define CS_CLEAR(CS) memset (CS, 0, sizeof (CharSet)) /* Set all characters in the set */ #define CS_SETALL(CS) memset (CS, 0xFF, sizeof (CharSet)) /* Add one char to the set */ #define CS_ADD(CS, C) ((CS)[(C) >> 3] |= (0x01 << ((C) & 0x07))) /* Check if a character is a member of the set */ #define CS_CONTAINS(CS, C) ((CS)[(C) >> 3] & (0x01 << ((C) & 0x07))) /* Invert a character set */ #define CS_INVERT(CS) \ do { \ unsigned I; \ for (I = 0; I < sizeof (CharSet); ++I) { \ CS[I] ^= 0xFF; \ } \ } while (0) /*****************************************************************************/ /* Code */ /*****************************************************************************/ /* Escape character */ #define ESCAPE_CHAR '\\' /* Utility macro used in RecursiveMatch */ #define IncPattern() Pattern++; \ if (*Pattern == '\0') { \ return 0; \ } static int RealChar (const unsigned char* Pattern) /* Return the next character from Pattern. If the next character is the * escape character, skip it and return the following. */ { if (*Pattern == ESCAPE_CHAR) { Pattern++; return (*Pattern == '\0') ? -1 : *Pattern; } else { return *Pattern; } } static int RecursiveMatch (const unsigned char* Source, const unsigned char* Pattern) /* A recursive pattern matcher */ { CharSet CS; while (1) { if (*Pattern == '\0') { /* Reached the end of Pattern, what about Source? */ return (*Source == '\0') ? 1 : 0; } else if (*Pattern == '*') { if (*++Pattern == '\0') { /* A trailing '*' is always a match */ return 1; } /* Check the rest of the string */ while (*Source) { if (RecursiveMatch (Source++, Pattern)) { /* Match! */ return 1; } } /* No match... */ return 0; } else if (*Source == '\0') { /* End of Source reached, no match */ return 0; } else { /* Check a single char. Build a set of all possible characters in * CS, then check if the current char of Source is contained in * there. */ CS_CLEAR (CS); /* Clear the character set */ if (*Pattern == '?') { /* All chars are allowed */ CS_SETALL (CS); ++Pattern; /* Skip '?' */ } else if (*Pattern == ESCAPE_CHAR) { /* Use the next char as is */ IncPattern (); CS_ADD (CS, *Pattern); ++Pattern; /* Skip the character */ } else if (*Pattern == '[') { /* A set follows */ int Invert = 0; IncPattern (); if (*Pattern == '!') { IncPattern (); Invert = 1; } while (*Pattern != ']') { int C1; if ((C1 = RealChar (Pattern)) == -1) { return 0; } IncPattern (); if (*Pattern != '-') { CS_ADD (CS, C1); } else { int C2; unsigned char C; IncPattern (); if ((C2 = RealChar (Pattern)) == -1) { return 0; } IncPattern (); for (C = C1; C <= C2; C++) { CS_ADD (CS, C); } } } /* Skip ']' */ ++Pattern; if (Invert) { /* Reverse all bits in the set */ CS_INVERT (CS); } } else { /* Include the char in the charset, then skip it */ CS_ADD (CS, *Pattern); ++Pattern; } if (!CS_CONTAINS (CS, *Source)) { /* No match */ return 0; } ++Source; } } } int MatchPattern (const char* Source, const char* Pattern) /* Match the string in Source against Pattern. Pattern may contain the * wildcards '*', '?', '[abcd]' '[ab-d]', '[!abcd]', '[!ab-d]'. The * function returns a value of zero if Source does not match Pattern, * otherwise a non zero value is returned. If Pattern contains an invalid * wildcard pattern (e.g. 'A[x'), the function returns zero. */ { /* Handle the trivial cases */ if (Pattern == 0 || *Pattern == '\0') { return (Source == 0 || *Source == '\0'); } /* Do the real thing */ return RecursiveMatch ((const unsigned char*) Source, (const unsigned char*) Pattern); }