]> git.sur5r.net Git - cc65/blob - src/cc65/locals.c
1649edcbedf98c50d3bae78f9a3d0b35e39d74e7
[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     Ullrich von Bassewitz                                        */
10 /*              Wacholderweg 14                                              */
11 /*              D-70597 Stuttgart                                            */
12 /* EMail:       uz@musoftware.de                                             */
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 #include "../common/xmalloc.h"
37
38 #include "anonname.h"
39 #include "asmlabel.h"
40 #include "codegen.h"
41 #include "declare.h"
42 #include "error.h"
43 #include "expr.h"
44 #include "function.h"
45 #include "global.h"
46 #include "symtab.h"
47 #include "locals.h"
48
49
50
51 /*****************************************************************************/
52 /*                                   Data                                    */
53 /*****************************************************************************/
54
55
56
57 /* Register variable management */
58 unsigned MaxRegSpace            = 6;    /* Maximum space available */
59 static unsigned RegOffs         = 0;    /* Offset into register space */
60 static const SymEntry** RegSyms = 0;    /* The register variables */
61 static unsigned RegSymCount     = 0;    /* Number of register variables */
62
63
64
65 /*****************************************************************************/
66 /*                                   Code                                    */
67 /*****************************************************************************/
68
69
70
71 void InitRegVars (void)
72 /* Initialize register variable control data */
73 {
74     /* If the register space is zero, bail out */
75     if (MaxRegSpace == 0) {
76         return;
77     }
78
79     /* The maximum number of register variables is equal to the register
80      * variable space available. So allocate one pointer per byte. This
81      * will usually waste some space but we don't need to dynamically
82      * grow the array.
83      */
84     RegSyms = xmalloc (MaxRegSpace * sizeof (RegSyms[0]));
85     RegOffs = MaxRegSpace;
86 }
87
88
89
90 void DoneRegVars (void)
91 /* Free the register variables */
92 {
93     xfree (RegSyms);
94     RegSyms = 0;
95     RegOffs = MaxRegSpace;
96     RegSymCount = 0;
97 }
98
99
100
101 static int AllocRegVar (const SymEntry* Sym, const type* tarray)
102 /* Allocate a register variable with the given amount of storage. If the
103  * allocation was successful, return the offset of the register variable in
104  * the register bank (zero page storage). If there is no register space left,
105  * return -1.
106  */
107 {
108     /* Maybe register variables are disabled... */
109     if (EnableRegVars) {
110
111         /* Get the size of the variable */
112         unsigned Size = SizeOf (tarray);
113
114         /* Do we have space left? */
115         if (RegOffs >= Size) {
116
117             /* Space left. We allocate the variables from high to low addresses,
118              * so the adressing is compatible with the saved values on stack.
119              * This allows shorter code when saving/restoring the variables.
120              */
121             RegOffs -= Size;
122             RegSyms [RegSymCount++] = Sym;
123             return RegOffs;
124         }
125     }
126
127     /* No space left or no allocation */
128     return -1;
129 }
130
131
132
133 static void ParseOneDecl (const DeclSpec* Spec)
134 /* Parse one variable declaration */
135 {
136     int         Size;           /* Size of an auto variable */
137     int         SC;             /* Storage class for symbol */
138     int         SymData = 0;    /* Symbol data (offset, label name, ...) */
139     unsigned    flags = 0;      /* Code generator flags */
140     Declaration Decl;           /* Declaration data structure */
141
142     /* Remember the storage class for the new symbol */
143     SC = Spec->StorageClass;
144
145     /* Read the declaration */
146     ParseDecl (Spec, &Decl, DM_NEED_IDENT);
147
148     /* Set the correct storage class for functions */
149     if (IsFunc (Decl.Type)) {
150         /* Function prototypes are always external */
151         if ((SC & SC_EXTERN) == 0) {
152             Warning (WARN_FUNC_MUST_BE_EXTERN);
153         }
154         SC |= SC_FUNC | SC_EXTERN;
155
156     }
157
158     /* If we don't have a name, this was flagged as an error earlier.
159      * To avoid problems later, use an anonymous name here.
160      */
161     if (Decl.Ident[0] == '\0') {
162         AnonName (Decl.Ident, "param");
163     }
164
165     /* Handle anything that needs storage (no functions, no typdefs) */
166     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
167
168         /* Get the size of the variable */
169         Size = SizeOf (Decl.Type);
170
171         if (SC & (SC_AUTO | SC_REGISTER)) {
172
173             /* Auto variable */
174             if (StaticLocals == 0) {
175
176                 /* Change SC in case it was register */
177                 SC = (SC & ~SC_REGISTER) | SC_AUTO;
178                 if (curtok == TOK_ASSIGN) {
179
180                     struct expent lval;
181
182                     /* Allocate previously reserved local space */
183                     AllocLocalSpace (CurrentFunc);
184
185                     /* Skip the '=' */
186                     NextToken ();
187
188                     /* Setup the type flags for the assignment */
189                     flags = Size == 1? CF_FORCECHAR : CF_NONE;
190
191                     /* Get the expression into the primary */
192                     if (evalexpr (flags, hie1, &lval) == 0) {
193                         /* Constant expression. Adjust the types */
194                         assignadjust (Decl.Type, &lval);
195                         flags |= CF_CONST;
196                     } else {
197                         /* Expression is not constant and in the primary */
198                         assignadjust (Decl.Type, &lval);
199                     }
200
201                     /* Push the value */
202                     g_push (flags | TypeOf (Decl.Type), lval.e_const);
203
204                     /* Mark the variable as referenced */
205                     SC |= SC_REF;
206
207                     /* Variable is located at the current SP */
208                     SymData = oursp;
209
210                 } else {
211                     /* Non-initialized local variable. Just keep track of
212                      * the space needed.
213                      */
214                     SymData = ReserveLocalSpace (CurrentFunc, Size);
215                 }
216
217             } else {
218
219                 /* Static local variables. */
220                 SC = (SC & ~(SC_REGISTER | SC_AUTO)) | SC_STATIC;
221
222                 /* Put them into the BSS */
223                 g_usebss ();
224
225                 /* Define the variable label */
226                 SymData = GetLabel ();
227                 g_defloclabel (SymData);
228
229                 /* Reserve space for the data */
230                 g_res (Size);
231
232                 /* Allow assignments */
233                 if (curtok == TOK_ASSIGN) {
234
235                     struct expent lval;
236
237                     /* Switch to the code segment. */
238                     g_usecode ();
239
240                     /* Skip the '=' */
241                     NextToken ();
242
243                     /* Get the expression into the primary */
244                     expression1 (&lval);
245
246                     /* Make type adjustments if needed */
247                     assignadjust (Decl.Type, &lval);
248
249                     /* Setup the type flags for the assignment */
250                     flags = TypeOf (Decl.Type);
251                     if (Size == 1) {
252                         flags |= CF_FORCECHAR;
253                     }
254
255                     /* Store the value into the variable */
256                     g_putstatic (flags, SymData, 0);
257
258                     /* Mark the variable as referenced */
259                     SC |= SC_REF;
260                 }
261             }
262
263         } else if ((SC & SC_STATIC) == SC_STATIC) {
264
265             /* Static data */
266             if (curtok == TOK_ASSIGN) {
267
268                 /* Initialization ahead, switch to data segment */
269                 g_usedata ();
270
271                 /* Define the variable label */
272                 SymData = GetLabel ();
273                 g_defloclabel (SymData);
274
275                 /* Skip the '=' */
276                 NextToken ();
277
278                 /* Allow initialization of static vars */
279                 ParseInit (Decl.Type);
280
281                 /* Mark the variable as referenced */
282                 SC |= SC_REF;
283
284             } else {
285
286                 /* Uninitialized data, use BSS segment */
287                 g_usebss ();
288
289                 /* Define the variable label */
290                 SymData = GetLabel ();
291                 g_defloclabel (SymData);
292
293                 /* Reserve space for the data */
294                 g_res (Size);
295
296             }
297         }
298
299     }
300
301     /* If the symbol is not marked as external, it will be defined */
302     if ((SC & SC_EXTERN) == 0) {
303         SC |= SC_DEF;
304     }
305
306     /* Add the symbol to the symbol table */
307     AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
308 }
309
310
311
312 void DeclareLocals (void)
313 /* Declare local variables and types. */
314 {
315     /* Loop until we don't find any more variables */
316     while (1) {
317
318         /* Check variable declarations. We need to distinguish between a
319          * default int type and the end of variable declarations. So we
320          * will do the following: If there is no explicit storage class
321          * specifier *and* no explicit type given, it is assume that we
322          * have reached the end of declarations.
323          */
324         DeclSpec Spec;
325         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
326         if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
327             break;
328         }
329
330         /* Accept type only declarations */
331         if (curtok == TOK_SEMI) {
332             /* Type declaration only */
333             CheckEmptyDecl (&Spec);
334             NextToken ();
335             continue;
336         }
337
338         /* Parse a comma separated variable list */
339         while (1) {
340
341             /* Parse one declaration */
342             ParseOneDecl (&Spec);
343
344             /* Check if there is more */
345             if (curtok == TOK_COMMA) {
346                 /* More to come */
347                 NextToken ();
348             } else {
349                 /* Done */
350                 break;
351             }
352         }
353
354         /* A semicolon must follow */
355         ConsumeSemi ();
356     }
357
358     /* Be sure to allocate any reserved space for locals */
359     AllocLocalSpace (CurrentFunc);
360
361     /* In case we switched away from code segment, switch back now */
362     g_usecode ();
363 }
364
365
366
367 void RestoreRegVars (int HaveResult)
368 /* Restore the register variables for the local function if there are any.
369  * The parameter tells us if there is a return value in ax, in that case,
370  * the accumulator must be saved across the restore.
371  */
372 {
373     unsigned I, J;
374     int Bytes, Offs;
375
376     /* If we don't have register variables in this function, bail out early */
377     if (RegSymCount == 0) {
378         return;
379     }
380
381     /* Save the accumulator if needed */
382     if (!HasVoidReturn (CurrentFunc) && HaveResult) {
383         g_save (CF_CHAR | CF_FORCECHAR);
384     }
385
386     /* Walk through all variables. If there are several variables in a row
387      * (that is, with increasing stack offset), restore them in one chunk.
388      */
389     I = 0;
390     while (I < RegSymCount) {
391
392         /* Check for more than one variable */
393         const SymEntry* Sym = RegSyms[I];
394         Offs  = Sym->V.Offs;
395         Bytes = SizeOf (Sym->Type);
396         J = I+1;
397
398         while (J < RegSymCount) {
399
400             /* Get the next symbol */
401             const SymEntry* NextSym = RegSyms [J];
402
403             /* Get the size */
404             int Size = SizeOf (NextSym->Type);
405
406             /* Adjacent variable? */
407             if (NextSym->V.Offs + Size != Offs) {
408                 /* No */
409                 break;
410             }
411
412             /* Adjacent variable */
413             Bytes += Size;
414             Offs  -= Size;
415             Sym   = NextSym;
416             ++J;
417         }
418
419         /* Restore the memory range */
420         g_restore_regvars (Offs, Sym->V.Offs, Bytes);
421
422         /* Next round */
423         I = J;
424     }
425
426     /* Restore the accumulator if needed */
427     if (!HasVoidReturn (CurrentFunc) && HaveResult) {
428         g_restore (CF_CHAR | CF_FORCECHAR);
429     }
430 }
431
432
433