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