]> git.sur5r.net Git - cc65/blob - src/cc65/locals.c
fbb054ea5002d1f872f5f1c08564e6fb1f2af29f
[cc65] / src / cc65 / locals.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 locals.c                                  */
4 /*                                                                           */
5 /*              Local variable handling for the cc65 C compiler              */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 /* common */
37 #include "xmalloc.h"
38 #include "xsprintf.h"
39
40 /* cc65 */
41 #include "anonname.h"
42 #include "asmlabel.h"
43 #include "codegen.h"
44 #include "declare.h"
45 #include "error.h"
46 #include "expr.h"
47 #include "function.h"
48 #include "global.h"
49 #include "symtab.h"
50 #include "locals.h"
51
52
53
54 /*****************************************************************************/
55 /*                                   Data                                    */
56 /*****************************************************************************/
57
58
59
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 */
65
66
67
68 /*****************************************************************************/
69 /*                                   Code                                    */
70 /*****************************************************************************/
71
72
73
74 void InitRegVars (void)
75 /* Initialize register variable control data */
76 {
77     /* If the register space is zero, bail out */
78     if (MaxRegSpace == 0) {
79         return;
80     }
81
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
85      * grow the array.
86      */
87     RegSyms = (const SymEntry**) xmalloc (MaxRegSpace * sizeof (RegSyms[0]));
88     RegOffs = MaxRegSpace;
89 }
90
91
92
93 void DoneRegVars (void)
94 /* Free the register variables */
95 {
96     xfree (RegSyms);
97     RegSyms = 0;
98     RegOffs = MaxRegSpace;
99     RegSymCount = 0;
100 }
101
102
103
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,
108  * return -1.
109  */
110 {
111     /* Maybe register variables are disabled... */
112     if (EnableRegVars) {
113
114         /* Get the size of the variable */
115         unsigned Size = CheckedSizeOf (tarray);
116
117         /* Do we have space left? */
118         if (RegOffs >= Size) {
119
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.
123              */
124             RegOffs -= Size;
125             RegSyms [RegSymCount++] = Sym;
126             return RegOffs;
127         }
128     }
129
130     /* No space left or no allocation */
131     return -1;
132 }
133
134
135
136 static unsigned ParseAutoDecl (Declaration* Decl, unsigned Size, 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
139  * static variables.
140  */
141 {
142     unsigned Flags;
143     unsigned SymData;
144     unsigned InitLabel;
145
146     /* Determine if this is a compound variable */
147     int IsCompound = IsClassStruct (Decl->Type) || IsTypeArray (Decl->Type);
148
149     /* Check if this is a variable on the stack or in static memory */
150     if (StaticLocals == 0) {
151
152         /* Change SC in case it was register */
153         *SC = (*SC & ~SC_REGISTER) | SC_AUTO;
154         if (CurTok.Tok == TOK_ASSIGN) {
155
156             ExprDesc lval;
157
158             /* Skip the '=' */
159             NextToken ();
160
161             /* Special handling for compound types */
162             if (IsCompound) {
163
164                 /* First reserve space for the variable */
165                 SymData = F_ReserveLocalSpace (CurrentFunc, Size);
166
167                 /* Next, allocate the space on the stack. This means that the
168                  * variable is now located at offset 0 from the current sp.
169                  */
170                 F_AllocLocalSpace (CurrentFunc);
171
172                 /* Switch to read only data */
173                 g_userodata ();
174
175                 /* Define a label for the initialization data */
176                 InitLabel = GetLocalLabel ();
177                 g_defdatalabel (InitLabel);
178
179                 /* Parse the initialization generating a memory image of the
180                  * data in the RODATA segment.
181                  */
182                 ParseInit (Decl->Type);
183
184                 /* Generate code to copy this data into the variable space */
185                 g_initauto (InitLabel, Size);
186
187             } else {
188
189                 /* Allocate previously reserved local space */
190                 F_AllocLocalSpace (CurrentFunc);
191
192                 /* Setup the type flags for the assignment */
193                 Flags = (Size == 1)? CF_FORCECHAR : CF_NONE;
194
195                 /* Get the expression into the primary */
196                 if (evalexpr (Flags, hie1, &lval) == 0) {
197                     /* Constant expression. Adjust the types */
198                     assignadjust (Decl->Type, &lval);
199                     Flags |= CF_CONST;
200                 } else {
201                     /* Expression is not constant and in the primary */
202                     assignadjust (Decl->Type, &lval);
203                 }
204
205                 /* Push the value */
206                 g_push (Flags | TypeOf (Decl->Type), lval.ConstVal);
207
208             }
209
210             /* Mark the variable as referenced */
211             *SC |= SC_REF;
212
213             /* Variable is located at the current SP */
214             SymData = oursp;
215
216         } else {
217             /* Non-initialized local variable. Just keep track of
218              * the space needed.
219              */
220             SymData = F_ReserveLocalSpace (CurrentFunc, Size);
221         }
222
223     } else {
224
225         /* Static local variables. */
226         *SC = (*SC & ~(SC_REGISTER | SC_AUTO)) | SC_STATIC;
227
228         /* Put them into the BSS */
229         g_usebss ();
230
231         /* Define the variable label */
232         SymData = GetLocalLabel ();
233         g_defdatalabel (SymData);
234
235         /* Reserve space for the data */
236         g_res (Size);
237
238         /* Allow assignments */
239         if (CurTok.Tok == TOK_ASSIGN) {
240
241             ExprDesc lval;
242
243             /* Skip the '=' */
244             NextToken ();
245
246             if (IsCompound) {
247
248                 /* Switch to read only data */
249                 g_userodata ();
250
251                 /* Define a label for the initialization data */
252                 InitLabel = GetLocalLabel ();
253                 g_defdatalabel (InitLabel);
254
255                 /* Parse the initialization generating a memory image of the
256                  * data in the RODATA segment.
257                  */
258                 ParseInit (Decl->Type);
259
260                 /* Generate code to copy this data into the variable space */
261                 g_initstatic (InitLabel, SymData, Size);
262
263             } else {
264
265                 /* Setup the type flags for the assignment */
266                 Flags = (Size == 1)? CF_FORCECHAR : CF_NONE;
267
268                 /* Get the expression into the primary */
269                 if (evalexpr (Flags, hie1, &lval) == 0) {
270                     /* Constant expression. Adjust the types */
271                     assignadjust (Decl->Type, &lval);
272                     Flags |= CF_CONST;
273                     /* Load it into the primary */
274                     exprhs (Flags, 0, &lval);
275                 } else {
276                     /* Expression is not constant and in the primary */
277                     assignadjust (Decl->Type, &lval);
278                 }
279
280                 /* Store the value into the variable */
281                 g_putstatic (Flags | TypeOf (Decl->Type), SymData, 0);
282
283             }
284
285             /* Mark the variable as referenced */
286             *SC |= SC_REF;
287         }
288     }
289
290     /* Return the symbol data */
291     return SymData;
292 }
293
294
295
296 static unsigned ParseStaticDecl (Declaration* Decl, unsigned Size, unsigned* SC)
297 /* Parse the declaration of a static variable. The function returns the symbol
298  * data, which is the asm label of the variable.
299  */
300 {
301     unsigned SymData;
302
303     /* Static data */
304     if (CurTok.Tok == TOK_ASSIGN) {
305
306         /* Initialization ahead, switch to data segment */
307         if (IsQualConst (Decl->Type)) {
308             g_userodata ();
309         } else {
310             g_usedata ();
311         }
312
313         /* Define the variable label */
314         SymData = GetLocalLabel ();
315         g_defdatalabel (SymData);
316
317         /* Skip the '=' */
318         NextToken ();
319
320         /* Allow initialization of static vars */
321         ParseInit (Decl->Type);
322
323         /* If the previous size has been unknown, it must be known now */
324         if (Size == 0) {
325             Size = SizeOf (Decl->Type);
326         }
327
328         /* Mark the variable as referenced */
329         *SC |= SC_REF;
330
331     } else {
332
333         /* Uninitialized data, use BSS segment */
334         g_usebss ();
335
336         /* Define the variable label */
337         SymData = GetLocalLabel ();
338         g_defdatalabel (SymData);
339
340         /* Reserve space for the data */
341         g_res (Size);
342
343     }
344
345     /* Return the symbol data */
346     return SymData;
347 }
348
349
350
351 static void ParseOneDecl (const DeclSpec* Spec)
352 /* Parse one variable declaration */
353 {
354     unsigned    SC;             /* Storage class for symbol */
355     unsigned    Size;           /* Size of the data object */
356     unsigned    SymData = 0;    /* Symbol data (offset, label name, ...) */
357     Declaration Decl;           /* Declaration data structure */
358
359     /* Remember the storage class for the new symbol */
360     SC = Spec->StorageClass;
361
362     /* Read the declaration */
363     ParseDecl (Spec, &Decl, DM_NEED_IDENT);
364
365     /* Set the correct storage class for functions */
366     if (IsTypeFunc (Decl.Type)) {
367         /* Function prototypes are always external */
368         if ((SC & SC_EXTERN) == 0) {
369             Warning ("Function must be extern");
370         }
371         SC |= SC_FUNC | SC_EXTERN;
372
373     }
374
375     /* If we don't have a name, this was flagged as an error earlier.
376      * To avoid problems later, use an anonymous name here.
377      */
378     if (Decl.Ident[0] == '\0') {
379         AnonName (Decl.Ident, "param");
380     }
381
382     /* Handle anything that needs storage (no functions, no typdefs) */
383     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
384
385         /* Get the size of the variable */
386         Size = SizeOf (Decl.Type);
387
388         /* */
389         if (SC & (SC_AUTO | SC_REGISTER)) {
390
391             /* Auto variable */
392             SymData = ParseAutoDecl (&Decl, Size, &SC);
393
394         } else if ((SC & SC_STATIC) == SC_STATIC) {
395
396             /* Static variable */
397             SymData = ParseStaticDecl (&Decl, Size, &SC);
398
399         }
400
401         /* Cannot allocate a variable of zero size */
402         if (Size == 0) {
403             Error ("Variable `%s' has unknown size", Decl.Ident);
404             return;
405         }
406     }
407
408     /* If the symbol is not marked as external, it will be defined */
409     if ((SC & SC_EXTERN) == 0) {
410         SC |= SC_DEF;
411     }
412
413     /* Add the symbol to the symbol table */
414     AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
415 }
416
417
418
419 void DeclareLocals (void)
420 /* Declare local variables and types. */
421 {
422     /* Remember the current stack pointer */
423     int InitialStack = oursp;
424
425     /* Loop until we don't find any more variables */
426     while (1) {
427
428         /* Check variable declarations. We need to distinguish between a
429          * default int type and the end of variable declarations. So we
430          * will do the following: If there is no explicit storage class
431          * specifier *and* no explicit type given, it is assume that we
432          * have reached the end of declarations.
433          */
434         DeclSpec Spec;
435         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
436         if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
437             break;
438         }
439
440         /* Accept type only declarations */
441         if (CurTok.Tok == TOK_SEMI) {
442             /* Type declaration only */
443             CheckEmptyDecl (&Spec);
444             NextToken ();
445             continue;
446         }
447
448         /* Parse a comma separated variable list */
449         while (1) {
450
451             /* Parse one declaration */
452             ParseOneDecl (&Spec);
453
454             /* Check if there is more */
455             if (CurTok.Tok == TOK_COMMA) {
456                 /* More to come */
457                 NextToken ();
458             } else {
459                 /* Done */
460                 break;
461             }
462         }
463
464         /* A semicolon must follow */
465         ConsumeSemi ();
466     }
467
468     /* Be sure to allocate any reserved space for locals */
469     F_AllocLocalSpace (CurrentFunc);
470
471     /* In case we've allocated local variables in this block, emit a call to
472      * the stack checking routine if stack checks are enabled.
473      */
474     if (CheckStack && InitialStack != oursp) {
475         g_cstackcheck ();
476     }
477 }
478
479
480
481 void RestoreRegVars (int HaveResult)
482 /* Restore the register variables for the local function if there are any.
483  * The parameter tells us if there is a return value in ax, in that case,
484  * the accumulator must be saved across the restore.
485  */
486 {
487     unsigned I, J;
488     int Bytes, Offs;
489
490     /* If we don't have register variables in this function, bail out early */
491     if (RegSymCount == 0) {
492         return;
493     }
494
495     /* Save the accumulator if needed */
496     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
497         g_save (CF_CHAR | CF_FORCECHAR);
498     }
499
500     /* Walk through all variables. If there are several variables in a row
501      * (that is, with increasing stack offset), restore them in one chunk.
502      */
503     I = 0;
504     while (I < RegSymCount) {
505
506         /* Check for more than one variable */
507         const SymEntry* Sym = RegSyms[I];
508         Offs  = Sym->V.Offs;
509         Bytes = CheckedSizeOf (Sym->Type);
510         J = I+1;
511
512         while (J < RegSymCount) {
513
514             /* Get the next symbol */
515             const SymEntry* NextSym = RegSyms [J];
516
517             /* Get the size */
518             int Size = CheckedSizeOf (NextSym->Type);
519
520             /* Adjacent variable? */
521             if (NextSym->V.Offs + Size != Offs) {
522                 /* No */
523                 break;
524             }
525
526             /* Adjacent variable */
527             Bytes += Size;
528             Offs  -= Size;
529             Sym   = NextSym;
530             ++J;
531         }
532
533         /* Restore the memory range */
534         g_restore_regvars (Offs, Sym->V.Offs, Bytes);
535
536         /* Next round */
537         I = J;
538     }
539
540     /* Restore the accumulator if needed */
541     if (!F_HasVoidReturn (CurrentFunc) && HaveResult) {
542         g_restore (CF_CHAR | CF_FORCECHAR);
543     }
544 }
545
546
547