]> git.sur5r.net Git - cc65/blob - src/cc65/locals.c
Added the lineinfo module. Changed the complete code generation to use the
[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-2001 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 = SizeOf (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 void ParseOneDecl (const DeclSpec* Spec)
137 /* Parse one variable declaration */
138 {
139     int         Size;           /* Size of an auto variable */
140     int         SC;             /* Storage class for symbol */
141     int         SymData = 0;    /* Symbol data (offset, label name, ...) */
142     unsigned    flags = 0;      /* Code generator flags */
143     Declaration Decl;           /* Declaration data structure */
144
145     /* Remember the storage class for the new symbol */
146     SC = Spec->StorageClass;
147
148     /* Read the declaration */
149     ParseDecl (Spec, &Decl, DM_NEED_IDENT);
150
151     /* Set the correct storage class for functions */
152     if (IsTypeFunc (Decl.Type)) {
153         /* Function prototypes are always external */
154         if ((SC & SC_EXTERN) == 0) {
155             Warning ("Function must be extern");
156         }
157         SC |= SC_FUNC | SC_EXTERN;
158
159     }
160
161     /* If we don't have a name, this was flagged as an error earlier.
162      * To avoid problems later, use an anonymous name here.
163      */
164     if (Decl.Ident[0] == '\0') {
165         AnonName (Decl.Ident, "param");
166     }
167
168     /* Handle anything that needs storage (no functions, no typdefs) */
169     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
170
171         /* Get the size of the variable */
172         Size = SizeOf (Decl.Type);
173
174         if (SC & (SC_AUTO | SC_REGISTER)) {
175
176             /* Auto variable */
177             if (StaticLocals == 0) {
178
179                 /* Change SC in case it was register */
180                 SC = (SC & ~SC_REGISTER) | SC_AUTO;
181                 if (CurTok.Tok == TOK_ASSIGN) {
182
183                     struct expent lval;
184
185                     /* Allocate previously reserved local space */
186                     AllocLocalSpace (CurrentFunc);
187
188                     /* Skip the '=' */
189                     NextToken ();
190
191                     /* Setup the type flags for the assignment */
192                     flags = Size == 1? CF_FORCECHAR : CF_NONE;
193
194                     /* Get the expression into the primary */
195                     if (evalexpr (flags, hie1, &lval) == 0) {
196                         /* Constant expression. Adjust the types */
197                         assignadjust (Decl.Type, &lval);
198                         flags |= CF_CONST;
199                     } else {
200                         /* Expression is not constant and in the primary */
201                         assignadjust (Decl.Type, &lval);
202                     }
203
204                     /* Push the value */
205                     g_push (flags | TypeOf (Decl.Type), lval.e_const);
206
207                     /* Mark the variable as referenced */
208                     SC |= SC_REF;
209
210                     /* Variable is located at the current SP */
211                     SymData = oursp;
212
213                 } else {
214                     /* Non-initialized local variable. Just keep track of
215                      * the space needed.
216                      */
217                     SymData = ReserveLocalSpace (CurrentFunc, Size);
218                 }
219
220             } else {
221
222                 /* Static local variables. */
223                 SC = (SC & ~(SC_REGISTER | SC_AUTO)) | SC_STATIC;
224
225                 /* Put them into the BSS */
226                 g_usebss ();
227
228                 /* Define the variable label */
229                 SymData = GetLocalLabel ();
230                 g_defdatalabel (SymData);
231
232                 /* Reserve space for the data */
233                 g_res (Size);
234
235                 /* Allow assignments */
236                 if (CurTok.Tok == TOK_ASSIGN) {
237
238                     struct expent lval;
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 == TOK_ASSIGN) {
267
268                 /* Initialization ahead, switch to data segment */
269                 if (IsQualConst (Decl.Type)) {
270                     g_userodata ();
271                 } else {
272                     g_usedata ();
273                 }
274
275                 /* Define the variable label */
276                 SymData = GetLocalLabel ();
277                 g_defdatalabel (SymData);
278
279                 /* Skip the '=' */
280                 NextToken ();
281
282                 /* Allow initialization of static vars */
283                 ParseInit (Decl.Type);
284
285                 /* Mark the variable as referenced */
286                 SC |= SC_REF;
287
288             } else {
289
290                 /* Uninitialized data, use BSS segment */
291                 g_usebss ();
292
293                 /* Define the variable label */
294                 SymData = GetLocalLabel ();
295                 g_defdatalabel (SymData);
296
297                 /* Reserve space for the data */
298                 g_res (Size);
299
300             }
301         }
302
303     }
304
305     /* If the symbol is not marked as external, it will be defined */
306     if ((SC & SC_EXTERN) == 0) {
307         SC |= SC_DEF;
308     }
309
310     /* Add the symbol to the symbol table */
311     AddLocalSym (Decl.Ident, Decl.Type, SC, SymData);
312 }
313
314
315
316 void DeclareLocals (void)
317 /* Declare local variables and types. */
318 {
319     /* Remember the current stack pointer */
320     int InitialStack = oursp;
321
322     /* Loop until we don't find any more variables */
323     while (1) {
324
325         /* Check variable declarations. We need to distinguish between a
326          * default int type and the end of variable declarations. So we
327          * will do the following: If there is no explicit storage class
328          * specifier *and* no explicit type given, it is assume that we
329          * have reached the end of declarations.
330          */
331         DeclSpec Spec;
332         ParseDeclSpec (&Spec, SC_AUTO, T_INT);
333         if ((Spec.Flags & DS_DEF_STORAGE) != 0 && (Spec.Flags & DS_DEF_TYPE) != 0) {
334             break;
335         }
336
337         /* Accept type only declarations */
338         if (CurTok.Tok == TOK_SEMI) {
339             /* Type declaration only */
340             CheckEmptyDecl (&Spec);
341             NextToken ();
342             continue;
343         }
344
345         /* Parse a comma separated variable list */
346         while (1) {
347
348             /* Parse one declaration */
349             ParseOneDecl (&Spec);
350
351             /* Check if there is more */
352             if (CurTok.Tok == TOK_COMMA) {
353                 /* More to come */
354                 NextToken ();
355             } else {
356                 /* Done */
357                 break;
358             }
359         }
360
361         /* A semicolon must follow */
362         ConsumeSemi ();
363     }
364
365     /* Be sure to allocate any reserved space for locals */
366     AllocLocalSpace (CurrentFunc);
367
368     /* In case we've allocated local variables in this block, emit a call to
369      * the stack checking routine if stack checks are enabled.
370      */
371     if (CheckStack && InitialStack != oursp) {
372         g_cstackcheck ();
373     }
374 }
375
376
377
378 void RestoreRegVars (int HaveResult)
379 /* Restore the register variables for the local function if there are any.
380  * The parameter tells us if there is a return value in ax, in that case,
381  * the accumulator must be saved across the restore.
382  */
383 {
384     unsigned I, J;
385     int Bytes, Offs;
386
387     /* If we don't have register variables in this function, bail out early */
388     if (RegSymCount == 0) {
389         return;
390     }
391
392     /* Save the accumulator if needed */
393     if (!HasVoidReturn (CurrentFunc) && HaveResult) {
394         g_save (CF_CHAR | CF_FORCECHAR);
395     }
396
397     /* Walk through all variables. If there are several variables in a row
398      * (that is, with increasing stack offset), restore them in one chunk.
399      */
400     I = 0;
401     while (I < RegSymCount) {
402
403         /* Check for more than one variable */
404         const SymEntry* Sym = RegSyms[I];
405         Offs  = Sym->V.Offs;
406         Bytes = SizeOf (Sym->Type);
407         J = I+1;
408
409         while (J < RegSymCount) {
410
411             /* Get the next symbol */
412             const SymEntry* NextSym = RegSyms [J];
413
414             /* Get the size */
415             int Size = SizeOf (NextSym->Type);
416
417             /* Adjacent variable? */
418             if (NextSym->V.Offs + Size != Offs) {
419                 /* No */
420                 break;
421             }
422
423             /* Adjacent variable */
424             Bytes += Size;
425             Offs  -= Size;
426             Sym   = NextSym;
427             ++J;
428         }
429
430         /* Restore the memory range */
431         g_restore_regvars (Offs, Sym->V.Offs, Bytes);
432
433         /* Next round */
434         I = J;
435     }
436
437     /* Restore the accumulator if needed */
438     if (!HasVoidReturn (CurrentFunc) && HaveResult) {
439         g_restore (CF_CHAR | CF_FORCECHAR);
440     }
441 }
442
443
444