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 type* Type)
105 /* Allocate a register variable for the given variable type. If the allocation
106 * was successful, return the offset of the register variable in the register
107 * bank (zero page storage). If there is no register space left, return -1.
110 /* Maybe register variables are disabled... */
113 /* Get the size of the variable */
114 unsigned Size = CheckedSizeOf (Type);
116 /* Do we have space left? */
117 if (RegOffs >= Size) {
118 /* Space left. We allocate the variables from high to low addresses,
119 * so the adressing is compatible with the saved values on stack.
120 * This allows shorter code when saving/restoring the variables.
127 /* No space left or no allocation */
133 static void RememberRegVar (const SymEntry* Sym)
134 /* Remember the given register variable */
136 RegSyms[RegSymCount++] = Sym;
141 static unsigned ParseRegisterDecl (Declaration* Decl, unsigned* SC, int Reg)
142 /* Parse the declaration of a register variable. The function returns the
143 * symbol data, which is the offset of the variable in the register bank.
149 /* Determine if this is a compound variable */
150 int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
152 /* Get the size of the variable */
153 unsigned Size = SizeOf (Decl->Type);
155 /* Save the current contents of the register variable on stack */
156 F_AllocLocalSpace (CurrentFunc);
157 g_save_regvars (Reg, Size);
159 /* Check for an optional initialization */
160 if (CurTok.Tok == TOK_ASSIGN) {
167 /* Special handling for compound types */
170 /* Switch to read only data */
173 /* Define a label for the initialization data */
174 InitLabel = GetLocalLabel ();
175 g_defdatalabel (InitLabel);
177 /* Parse the initialization generating a memory image of the
178 * data in the RODATA segment.
180 ParseInit (Decl->Type);
182 /* Generate code to copy this data into the variable space */
183 g_initregister (InitLabel, Reg, Size);
187 /* Setup the type flags for the assignment */
189 if (Size == SIZEOF_CHAR) {
190 Flags |= CF_FORCECHAR;
193 /* Get the expression into the primary */
194 if (evalexpr (Flags, hie1, &lval) == 0) {
195 /* Constant expression. Adjust the types */
196 assignadjust (Decl->Type, &lval);
199 /* Expression is not constant and in the primary */
200 assignadjust (Decl->Type, &lval);
203 /* Store the value into the variable */
204 g_putstatic (Flags | TypeOf (Decl->Type), Reg, 0);
208 /* Mark the variable as referenced */
212 /* Cannot allocate a variable of zero size */
214 Error ("Variable `%s' has unknown size", Decl->Ident);
217 /* Return the symbol data */
223 static unsigned ParseAutoDecl (Declaration* Decl, unsigned* SC)
224 /* Parse the declaration of an auto variable. The function returns the symbol
225 * data, which is the offset for variables on the stack, and the label for
233 /* Determine if this is a compound variable */
234 int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
236 /* Get the size of the variable */
237 unsigned Size = SizeOf (Decl->Type);
239 /* Check if this is a variable on the stack or in static memory */
240 if (StaticLocals == 0) {
242 /* Check for an optional initialization */
243 if (CurTok.Tok == TOK_ASSIGN) {
250 /* Special handling for compound types */
253 /* First reserve space for the variable */
254 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
256 /* Next, allocate the space on the stack. This means that the
257 * variable is now located at offset 0 from the current sp.
259 F_AllocLocalSpace (CurrentFunc);
261 /* Switch to read only data */
264 /* Define a label for the initialization data */
265 InitLabel = GetLocalLabel ();
266 g_defdatalabel (InitLabel);
268 /* Parse the initialization generating a memory image of the
269 * data in the RODATA segment.
271 ParseInit (Decl->Type);
273 /* Generate code to copy this data into the variable space */
274 g_initauto (InitLabel, Size);
278 /* Allocate previously reserved local space */
279 F_AllocLocalSpace (CurrentFunc);
281 /* Setup the type flags for the assignment */
282 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
284 /* Get the expression into the primary */
285 if (evalexpr (Flags, hie1, &lval) == 0) {
286 /* Constant expression. Adjust the types */
287 assignadjust (Decl->Type, &lval);
290 /* Expression is not constant and in the primary */
291 assignadjust (Decl->Type, &lval);
295 g_push (Flags | TypeOf (Decl->Type), lval.ConstVal);
299 /* Mark the variable as referenced */
302 /* Variable is located at the current SP */
306 /* Non-initialized local variable. Just keep track of
309 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
314 /* Static local variables. */
315 *SC = (*SC & ~SC_AUTO) | SC_STATIC;
317 /* Put them into the BSS */
320 /* Define the variable label */
321 SymData = GetLocalLabel ();
322 g_defdatalabel (SymData);
324 /* Reserve space for the data */
327 /* Allow assignments */
328 if (CurTok.Tok == TOK_ASSIGN) {
337 /* Switch to read only data */
340 /* Define a label for the initialization data */
341 InitLabel = GetLocalLabel ();
342 g_defdatalabel (InitLabel);
344 /* Parse the initialization generating a memory image of the
345 * data in the RODATA segment.
347 ParseInit (Decl->Type);
349 /* Generate code to copy this data into the variable space */
350 g_initstatic (InitLabel, SymData, Size);
354 /* Setup the type flags for the assignment */
355 Flags = (Size == SIZEOF_CHAR)? CF_FORCECHAR : CF_NONE;
357 /* Get the expression into the primary */
358 if (evalexpr (Flags, hie1, &lval) == 0) {
359 /* Constant expression. Adjust the types */
360 assignadjust (Decl->Type, &lval);
362 /* Load it into the primary */
363 exprhs (Flags, 0, &lval);
365 /* Expression is not constant and in the primary */
366 assignadjust (Decl->Type, &lval);
369 /* Store the value into the variable */
370 g_putstatic (Flags | TypeOf (Decl->Type), SymData, 0);
374 /* Mark the variable as referenced */
379 /* Cannot allocate a variable of zero size */
381 Error ("Variable `%s' has unknown size", Decl->Ident);
384 /* Return the symbol data */
390 static unsigned ParseStaticDecl (Declaration* Decl, unsigned* SC)
391 /* Parse the declaration of a static variable. The function returns the symbol
392 * data, which is the asm label of the variable.
397 /* Get the size of the variable */
398 unsigned Size = SizeOf (Decl->Type);
401 if (CurTok.Tok == TOK_ASSIGN) {
403 /* Initialization ahead, switch to data segment */
404 if (IsQualConst (Decl->Type)) {
410 /* Define the variable label */
411 SymData = GetLocalLabel ();
412 g_defdatalabel (SymData);
417 /* Allow initialization of static vars */
418 ParseInit (Decl->Type);
420 /* If the previous size has been unknown, it must be known now */
422 Size = SizeOf (Decl->Type);
425 /* Mark the variable as referenced */
430 /* Uninitialized data, use BSS segment */
433 /* Define the variable label */
434 SymData = GetLocalLabel ();
435 g_defdatalabel (SymData);
437 /* Reserve space for the data */
442 /* Cannot allocate a variable of zero size */
444 Error ("Variable `%s' has unknown size", Decl->Ident);
447 /* Return the symbol data */
453 static void ParseOneDecl (const DeclSpec* Spec)
454 /* Parse one variable declaration */
456 unsigned SC; /* Storage class for symbol */
457 unsigned SymData = 0; /* Symbol data (offset, label name, ...) */
458 Declaration Decl; /* Declaration data structure */
459 SymEntry* Sym; /* Symbol declared */
462 /* Remember the storage class for the new symbol */
463 SC = Spec->StorageClass;
465 /* Read the declaration */
466 ParseDecl (Spec, &Decl, DM_NEED_IDENT);
468 /* Set the correct storage class for functions */
469 if (IsTypeFunc (Decl.Type)) {
470 /* Function prototypes are always external */
471 if ((SC & SC_EXTERN) == 0) {
472 Warning ("Function must be extern");
474 SC |= SC_FUNC | SC_EXTERN;
478 /* If we don't have a name, this was flagged as an error earlier.
479 * To avoid problems later, use an anonymous name here.
481 if (Decl.Ident[0] == '\0') {
482 AnonName (Decl.Ident, "param");
485 /* Handle anything that needs storage (no functions, no typdefs) */
486 if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
488 /* If we have a register variable, try to allocate a register and
489 * convert the declaration to "auto" if this is not possible.
491 int Reg = 0; /* Initialize to avoid gcc complains */
492 if ((SC & SC_REGISTER) != 0 && (Reg = AllocRegVar (Decl.Type)) < 0) {
493 /* No space for this register variable, convert to auto */
494 SC = (SC & ~SC_REGISTER) | SC_AUTO;
497 /* Check the variable type */
498 if (SC & SC_REGISTER) {
499 /* Register variable */
500 SymData = ParseRegisterDecl (&Decl, &SC, Reg);
501 } else if (SC & SC_AUTO) {
503 SymData = ParseAutoDecl (&Decl, &SC);
504 } else if (SC & SC_STATIC) {
505 /* Static variable */
506 SymData = ParseStaticDecl (&Decl, &SC);
508 Internal ("Invalid storage class in ParseOneDecl: %04X", SC);
512 /* If the symbol is not marked as external, it will be defined now */
513 if ((SC & SC_EXTERN) == 0) {
517 /* Add the symbol to the symbol table */
518 Sym = AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
520 /* If we had declared a register variable, remember it now */
521 if (SC & SC_REGISTER) {
522 RememberRegVar (Sym);
528 void DeclareLocals (void)
529 /* Declare local variables and types. */
531 /* Remember the current stack pointer */
532 int InitialStack = oursp;
534 /* Loop until we don't find any more variables */
537 /* Check variable declarations. We need to distinguish between a
538 * default int type and the end of variable declarations. So we
539 * will do the following: If there is no explicit storage class
540 * specifier *and* no explicit type given, it is assume that we
541 * have reached the end of declarations.
544 ParseDeclSpec (&Spec, SC_AUTO, T_INT);
545 if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
549 /* Accept type only declarations */
550 if (CurTok.Tok == TOK_SEMI) {
551 /* Type declaration only */
552 CheckEmptyDecl (&Spec);
557 /* Parse a comma separated variable list */
560 /* Parse one declaration */
561 ParseOneDecl (&Spec);
563 /* Check if there is more */
564 if (CurTok.Tok == TOK_COMMA) {
573 /* A semicolon must follow */
577 /* Be sure to allocate any reserved space for locals */
578 F_AllocLocalSpace (CurrentFunc);
580 /* In case we've allocated local variables in this block, emit a call to
581 * the stack checking routine if stack checks are enabled.
583 if (CheckStack && InitialStack != oursp) {
590 void RestoreRegVars (int HaveResult)
591 /* Restore the register variables for the local function if there are any.
592 * The parameter tells us if there is a return value in ax, in that case,
593 * the accumulator must be saved across the restore.
599 /* If we don't have register variables in this function, bail out early */
600 if (RegSymCount == 0) {
604 /* Save the accumulator if needed */
605 if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
606 g_save (CF_CHAR | CF_FORCECHAR);
609 /* Walk through all variables. If there are several variables in a row
610 * (that is, with increasing stack offset), restore them in one chunk.
613 while (I < RegSymCount) {
615 /* Check for more than one variable */
616 const SymEntry* Sym = RegSyms[I];
617 Offs = Sym->V.R.SaveOffs;
618 Bytes = CheckedSizeOf (Sym->Type);
621 while (J < RegSymCount) {
623 /* Get the next symbol */
624 const SymEntry* NextSym = RegSyms [J];
627 int Size = CheckedSizeOf (NextSym->Type);
629 /* Adjacent variable? */
630 if (NextSym->V.R.SaveOffs + Size != Offs) {
635 /* Adjacent variable */
642 /* Restore the memory range */
643 g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
649 /* Restore the accumulator if needed */
650 if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
651 g_restore (CF_CHAR | CF_FORCECHAR);