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