]> git.sur5r.net Git - cc65/blob - src/cc65/function.c
edf795b8d6bb514bf314b995d8fdee5859f02597
[cc65] / src / cc65 / function.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                function.c                                 */
4 /*                                                                           */
5 /*                      Parse function entry/body/exit                       */
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 "check.h"
38 #include "xmalloc.h"
39
40 /* cc65 */
41 #include "asmcode.h"
42 #include "asmlabel.h"
43 #include "codegen.h"
44 #include "error.h"
45 #include "funcdesc.h"
46 #include "global.h"
47 #include "litpool.h"
48 #include "locals.h"
49 #include "scanner.h"
50 #include "segments.h"
51 #include "stmt.h"
52 #include "symtab.h"
53 #include "function.h"
54
55
56
57 /*****************************************************************************/
58 /*                                   Data                                    */
59 /*****************************************************************************/
60
61
62
63 /* Maximum register variable size */
64 #define MAX_REG_SPACE   6
65
66 /* Structure that holds all data needed for function activation */
67 struct Function {
68     struct SymEntry*    FuncEntry;      /* Symbol table entry */
69     type*               ReturnType;     /* Function return type */
70     struct FuncDesc*    Desc;           /* Function descriptor */
71     int                 Reserved;       /* Reserved local space */
72     unsigned            RetLab;         /* Return code label */
73     int                 TopLevelSP;     /* SP at function top level */
74     unsigned            RegOffs;        /* Register variable space offset */
75 };
76
77 /* Pointer to current function */
78 Function* CurrentFunc = 0;
79
80
81
82 /*****************************************************************************/
83 /*                 Subroutines working with struct Function                  */
84 /*****************************************************************************/
85
86
87
88 static Function* NewFunction (struct SymEntry* Sym)
89 /* Create a new function activation structure and return it */
90 {
91     /* Allocate a new structure */
92     Function* F = (Function*) xmalloc (sizeof (Function));
93
94     /* Initialize the fields */
95     F->FuncEntry  = Sym;
96     F->ReturnType = GetFuncReturn (Sym->Type);
97     F->Desc       = (FuncDesc*) DecodePtr (Sym->Type + 1);
98     F->Reserved   = 0;
99     F->RetLab     = GetLocalLabel ();
100     F->TopLevelSP = 0;
101     F->RegOffs    = MAX_REG_SPACE;
102
103     /* Return the new structure */
104     return F;
105 }
106
107
108
109 static void FreeFunction (Function* F)
110 /* Free a function activation structure */
111 {
112     xfree (F);
113 }
114
115
116
117 const char* F_GetFuncName (const Function* F)
118 /* Return the name of the current function */
119 {
120     return F->FuncEntry->Name;
121 }
122
123
124
125 unsigned F_GetParamCount (const Function* F)
126 /* Return the parameter count for the current function */
127 {
128     return F->Desc->ParamCount;
129 }
130
131
132
133 unsigned F_GetParamSize (const Function* F)
134 /* Return the parameter size for the current function */
135 {
136     return F->Desc->ParamSize;
137 }
138
139
140
141 type* F_GetReturnType (Function* F)
142 /* Get the return type for the function */
143 {
144     return F->ReturnType;
145 }
146
147
148
149 int F_HasVoidReturn (const Function* F)
150 /* Return true if the function does not have a return value */
151 {
152     return IsTypeVoid (F->ReturnType);
153 }
154
155
156
157 int F_IsVariadic (const Function* F)
158 /* Return true if this is a variadic function */
159 {
160     return (F->Desc->Flags & FD_VARIADIC) != 0;
161 }
162
163
164
165 int F_IsOldStyle (const Function* F)
166 /* Return true if this is an old style (K&R) function */
167 {
168     return (F->Desc->Flags & FD_OLDSTYLE) != 0;
169 }
170
171
172
173 int F_HasOldStyleIntRet (const Function* F)
174 /* Return true if this is an old style (K&R) function with an implicit int return */
175 {
176     return (F->Desc->Flags & FD_OLDSTYLE_INTRET) != 0;
177 }
178
179
180
181 unsigned F_GetRetLab (const Function* F)
182 /* Return the return jump label */
183 {
184     return F->RetLab;
185 }
186
187
188
189 int F_GetTopLevelSP (const Function* F)
190 /* Get the value of the stack pointer on function top level */
191 {
192     return F->TopLevelSP;
193 }
194
195
196
197 int F_ReserveLocalSpace (Function* F, unsigned Size)
198 /* Reserve (but don't allocate) the given local space and return the stack
199  * offset.
200  */
201 {
202     F->Reserved += Size;
203     return oursp - F->Reserved;
204 }
205
206
207
208 void F_AllocLocalSpace (Function* F)
209 /* Allocate any local space previously reserved. The function will do
210  * nothing if there is no reserved local space.
211  */
212 {
213     if (F->Reserved > 0) {
214
215         /* Create space on the stack */
216         g_space (F->Reserved);
217
218         /* Correct the stack pointer */
219         oursp -= F->Reserved;
220
221         /* Nothing more reserved */
222         F->Reserved = 0;
223     }
224 }
225
226
227
228 int F_AllocRegVar (Function* F, const type* Type)
229 /* Allocate a register variable for the given variable type. If the allocation
230  * was successful, return the offset of the register variable in the register
231  * bank (zero page storage). If there is no register space left, return -1.
232  */
233 {
234     /* Allow register variables only on top level and if enabled */
235     if (EnableRegVars && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
236
237         /* Get the size of the variable */
238         unsigned Size = CheckedSizeOf (Type);
239
240         /* Do we have space left? */
241         if (F->RegOffs >= Size) {
242             /* Space left. We allocate the variables from high to low addresses,
243              * so the adressing is compatible with the saved values on stack.
244              * This allows shorter code when saving/restoring the variables.
245              */
246             F->RegOffs -= Size;
247             return F->RegOffs;
248         }
249     }
250
251     /* No space left or no allocation */
252     return -1;
253 }
254
255
256
257 static void F_RestoreRegVars (Function* F)
258 /* Restore the register variables for the local function if there are any. */
259 {
260     const SymEntry* Sym;
261
262     /* If we don't have register variables in this function, bail out early */
263     if (F->RegOffs == MAX_REG_SPACE) {
264         return;
265     }
266
267     /* Save the accumulator if needed */
268     if (!F_HasVoidReturn (F)) {
269         g_save (CF_CHAR | CF_FORCECHAR);
270     }
271
272     /* Get the first symbol from the function symbol table */
273     Sym = F->FuncEntry->V.F.Func->SymTab->SymHead;
274
275     /* Walk through all symbols checking for register variables */
276     while (Sym) {
277         if (SymIsRegVar (Sym)) {
278
279             /* Check for more than one variable */
280             int Offs       = Sym->V.R.SaveOffs;
281             unsigned Bytes = CheckedSizeOf (Sym->Type);
282
283             while (1) {
284
285                 /* Find next register variable */
286                 const SymEntry* NextSym = Sym->NextSym;
287                 while (NextSym && !SymIsRegVar (NextSym)) {
288                     NextSym = NextSym->NextSym;
289                 }
290
291                 /* If we have a next one, compare the stack offsets */
292                 if (NextSym) {
293
294                     /* We have a following register variable. Get the size */
295                     int Size = CheckedSizeOf (NextSym->Type);
296
297                     /* Adjacent variable? */
298                     if (NextSym->V.R.SaveOffs + Size != Offs) {
299                         /* No */
300                         break;
301                     }
302
303                     /* Adjacent variable */
304                     Bytes += Size;
305                     Offs  -= Size;
306                     Sym   = NextSym;
307
308                 } else {
309                     break;
310                 }
311             }
312
313             /* Restore the memory range */
314             g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
315
316         }
317
318         /* Check next symbol */
319         Sym = Sym->NextSym;
320     }
321
322     /* Restore the accumulator if needed */
323     if (!F_HasVoidReturn (F)) {
324         g_restore (CF_CHAR | CF_FORCECHAR);
325     }
326 }
327
328
329
330 /*****************************************************************************/
331 /*                                   code                                    */
332 /*****************************************************************************/
333
334
335
336 void NewFunc (SymEntry* Func)
337 /* Parse argument declarations and function body. */
338 {
339     int HadReturn;
340     SymEntry* LastParam;
341     SymEntry* Param;
342
343     /* Get the function descriptor from the function entry */
344     FuncDesc* D = Func->V.F.Func;
345
346     /* Allocate the function activation record for the function */
347     CurrentFunc = NewFunction (Func);
348
349     /* Reenter the lexical level */
350     ReenterFunctionLevel (D);
351
352     /* Before adding more symbols, remember the last parameter for later */
353     LastParam = D->SymTab->SymTail;
354
355     /* Declare two special functions symbols: __fixargs__ and __argsize__.
356      * The latter is different depending on the type of the function (variadic
357      * or not).
358      */
359     AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
360     if (D->Flags & FD_VARIADIC) {
361         /* Variadic function. The variable must be const. */
362         static const type T [] = { T_UCHAR | T_QUAL_CONST, T_END };
363         AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
364     } else {
365         /* Non variadic */
366         AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
367     }
368
369     /* Function body now defined */
370     Func->Flags |= SC_DEF;
371
372     /* Allocate code and data segments for this function */
373     Func->V.F.Seg = PushSegments (Func);
374
375     /* If this is a fastcall function, push the last parameter onto the stack */
376     if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
377
378         unsigned Flags;
379
380         /* Fastcall functions may never have an ellipsis or the compiler is buggy */
381         CHECK ((D->Flags & FD_VARIADIC) == 0);
382
383         /* Generate the push */
384         if (IsTypeFunc (LastParam->Type)) {
385             /* Pointer to function */
386             Flags = CF_PTR;
387         } else {
388             Flags = TypeOf (LastParam->Type) | CF_FORCECHAR;
389         }
390         g_push (Flags, 0);
391     }
392
393     /* Generate function entry code if needed */
394     g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
395
396     /* If stack checking code is requested, emit a call to the helper routine */
397     if (CheckStack) {
398         g_stackcheck ();
399     }
400
401     /* Walk through the parameter list and allocate register variable space
402      * for parameters declared as register. Generate code to swap the contents
403      * of the register bank with the save area on the stack.
404      */
405     Param = D->SymTab->SymHead;
406     while (Param && (Param->Flags & SC_PARAM) != 0) {
407
408         /* Check for a register variable */
409         if (SymIsRegVar (Param)) {
410
411             /* Allocate space */
412             int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
413
414             /* Could we allocate a register? */
415             if (Reg < 0) {
416                 /* No register available: Convert parameter to auto */
417                 CvtRegVarToAuto (Param);
418             } else {
419                 /* Remember the register offset */
420                 Param->V.R.RegOffs = Reg;
421
422                 /* Generate swap code */
423                 g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
424
425             }
426         }
427
428         /* Next parameter */
429         Param = Param->NextSym;
430     }
431
432     /* Setup the stack */
433     oursp = 0;
434
435     /* Need a starting curly brace */
436     ConsumeLCurly ();
437
438     /* Parse local variable declarations if any */
439     DeclareLocals ();
440
441     /* Remember the current stack pointer. All variables allocated elsewhere
442      * must be dropped when doing a return from an inner block.
443      */
444     CurrentFunc->TopLevelSP = oursp;
445
446     /* Now process statements in this block */
447     HadReturn = 0;
448     while (CurTok.Tok != TOK_RCURLY) {
449         if (CurTok.Tok != TOK_CEOF) {
450             HadReturn = Statement (0);
451         } else {
452             break;
453         }
454     }
455
456     /* Output the function exit code label */
457     g_defcodelabel (F_GetRetLab (CurrentFunc));
458
459     /* Restore the register variables */
460     F_RestoreRegVars (CurrentFunc);
461
462     /* Generate the exit code */
463     g_leave ();
464
465     /* Eat the closing brace */
466     ConsumeRCurly ();
467
468     /* Emit references to imports/exports */
469     EmitExternals ();
470
471     /* Leave the lexical level */
472     LeaveFunctionLevel ();
473
474     /* Switch back to the old segments */
475     PopSegments ();
476
477     /* Reset the current function pointer */
478     FreeFunction (CurrentFunc);
479     CurrentFunc = 0;
480 }
481
482
483