1 /*****************************************************************************/
5 /* Local variable handling for the cc65 C compiler */
9 /* (C) 2000-2002 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
54 /*****************************************************************************/
56 /*****************************************************************************/
60 /* Register variable management */
61 unsigned MaxRegSpace = 6; /* Maximum space available */
62 static unsigned RegOffs = 0; /* Offset into register space */
63 static const SymEntry** RegSyms = 0; /* The register variables */
64 static unsigned RegSymCount = 0; /* Number of register variables */
68 /*****************************************************************************/
70 /*****************************************************************************/
74 void InitRegVars (void)
75 /* Initialize register variable control data */
77 /* If the register space is zero, bail out */
78 if (MaxRegSpace == 0) {
82 /* The maximum number of register variables is equal to the register
83 * variable space available. So allocate one pointer per byte. This
84 * will usually waste some space but we don't need to dynamically
87 RegSyms = (const SymEntry**) xmalloc (MaxRegSpace * sizeof (RegSyms[0]));
88 RegOffs = MaxRegSpace;
93 void DoneRegVars (void)
94 /* Free the register variables */
98 RegOffs = MaxRegSpace;
104 static int AllocRegVar (const SymEntry* Sym, const type* tarray)
105 /* Allocate a register variable with the given amount of storage. If the
106 * allocation was successful, return the offset of the register variable in
107 * the register bank (zero page storage). If there is no register space left,
111 /* Maybe register variables are disabled... */
114 /* Get the size of the variable */
115 unsigned Size = CheckedSizeOf (tarray);
117 /* Do we have space left? */
118 if (RegOffs >= Size) {
120 /* Space left. We allocate the variables from high to low addresses,
121 * so the adressing is compatible with the saved values on stack.
122 * This allows shorter code when saving/restoring the variables.
125 RegSyms [RegSymCount++] = Sym;
130 /* No space left or no allocation */
136 static unsigned ParseAutoDecl (Declaration* Decl, unsigned* SC)
137 /* Parse the declaration of an auto variable. The function returns the symbol
138 * data, which is the offset for variables on the stack, and the label for
146 /* Determine if this is a compound variable */
147 int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
149 /* Get the size of the variable */
150 unsigned Size = SizeOf (Decl->Type);
152 /* Check if this is a variable on the stack or in static memory */
153 if (StaticLocals == 0) {
155 /* Change SC in case it was register */
156 *SC = (*SC & ~SC_REGISTER) | SC_AUTO;
157 if (CurTok.Tok == TOK_ASSIGN) {
164 /* Special handling for compound types */
167 /* First reserve space for the variable */
168 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
170 /* Next, allocate the space on the stack. This means that the
171 * variable is now located at offset 0 from the current sp.
173 F_AllocLocalSpace (CurrentFunc);
175 /* Switch to read only data */
178 /* Define a label for the initialization data */
179 InitLabel = GetLocalLabel ();
180 g_defdatalabel (InitLabel);
182 /* Parse the initialization generating a memory image of the
183 * data in the RODATA segment.
185 ParseInit (Decl->Type);
187 /* Generate code to copy this data into the variable space */
188 g_initauto (InitLabel, Size);
192 /* Allocate previously reserved local space */
193 F_AllocLocalSpace (CurrentFunc);
195 /* Setup the type flags for the assignment */
196 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
198 /* Get the expression into the primary */
199 if (evalexpr (Flags, hie1, &lval) == 0) {
200 /* Constant expression. Adjust the types */
201 assignadjust (Decl->Type, &lval);
204 /* Expression is not constant and in the primary */
205 assignadjust (Decl->Type, &lval);
209 g_push (Flags | TypeOf (Decl->Type), lval.ConstVal);
213 /* Mark the variable as referenced */
216 /* Variable is located at the current SP */
220 /* Non-initialized local variable. Just keep track of
223 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
228 /* Static local variables. */
229 *SC = (*SC & ~(SC_REGISTER | SC_AUTO)) | SC_STATIC;
231 /* Put them into the BSS */
234 /* Define the variable label */
235 SymData = GetLocalLabel ();
236 g_defdatalabel (SymData);
238 /* Reserve space for the data */
241 /* Allow assignments */
242 if (CurTok.Tok == TOK_ASSIGN) {
251 /* Switch to read only data */
254 /* Define a label for the initialization data */
255 InitLabel = GetLocalLabel ();
256 g_defdatalabel (InitLabel);
258 /* Parse the initialization generating a memory image of the
259 * data in the RODATA segment.
261 ParseInit (Decl->Type);
263 /* Generate code to copy this data into the variable space */
264 g_initstatic (InitLabel, SymData, Size);
268 /* Setup the type flags for the assignment */
269 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
271 /* Get the expression into the primary */
272 if (evalexpr (Flags, hie1, &lval) == 0) {
273 /* Constant expression. Adjust the types */
274 assignadjust (Decl->Type, &lval);
276 /* Load it into the primary */
277 exprhs (Flags, 0, &lval);
279 /* Expression is not constant and in the primary */
280 assignadjust (Decl->Type, &lval);
283 /* Store the value into the variable */
284 g_putstatic (Flags | TypeOf (Decl->Type), SymData, 0);
288 /* Mark the variable as referenced */
293 /* Cannot allocate a variable of zero size */
295 Error ("Variable `%s' has unknown size", Decl->Ident);
298 /* Return the symbol data */
304 static unsigned ParseStaticDecl (Declaration* Decl, unsigned* SC)
305 /* Parse the declaration of a static variable. The function returns the symbol
306 * data, which is the asm label of the variable.
311 /* Get the size of the variable */
312 unsigned Size = SizeOf (Decl->Type);
315 if (CurTok.Tok == TOK_ASSIGN) {
317 /* Initialization ahead, switch to data segment */
318 if (IsQualConst (Decl->Type)) {
324 /* Define the variable label */
325 SymData = GetLocalLabel ();
326 g_defdatalabel (SymData);
331 /* Allow initialization of static vars */
332 ParseInit (Decl->Type);
334 /* If the previous size has been unknown, it must be known now */
336 Size = SizeOf (Decl->Type);
339 /* Mark the variable as referenced */
344 /* Uninitialized data, use BSS segment */
347 /* Define the variable label */
348 SymData = GetLocalLabel ();
349 g_defdatalabel (SymData);
351 /* Reserve space for the data */
356 /* Cannot allocate a variable of zero size */
358 Error ("Variable `%s' has unknown size", Decl->Ident);
361 /* Return the symbol data */
367 static void ParseOneDecl (const DeclSpec* Spec)
368 /* Parse one variable declaration */
370 unsigned SC; /* Storage class for symbol */
371 unsigned SymData = 0; /* Symbol data (offset, label name, ...) */
372 Declaration Decl; /* Declaration data structure */
374 /* Remember the storage class for the new symbol */
375 SC = Spec->StorageClass;
377 /* Read the declaration */
378 ParseDecl (Spec, &Decl, DM_NEED_IDENT);
380 /* Set the correct storage class for functions */
381 if (IsTypeFunc (Decl.Type)) {
382 /* Function prototypes are always external */
383 if ((SC & SC_EXTERN) == 0) {
384 Warning ("Function must be extern");
386 SC |= SC_FUNC | SC_EXTERN;
390 /* If we don't have a name, this was flagged as an error earlier.
391 * To avoid problems later, use an anonymous name here.
393 if (Decl.Ident[0] == '\0') {
394 AnonName (Decl.Ident, "param");
397 /* Handle anything that needs storage (no functions, no typdefs) */
398 if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
401 if (SC & (SC_AUTO | SC_REGISTER)) {
404 SymData = ParseAutoDecl (&Decl, &SC);
406 } else if ((SC & SC_STATIC) == SC_STATIC) {
408 /* Static variable */
409 SymData = ParseStaticDecl (&Decl, &SC);
414 /* If the symbol is not marked as external, it will be defined */
415 if ((SC & SC_EXTERN) == 0) {
419 /* Add the symbol to the symbol table */
420 AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
425 void DeclareLocals (void)
426 /* Declare local variables and types. */
428 /* Remember the current stack pointer */
429 int InitialStack = oursp;
431 /* Loop until we don't find any more variables */
434 /* Check variable declarations. We need to distinguish between a
435 * default int type and the end of variable declarations. So we
436 * will do the following: If there is no explicit storage class
437 * specifier *and* no explicit type given, it is assume that we
438 * have reached the end of declarations.
441 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
442 if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
446 /* Accept type only declarations */
447 if (CurTok.Tok == TOK_SEMI) {
448 /* Type declaration only */
449 CheckEmptyDecl (&Spec);
454 /* Parse a comma separated variable list */
457 /* Parse one declaration */
458 ParseOneDecl (&Spec);
460 /* Check if there is more */
461 if (CurTok.Tok == TOK_COMMA) {
470 /* A semicolon must follow */
474 /* Be sure to allocate any reserved space for locals */
475 F_AllocLocalSpace (CurrentFunc);
477 /* In case we've allocated local variables in this block, emit a call to
478 * the stack checking routine if stack checks are enabled.
480 if (CheckStack && InitialStack != oursp) {
487 void RestoreRegVars (int HaveResult)
488 /* Restore the register variables for the local function if there are any.
489 * The parameter tells us if there is a return value in ax, in that case,
490 * the accumulator must be saved across the restore.
496 /* If we don't have register variables in this function, bail out early */
497 if (RegSymCount == 0) {
501 /* Save the accumulator if needed */
502 if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
503 g_save (CF_CHAR | CF_FORCECHAR);
506 /* Walk through all variables. If there are several variables in a row
507 * (that is, with increasing stack offset), restore them in one chunk.
510 while (I < RegSymCount) {
512 /* Check for more than one variable */
513 const SymEntry* Sym = RegSyms[I];
515 Bytes = CheckedSizeOf (Sym->Type);
518 while (J < RegSymCount) {
520 /* Get the next symbol */
521 const SymEntry* NextSym = RegSyms [J];
524 int Size = CheckedSizeOf (NextSym->Type);
526 /* Adjacent variable? */
527 if (NextSym->V.Offs + Size != Offs) {
532 /* Adjacent variable */
539 /* Restore the memory range */
540 g_restore_regvars (Offs, Sym->V.Offs, Bytes);
546 /* Restore the accumulator if needed */
547 if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
548 g_restore (CF_CHAR | CF_FORCECHAR);